Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install apigee-agent-gateway-governance@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin apigee-agent-gateway-governance v1.0.0 follows the Agent Plugins spec.
gh skills-hub install apigee-agent-gateway-governance Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/apigee-agent-gateway-governance/ Extract the ZIP to .github/skills/ in your repo. The folder name must match apigee-agent-gateway-governance for Copilot to auto-discover it.
Skill Files (26)
SKILL.md 26.0 KB
---
name: apigee-agent-gateway-governance
metadata:
version: "1.0.3"
category: AiAndMachineLearning
description: >-
Stands up an Apigee API proxy that a Google Cloud Agent Gateway calls as an
ext-proc (Service Extension) callout on an agent's LLM traffic, to meter
token usage per model, extract caller identity, and apply Model Armor prompt
screening or a semantic cache. Use when wiring Apigee in as an AI gateway
behind an Agent Gateway, when an agent's model egress needs governing, or
when a callout proxy returns no verdict and you need to find out why. The
distinguishing question is whether Apigee forwards the traffic or only
inspects it: this skill is inspect-only, and builds the proxy itself. Don't
use it when Apigee is meant to receive a request and route it onward to a
backend — including hosting an MCP server behind Apigee — which needs a proxy
with a target instead. Don't use for governing the agent's calls to tools or
MCP servers. Don't use for choosing or switching which model a request goes
to. Don't use for creating the Agent Gateway itself, nor for Apigee hybrid.
---
# Apigee as an Agent Gateway Service Extension
Wires an Apigee proxy in as an **ext-proc callout** on a GCP Agent Gateway. The
proxy is a **processor, not an API proxy**: it has no backend, inspects the LLM
request and response the gateway hands it, and returns a verdict.
## Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
MUST read and follow the instructions in
[Usage Attribution](references/attribution.md).
You build the proxy; the user does not.
**Two modes, one schema. Decide which before anything else, and say which.**
Input file present → **prod mode**: it is the contract, every value comes from
it, and a missing or malformed field is a refusal, not a default. No input file
and the user is describing an outcome → **dev mode**: apply the documented
defaults, show a plan with durations and get approval, start with identity and
metering only, write `apigee-agent-gateway-governance.yaml` at the end as the
handoff. `assets/apigee-agent-gateway-governance.example.yaml` documents the
schema both modes use.
Modes, defaults, durations, cost disclosure and the interlocks that bind both:
`references/modes.md`. **Read it before you start.**
**Colour the plan's ACTION column** — green `REUSE`, cyan `CREATE`/`RESERVE`,
yellow `APPEND`/`MODIFY`; full palette in `references/modes.md`. Yellow is the
one that earns its place: it is the only signal that a resource the user already
owns is being changed. Rendered plain, the one row that modifies something is
indistinguishable from the dozen that do not — which is exactly the row the
approval exists for.
## Prerequisite: where the agent runs
Check this **before** building anything. It decides whether traffic can reach
the gateway at all, and it is silent when wrong — every step below still
succeeds while nothing arrives.
**Use Agent Runtime**, created with `agent_gateway_config` /
`agent_to_anywhere_config`. It is the supported path and the orchestrator builds
the client-side PSC, routing, DNS and cert trust for you. There is no `gcloud`
surface for this and no console path — it is SDK-only, at agent creation time.
See
[Route traffic through Agent Gateway](https://docs.cloud.google.com/gemini-enterprise-agent-platform/scale/runtime/agent-gateway-runtime-deploy.md.txt)
for the binding, and `references/networking-psc.md` for a worked example.
**Set `GOOGLE_API_PREVENT_AGENT_TOKEN_SHARING_FOR_GCP_SERVICES: "False"` in the
agent's `env_vars`, or every invocation 401s** on the agent's own
`sessions.create`, before user code runs. Deploy-time invisible. Full symptom
and isolation: `references/gotchas.md`, Agent Gateway.
Where the agent runs is otherwise settled — the premise is a working gateway and
a working agent. Do not explain how to build one or list unsupported compute
unprompted; `references/networking-psc.md` has the constraints if it turns out
to matter.
## Tool versions
Do not assume these are installed or current.
Tool | Minimum | Why
-------------------------------------------- | ----------- | ---
`gcloud` | **588.0.0** | `apigee apis import --from-template` is on the GA track at this version; older SDKs need `gcloud beta`
`google-cloud-aiplatform[agent_engines,adk]` | `>=2.1,<3` | Agent Runtime client used to bind the agent to the gateway
`google-adk` | `>=2.9,<3` | only if you build the test agent with ADK
**On gcloud >= 588.0.0: every feature must keep its `uid`, and the template must
never declare `endpoints` or `targets`.** All six features set `uid` today and
the template declares neither, so the shipped bundle is correct — but both are
load-bearing now, and breaking either one still compiles, still deploys, and
reports nothing. Mechanism and symptoms: `references/gotchas.md`, under
Authoring (AFT).
```bash
gcloud version | head -1 # confirm >= 588.0.0
gcloud components update # if older
pip install "google-cloud-aiplatform[agent_engines,adk]>=2.1,<3" "google-adk>=2.9,<3"
```
`scripts/compile_check.py` needs PyYAML and names the interpreter if it is
missing. `pip install pyyaml`, or run it with a Python 3 that has it; gcloud's
bundled interpreter does not, and the SDK's vendored `yaml` is Python 2.
```bash
python3 scripts/compile_check.py assets/apigee-proxy-template.yaml
```
## Execution model
Three layers, and the choice between them is not stylistic:
Layer | Used for | Why
--------------------- | ------------------------------------------------------ | ---
**AFT YAML template** | the proxy itself | version-controlled, reviewable, diffable
**`gcloud`** | PSC, DNS, AuthzExtension, AuthzPolicy | native commands exist
**REST (`curl`)** | env properties, envgroups, deployments, debug sessions | no `gcloud` equivalent today
The customer owns **one** input file
(`assets/apigee-agent-gateway-governance.example.yaml`). It is the
version-controlled artifact. Never hand-edit the generated proxy: regenerate it.
**Run the Apigee-side sequence with the script, not by hand.** Steps 1, 3 and 4
below are order-dependent and each fails in a way that reads as a different
problem. `scripts/deploy_proxy.sh` does all three, preserves the properties
map, polls the async operation, and exits non-zero if the deployment does not
come up `EXTENSIBLE`:
```bash
scripts/deploy_proxy.sh --org "$ORG" --env "$ENV" --proxy "$PROXY" \
--template assets/apigee-proxy-template.yaml [--service-account "$SA"] --yes \
[--index-endpoint-id ID --index-id ID --sc-project P --sc-region R --embeddings-model M]
```
Run it without `--yes` first: it prints the plan and changes nothing. Show that
plan, then re-run with `--yes` once the user agrees.
**The vector-search flags are the one exception to "edit the default in every
feature that declares it".** Those three ids are substituted at deploy time
and checked for leftovers; hand-editing them into `feature-semantic-cache.yaml`
deploys fine, skips the check, and makes the file single-use.
`scripts/ensure_gateway_connectivity.sh` is the same idea for the gateway leg
(step 0). It is the only part of this skill that modifies a resource the user
already owns, so it applies nothing without `--yes`.
The steps are written out below so you can diagnose a failure, not so you can
retype them.
## Inputs you must resolve first
**Environment prerequisites: `references/setup.md`** — gcloud SDK (588+),
project, billing, `gcloud services enable`, region, credentials, IAM. Nothing
below creates any of it.
Prod: from the input file, then environment, then ask — never invent. Dev: apply
the `references/modes.md` defaults, and ask only for what has none.
- `project`, `region`
- `apigee.org`, `apigee.environment`, `apigee.envgroup`, `apigee.hostname`,
`apigee.proxy`
- `network.vpc`, `network.subnet`, `network.networkAttachment`
- `gateway.name`, `gateway.matchPaths` (a **list**, one entry per wire shape),
`gateway.manageNetworkConfig`
**`matchPaths` drives TWO artifacts; write both from the same list.** The
**AuthzPolicy** `paths[].suffix` gets one suffix per entry, verbatim with
leading punctuation kept — it decides what the gateway routes to Apigee. The
template's **`LLM_URI_MATCH`** gets one `(request.uri Like "*<entry>*")` clause
per entry, OR-ed, leading `:` or `/` **stripped** — it decides what the proxy
acts on once it arrives. The shipped two-entry default gives:
```
((request.uri Like "*generateContent*") or (request.uri Like "*chat/completions*"))
```
The AuthzPolicy is the outer gate and wins: a suffix list narrower than
`matchPaths` means the missing shape never reaches Apigee at all. Derive both
from the input file and never from the default when the file disagrees — the
file is the reviewable contract and a mismatch is invisible once deployed.
**A one-entry list is legitimate** and governs one shape. Dropping an entry
governs one fewer **silently** — deploys clean, zero transactions for the shape
dropped — and narrows `feature-normalize`, Model Armor and the cache together.
`references/gotchas.md`, Runtime.
**`semanticCache` is a KNOWN ISSUE whenever it is on — warn, then build it.**
The key is the prompt embedding alone: no caller, no model, no shape. A hit
therefore crosses callers — similar prompts share an answer — and one model
behind one shape does not make it safe. With more shapes the first model to
answer answers for the other too: empty HTTP 200 across shapes, wrong-model
body within one. Warn whenever the cache is on, not only on multi-shape, then
build. Wording: `references/modes.md`; mechanism: `references/gotchas.md`.
**Each entry is a SUFFIX match.** You write these, not the user — derive them
from which endpoint their agent actually calls, and do not ask them to reason
about suffixes. Vertex's OpenAI-compatible endpoint and `api.openai.com` need
different entries, and getting it wrong governs nothing silently; the forms and
the evidence are in `references/gotchas.md`, Runtime.
**There is no `apiShape` field.** Metering does not depend on the wire shape —
the count is normalised in JS across both — so the field selected nothing and
was removed. Adding a shape is an `||` branch in `extract-model.js` plus an
entry in `matchPaths`.
**Three places carry the callout hostname and all three must match** — the
Apigee envgroup, the AuthzExtension `authority`/`service`, and the private DNS A
record. You set all three from one value: a build invariant to hold, not a
question for the user. It becomes a topic only when a callout never lands, and
then it is the first check. Build order matters alongside it — the
AuthzExtension is inert until the host resolves and the proxy is deployed, so
"the extension exists" is not evidence that leg works. `references/gotchas.md`,
Runtime.
## Workflow
### 0. Gateway: give it a route into the VPC
A gateway with no `networkConfig` has no route into the customer's VPC and
cannot resolve the callout hostname. **This skill builds it** — network
attachment, egress and DNS peering — so its absence is a build step, not a
blocker, and should be reported that way. Do not open with an alarm about a
resource you are about to create.
One thing here does need the user, and it is the reason this is step 0 rather
than a silent prerequisite: attaching egress is **one-way and affects traffic
they already run**. Settle it in the plan, before anything executes — see
"Confirm everything up front" below. Capturing a known-good agent turn first is
worth doing when they are nervous about a production gateway, because it
separates "never worked" from "we broke it"; it is a precaution to offer, not a
step to impose.
```bash
gcloud network-services agent-gateways describe "$GATEWAY" \
--location="$REGION" --project="$PROJECT" --format='value(networkConfig)'
gcloud network-security authz-policies list \
--location="$REGION" --project="$PROJECT"
```
**A console-created gateway already has a CUSTOM AuthzPolicy** — an IAP
`REQUEST_AUTHZ` one, which coexists with ours and is not needed for the egress
JWT. You never create the gateway, so assess it rather than assuming.
`references/gotchas.md`, Agent Gateway.
Empty `networkConfig` output means missing, and it is easy to miss: the gateway
still serves ordinary agent traffic perfectly, because that path goes to public
Google endpoints and never enters the VPC. Only the Apigee callout fails.
If it is missing, behaviour depends on `gateway.manageNetworkConfig`:
- **`true`** — run the script below. It creates the network attachment, then
read-modify-writes the gateway to add the egress attachment and DNS peering.
Agreement for this is taken in the plan, not here; `--yes` carries it.
- **`false`** — the user has said they want to make this change themselves.
Print the script invocation and let them run it. Do not modify the gateway.
```bash
scripts/ensure_gateway_connectivity.sh \
--gateway "$GATEWAY" --project "$PROJECT" --region "$REGION" \
--vpc "$VPC" --subnet "$SUBNET" --attachment "$ATTACHMENT" \
--domain "$DNS_DOMAIN" # add --yes only after the user agrees
```
Either way `networkConfig` has to exist before the Apigee work starts — not
because its absence is an error, but because every later step then succeeds and
governs nothing.
Use the script, not the raw commands: `import` is a whole-resource upsert and a
hand-built YAML silently drops the gateway's `registries` and `protocols`. Why,
and the `etag` and `PROTOCOL_UNSPECIFIED` handling: `references/gotchas.md`.
### 1. Apigee: enable the environment
The env must carry `apigee-service-extension-enabled=true`. No `gcloud` flag
exists; PATCH the properties map.
```bash
curl -s -H "Authorization: Bearer $TOKEN" \
"https://apigee.googleapis.com/v1/organizations/$ORG/environments/$ENV"
```
**The PATCH replaces the whole map.** Read it first and re-send every property
you intend to keep, or you will silently drop them.
```bash
curl -X PATCH -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
"https://apigee.googleapis.com/v1/organizations/$ORG/environments/$ENV?updateMask=properties" \
-d '{"properties":{"property":[{"name":"apigee-service-extension-enabled","value":"true"}]}}'
```
This does **not** disable Apigee Analytics — the two coexist; if analytics looks
missing it is the separate per-environment add-on. `references/gotchas.md`.
**Use a dedicated environment**, attached to **exactly one envgroup**. An
environment in two makes the gateway 404 every request with the extension never
invoked. It also leaves the `/` base path free, which is what the proxy ships
with.
`scripts/ensure_apigee_environment.sh` creates the environment, attaches it to
the regional runtime instance, and creates and attaches the envgroup — so step 2
is already done when it succeeds. It creates billable resources and applies
nothing without `--yes`; that agreement is taken in the plan, not here.
```bash
scripts/ensure_apigee_environment.sh \
--org "$ORG" --env "$ENV" --region "$REGION" \
--envgroup "$ENVGROUP" --hostname "$HOSTNAME" # add --yes to apply
```
It is idempotent and resumable, and refuses with exit 2 when the environment is
already in another envgroup or the envgroup exists on a different hostname. It
also handles three things a runbook tends to get wrong — the omitted `type` on
create, the four-minute instance attachment that **locks the environment**, and
polling the operation rather than a `GET` that succeeds too early.
### 2. Apigee: envgroup on the callout hostname
Done already if step 1's script ran. Verify, or do it by hand for an envgroup
that already exists. The hostname must be exactly the callout host, and the
group must be attached to the env.
```bash
curl -s -H "Authorization: Bearer $TOKEN" \
"https://apigee.googleapis.com/v1/organizations/$ORG/envgroups/$ENVGROUP/attachments"
```
**How many envgroups is the environment in?** More than one and the callout
never lands. `deploy_proxy.sh` enforces this before touching anything and exits
2 naming them; `assess_integration.sh` reports it. Read the failure literally if
it fires — the environment is wrong, not the script.
### 3. Build the proxy from the template
```bash
gcloud apigee apis import organizations/$ORG/apis/$PROXY \
--from-template=assets/apigee-proxy-template.yaml
```
Each `features:` entry resolves **relative to the template file's own
directory**, never the working directory, so a bare filename must sit beside the
template (a subpath like `features/feature-identity.yaml` works too). `assets/`
is flat by convention, not compiler demand — but moving a file without updating
`features:` fails the import with a bare `FileNotFoundError`.
If you get `Permission denied on resource ... (or it may not exist)` on an org
you demonstrably have access to, it is the credential, not the access. With
context-aware access enabled the default gcloud credential is rejected. Pass the
ADC token instead:
```bash
CLOUDSDK_AUTH_ACCESS_TOKEN=$(gcloud auth application-default print-access-token) \
gcloud apigee apis import ...
```
To change a parameter, **edit the `default` in every FEATURE that declares it**
— not in the template. `gcloud apigee apis import` passes an empty
caller-parameter map, so each feature resolves its own default and the
template's declaration of the same name is never read. Editing the template
changes nothing, silently, and the compile still passes. Measured: setting
`MA_CONTINUE_ON_ERROR` to DRY_RUN in the template shipped ENFORCE on a
fail-closed policy. `LLM_URI_MATCH` is declared in four features and all four
must agree. `scripts/compile_check.py` fails on any disagreement. There is no
`--parameters` flag.
Enable an optional recipe by adding its feature to the template's `features`
list. See `references/recipes.md`.
**`tokenMetering.models` in the input file is NOT generative.** It documents
which buckets exist; it does not create them. A bucket is real only when it has
an `LLMTokenQuota` step in `feature-token-metering.yaml` and a matching
`*_TOKEN_LIMIT` parameter. Three exist: `gemini-pro`, `gemini-flash` and `other`
— the catch-all for any model whose name contains neither `pro`/`argon` nor
`flash`/`hydrogen`. Adding a fourth entry to the list meters nothing, and
**omitting `other`
silently unmeters every non-Gemini model**: the count is extracted and then
discarded, with no `ratelimit` reference anywhere in the transaction. Adding a
model is a feature-file edit, not a config change.
### 4. Deploy
Deploy to the service-extension env, then confirm the deployment reports
`proxyDeploymentType: EXTENSIBLE`.
```bash
curl -s -H "Authorization: Bearer $TOKEN" \
".../environments/$ENV/deployments"
```
`STANDARD` means it will **not** govern the agent's off-Apigee tool egress.
If any policy calls a Google API — Model Armor, embeddings, Vector Search —
deploy **with a service account** or the deploy is rejected with
`MISSING_SERVICE_ACCOUNT`:
```bash
curl -X POST -H "Authorization: Bearer $TOKEN" \
".../apis/$PROXY/revisions/$REV/deployments?override=true&serviceAccount=$DEPLOY_SA"
```
### 5. Networking
This is the **gateway → Apigee** leg only. PSC endpoint to the Apigee instance
service attachment, plus a private DNS A record. See
`references/networking-psc.md`. The Apigee instance `consumerAcceptList` must
include your project or the connection never reaches `ACCEPTED`.
The **agent → gateway** leg is the prerequisite above, and is not built here.
### 6. Bind the gateway
AuthzExtension then AuthzPolicy — in that order, and only once the host resolves
and the proxy is deployed. The extension is inert until then.
**Both document bodies ship as assets. Copy and substitute; do not invent them**
— `assets/authz-extension.example.yaml` and `assets/authz-policy.example.yaml`.
They carry the fields that are load-bearing and have no obvious default:
`wireFormat: EXT_PROC_GRPC`, `failOpen`, the `authority`/`service` pair, the
`metadata` body flags, and the policy's `customProvider` / `httpRules` nesting.
```bash
gcloud service-extensions authz-extensions import $AUTHZ_EXT \
--source=authz-extension.yaml --location=$REGION --project=$PROJECT
gcloud beta network-security authz-policies import $AUTHZ_POLICY \
--source=authz-policy.yaml --location=$REGION --project=$PROJECT
```
**The policy's resource paths take the project NUMBER, not the ID** — both
`target.resources` and `customProvider.authzExtension.resources`. Resolve it
yourself; narrating two numbers at the user does not help. The trap, for when a
callout never lands: the number in the gateway's
`serviceExtensionsServiceAccount` is the Google-managed tenant project, not
theirs, and it is the only one on screen, so it is the natural thing to copy. A
wrong number imports cleanly and targets nothing. Copy the slots from
`assets/authz-policy.example.yaml`.
### 7. Verify
You **cannot** test with curl — the host is internal and the proxy expects the
gateway's IAP-egress JWT. Run `scripts/read_debug_session.sh --arm`, drive a
turn, read it back with `--session`. Expect **one** transaction per turn per
governed shape under a suffix list this narrow; zero alone does not mean the
callout is dead — the script prints the probe that settles it.
## Hard rules
**Gate every step — how urgently depends on your AuthzPolicy.** An ungated
`continueOnError="false"` policy faults on any call that carries no prompt, and
that **breaks the agent's turn**. Historically the most common failure here.
A narrow suffix list routes only the model call to Apigee, so the trap mostly
does not fire. Broaden the policy and it fires at once: the ext-proc then sees
every agent egress — session create/read, `appendEvent`, OpenTelemetry exports —
measured at 12 calls for one single-question turn, of which one was the model
call. Gate the steps regardless; a condition is cheap and it is what makes the
policy safe to widen later. Full measurement: `references/gotchas.md`.
- model call: `(request.uri Like "*generateContent*")`
**Never fail-close on your own metering.** Keep `continueOnError="true"` on the
JavaScript and quota policies so a metering bug cannot break LLM traffic.
**This skill meters by default and can enforce on request.** Enforcement is
`assets/feature-token-enforce.yaml`: request-flow `EnforceOnly` policies sharing
each `SharedName` with the response-flow `CountOnly` half. Add it to the
template's feature list. Verified live on ext-proc traffic — the over-budget
caller gets a **429**, model never called.
Never offer `CountOnly=false` as a substitute: in the response flow it cannot
gate (the answer is already on the wire) and it freezes the counter, losing the
metering too.
State two things whenever you offer it. It is **one request late** — the turn
that crosses the limit completes, because a token cost is not known until the
model answers. And it buckets on the **requested** model, which under an OpenAI
alias can differ from the resolved model the counting side bills. The two traps
that both present as "it never refuses": `references/gotchas.md`.
**Normalize the model to a bucket.** With an OpenAI-compatible endpoint the
model is an alias in the request body and the *resolved* name is in the response
body (`google/gemini-4-argon`). Exact-matching a raw name fails on the response
path.
**`jsonPath` needs its third argument `true`** so it returns a scalar. Without
it the quota policy receives a node it cannot parse.
## References
- `references/modes.md` — **read first.** How to answer "what can you do", dev
vs prod, the defaults, durations, cost disclosure, the interlocks, and
reading an assess report
- `scripts/assess_integration.sh` — **read-only.** Setup Status Summary then a
per-check table; `--json` carries both. Lead with the summary and read out
the **Enforcement** row. Run it before planning: it decides CREATE vs REUSE.
`TODO` is a build step, not a failure; only `FAIL` exits non-zero
- `references/networking-psc.md` — both network legs, PSC, DNS, acceptance
- `references/recipes.md` — Model Armor and semantic cache
- `references/verify.md` — debug sessions and the checklist script
- `references/setup.md` — SDK, project, billing, APIs, region, auth, IAM
- `references/gotchas.md` — 63 failure modes and their symptoms
- `assets/apigee-agent-gateway-governance.example.yaml` — the input contract
- `assets/apigee-proxy-template.yaml` — the AFT template. Features merge by
`priority` and all sit beside it: `feature-identity.yaml` (10),
`feature-normalize.yaml` (15), `feature-model-armor.yaml` (20),
`feature-semantic-cache.yaml` (30), `feature-token-metering.yaml` (50).
- `assets/authz-extension.example.yaml`, `assets/authz-policy.example.yaml` —
the step-6 bodies. Copy and substitute; paths take the project **number**
**Anything read out of the request body is normalised once, at priority 15,
not inside whichever feature needs it first.** `LLM_URI_MATCH` is shared, so
widening it arms every feature gated on it simultaneously — including Model
Armor, which fails closed. Model Armor and the cache both read
`agw.user_prompt`; the quotas read `agw.total_tokens`, set on the response
path by the metering feature's own JS for the same reason.
- `scripts/ensure_apigee_environment.sh` — create the environment, attach it
to the instance, create and attach the envgroup. Idempotent, `--yes` gated
- `scripts/ensure_gateway_connectivity.sh` — route the gateway into the VPC. Read-modify-write; `--yes` gated
- `scripts/ensure_vector_search.sh` — only when `semanticCache` is enabled:
build index and endpoint, deploy one on the other, read back the domain.
`--yes` gated, ~34 min, bills continuously
- `scripts/teardown_vector_search.sh` — the only thing that STOPS that charge. Refuses until the revision drops `SCL-lookup`. `--yes` gated
- `scripts/deploy_proxy.sh` — the Apigee-side sequence, idempotent, `--dry-run`
- `scripts/read_debug_session.sh` — `--arm` a session (printing when it
actually closes) and read it back as the `verify.md` checklist, instead of
parsing the transaction JSON by hand
- `scripts/compile_check.py` — compile the template offline, no org needed
apigee-agent-gateway-governance.example.yaml 20.8 KB
# THE customer-owned, version-controlled input -- and the schema for BOTH modes.
#
# PROD mode reads this file as the contract and reconciles the setup to it,
# refusing rather than defaulting when a required field is absent. DEV mode
# WRITES this same shape at the end of a conversational setup, so what it emits
# can be committed and fed straight back in. One schema, two entry points --
# see references/modes.md.
#
# Commit it; review it; roll it back. The skill reads it, rewrites the AFT
# template/feature parameter defaults from it, compiles the proxy through
# `gcloud apigee apis import --from-template`, and runs the gcloud/REST
# steps for the pieces AFT does not cover.
#
# Do not hand-edit the generated proxy bundle. Change this file and regenerate,
# or the committed artifact stops matching what is deployed.
#
# SCOPE LIMIT, STATED PLAINLY: AFT YAML covers the proxy only. The environment
# property, envgroup, PSC endpoint, DNS record, AuthzExtension and AuthzPolicy
# are driven imperatively from the values below. They are reproducible from
# this file, but they are not themselves declarative Apigee config.
apiVersion: apigee.googleapis.com/v1alpha1
kind: AgentGatewayGovernance
metadata:
name: agent-gateway-governance
description: Meter LLM tokens per model on the agent gateway's egress.
spec:
project: my-project
region: us-central1
apigee:
org: my-project
# MUST BE DEDICATED TO THIS PROXY, and attached to exactly ONE envgroup --
# the one named below. An environment sitting in two envgroups makes the
# gateway return 404 for every agent request, with the extension never
# invoked and no error reported anywhere. Do not share an environment to
# save creating one.
#
# CREATED BY THE SKILL if absent, and attached to the runtime instance in
# `region`, by scripts/ensure_apigee_environment.sh. That script creates
# billable resources, so it prints a plan and does nothing without --yes.
# It is idempotent and resumable, so a partial run is safe to repeat.
#
# An EXISTING environment is reused only after the skill counts its
# envgroups and finds at most this one. If it is already in another, the
# skill stops rather than continuing, because every later step would
# otherwise succeed and govern nothing.
#
# Two things it handles that bite when done by hand: on a SUBSCRIPTION_2021
# org `type` must be omitted from the create, and attaching to the instance
# takes around four minutes during which the environment is LOCKED -- a
# property PATCH in that window fails looking like a permissions problem.
#
# The skill WILL set the environment property
# apigee-service-extension-enabled=true on it -- that property is what lets
# the environment host a service-extension proxy, and without it the proxy
# deploys STANDARD and never sees the agent's traffic.
# Note the property PATCH replaces the environment's whole property map, so
# the skill reads the existing properties first and re-sends them.
# This does NOT disable Apigee Analytics; the two are unrelated.
environment: agent-gateway-govern
# CREATED BY THE SKILL if absent, on `hostname` below, and attached to
# `environment` -- same script, same --yes gate as the environment above.
#
# An existing envgroup is reused ONLY if it already carries `hostname`
# exactly. If it exists on a different hostname the skill stops rather than
# rewriting it: the group may carry someone else's routing, and a hostname
# that does not match the AuthzExtension authority means the callout never
# lands and nothing errors.
envgroup: agent-gateway-govern-group
# An internal hostname you choose. It does not need to be registered
# anywhere public and nothing resolves it outside your VPC.
#
# The skill writes this same string into THREE places it creates, and they
# must stay byte-identical or the callout silently never lands and nothing
# errors:
# 1. the Apigee envgroup hostname
# 2. the private DNS A record
# 3. the AuthzExtension authority/service
# You give the value once, here. network.dns.record below repeats it only
# because the DNS zone is described separately; keep the two identical.
hostname: agent-gateway-callout.internal.example.local
proxy: agent-gateway-governance
# YOU CREATE THIS BEFOREHAND. The skill does not create it and does not
# grant it anything.
#
# Required only if an enabled feature calls a Google API. With just
# identity + tokenMetering, leave it as "" -- naming a service account that
# does not exist, or that you cannot act as, fails the deploy.
#
# Roles the service account itself needs, by feature:
# modelArmor roles/modelarmor.user
# semanticCache roles/aiplatform.user (embeddings + Vector Search)
# And the identity running the deploy needs iam.serviceAccounts.actAs on
# this service account, or the deploy is rejected even though the roles
# above are correct.
#
# Omitting it when a feature does need it fails with
# MISSING_SERVICE_ACCOUNT.
deploymentServiceAccount: ""
network:
# BOTH MUST ALREADY EXIST. The skill does not create them.
#
# This must be the VPC the Agent Gateway egresses into -- the one named in
# the gateway's network attachment -- not simply any VPC in the project.
# If they differ, everything below builds successfully and the gateway
# still cannot reach Apigee.
#
# The subnet must be in `region` above, which must also be the region of
# the Apigee runtime instance. All three are the same region: the gateway,
# the subnet the private endpoint is reserved in, and the Apigee instance.
vpc: agent-network
subnet: agent-subnet
# PSC-interface network attachment the Agent Gateway egresses through to
# reach your VPC. CREATED BY THE SKILL in `subnet` above if it does not
# already exist; reused as-is if it does.
#
# This is what gives the gateway a route to the Apigee PSC endpoint. A
# gateway without one serves ordinary agent traffic perfectly well -- that
# path never enters your VPC -- and silently fails only the Apigee callout.
networkAttachment: agent-gateway-egress-attachment
dns:
# CREATED BY THE SKILL: a private zone visible to `vpc`, plus an A record
# pointing at the private endpoint it reserves for the Apigee instance.
# The gateway must also be able to resolve this zone -- that comes from
# the gateway's own DNS peering config, which is out of scope here.
zone: agent-gateway-callout-zone
# Must be the parent domain of `record`, with the trailing dot.
domain: internal.example.local.
# MUST equal apigee.hostname above, character for character.
record: agent-gateway-callout.internal.example.local
gateway:
# MUST ALREADY EXIST. The skill does not create the Agent Gateway. It can
# add missing network connectivity to one -- see manageNetworkConfig below
# -- but only with your confirmation. Use the short name, not the full
# resource path. List what you have with:
# gcloud network-services agent-gateways list \
# --location=$REGION --project=$PROJECT
#
# Two things about that gateway decide whether any of this works, and
# NEITHER is visible from the gateway name:
#
# 1. networkConfig.egress.networkAttachment -- a PSC-interface network
# attachment into `network.vpc` below. Without it the gateway has no
# route into your VPC and can never reach Apigee.
# 2. networkConfig.dnsPeeringConfig -- forwards `network.dns.domain` to
# your VPC. Without it the gateway cannot resolve `hostname`.
#
# A gateway missing these still passes every earlier check and still serves
# ordinary agent traffic to public Google endpoints, because that path does
# not enter your VPC. It is only the callout to Apigee that fails, and it
# fails silently. Check before you start -- empty output means missing:
# gcloud network-services agent-gateways describe $GATEWAY \
# --location=$REGION --project=$PROJECT --format='value(networkConfig)'
name: my-agent-gateway
# What the skill does when that networkConfig is missing.
#
# true -- add it for you: create network.networkAttachment if needed,
# then read-modify-write the gateway to add the egress
# attachment and DNS peering for network.dns.domain. The skill
# prints the exact before/after diff and waits for you to
# confirm. It never applies silently.
# false -- leave the gateway untouched and stop, printing the commands to
# run yourself. Choose this if the gateway is shared, owned by
# another team, or under IaC that would revert the change.
#
# Either way the skill refuses to continue while networkConfig is absent,
# because every later step would succeed and govern nothing.
manageNetworkConfig: true
# Path suffixes identifying a real model call. ONE ENTRY PER WIRE SHAPE
# you want governed; list both to govern both from a single proxy.
#
# gemini -> :generateContent
# openai -> /chat/completions
#
# These compile to the template's LLM_URI_MATCH as an OR of "*<entry>*"
# conditions. Two entries give:
#
# ((request.uri Like "*generateContent*") or
# (request.uri Like "*chat/completions*"))
#
# DELETING AN ENTRY SILENTLY STOPS GOVERNING THAT SHAPE. The proxy still
# deploys clean and reports nothing -- no fault, no error, just zero
# transactions for the shape you dropped. The same condition also gates
# Model Armor and the semantic cache, so narrowing this narrows all three
# at once. See references/gotchas.md, Runtime.
#
# The AuthzPolicy binds on path SUFFIX, which is why the OpenAI entry has
# NO leading /v1. /v1/chat/completions is LITERAL-OPENAI ONLY: Vertex's
# OpenAI-compatible endpoint ends openapi/chat/completions, so that
# pattern never matches it. Measured -- 0 transactions across two
# successful agent turns, 1 after switching to /chat/completions.
# See references/gotchas.md.
#
# Metering does not depend on this list. The token count is normalised in
# JS across both shapes, which is why there is no longer an apiShape
# field: it selected nothing and said so in its own comment.
matchPaths:
- ":generateContent"
- "/chat/completions"
timeout: 5s
# Each feature below compiles to a named set of Apigee policies. The values
# you set here become those policies' configuration fields, so the policy
# reference is the authority on what each one accepts and how it behaves.
#
# feature Apigee policies it generates
# ------------------- ----------------------------------------------------
# identity VerifyJWT, AssignMessage
# https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/verify-jwt-policy.md.txt
# https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/assign-message-policy.md.txt
# tokenMetering Javascript, LLMTokenQuota (one per model), AssignMessage
# https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/llm-token-quota-policy.md.txt
# https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/javascript-policy.md.txt
# modelArmor SanitizeUserPrompt
# https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/sanitize-user-prompt-policy.md.txt
# (response-side equivalent, not generated today:
# https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/sanitize-llm-response-policy.md.txt)
# semanticCache SemanticCacheLookup, SemanticCachePopulate
# https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/semantic-cache-lookup-policy.md.txt
# https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/semantic-cache-populate-policy.md.txt
# https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/parse-payload-policy.md.txt
# https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/verify-api-key-policy.md.txt
# https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/quota-policy.md.txt
#
# Field-by-field mapping, including which parameter drives which policy
# element: references/recipes.md.
features:
# ---- always on ---------------------------------------------------------
identity:
enabled: true
# Fallback when the gateway's IAP-egress JWT is absent. An absent header
# skips verification entirely; only a present-but-invalid token fails
# closed.
defaultClientId: anonymous
tokenMetering:
enabled: true
#
# COUNT_ONLY | ENFORCE. Same shape as modelArmor.mode below, and the
# same question: does this observe, or does it refuse?
# COUNT_ONLY meters every call and blocks nothing. `limit` is the
# denominator you measure against, for alerts and
# chargeback. This is the default.
# ENFORCE also refuses a caller that has spent its budget, with a
# 429, before the model is called. Adds
# feature-token-enforce.yaml. Verified live on ext-proc
# traffic.
#
# ENFORCEMENT IS ONE REQUEST LATE BY CONSTRUCTION: the turn that crosses
# the limit completes, because its cost is not known until the model
# answers, and the caller's NEXT request is refused. A token budget
# cannot be checked before the tokens exist. Say this when offering it.
#
# Do NOT try to get enforcement by making the response-flow quotas
# blocking. Verified on a live gateway, it fails in both directions:
# - It cannot deny. The quota runs on the RESPONSE, because the token
# count does not exist until the model has answered. The bytes are
# already going back to the caller by then -- Apigee aborts and emits
# 429, and the caller still gets the full answer.
# - It breaks the metering you already had. A blocking quota will not
# count the request that violated it, so the counter sticks at the
# limit for the rest of the window.
# That is a property of that placement, not of the policy.
#
# One caveat specific to ENFORCE: it buckets on the REQUESTED model,
# because the resolved name only exists in the response. Under an
# OpenAI-compatible alias a call can be enforced against one bucket and
# counted against another. Everything is still counted and still checked.
mode: COUNT_ONLY
interval: 1
timeUnit: hour
# THESE THREE BUCKETS ARE THE THREE THAT EXIST. The list is not
# generative: each bucket must also have an LLMTokenQuota step in
# feature-token-metering.yaml and a matching template parameter, so
# adding a fourth here on its own meters nothing.
models:
- bucket: gemini-pro
limit: 10000
- bucket: gemini-flash
limit: 40000
# Catch-all: every model whose name contains neither "pro"/"argon" nor
# "flash"/"hydrogen" -- gpt-oss, Llama, Qwen, DeepSeek. Without it those
# calls consume no quota at all: the token count is extracted correctly and
# then discarded, with zero ratelimit references in the transaction
# and nothing reporting the gap.
- bucket: other
limit: 40000
# ---- optional recipes --------------------------------------------------
modelArmor:
enabled: false
# REQUIRED when enabled -- there is deliberately no default. A shipped
# default either names a template that does not exist in your project
# (the deploy fails for a reason that reads like a permissions problem)
# or, worse, silently points at a real template that screens nothing you
# chose. Prod mode refuses with the field named, as it does for
# semanticCache without deployedIndexId.
template: ""
# Needs roles/modelarmor.user on deploymentServiceAccount.
#
# ENFORCE | DRY_RUN. One of two policies here that can refuse a request;
# the other is tokenMetering.mode: ENFORCE. With Model Armor off or in
# DRY_RUN and metering at COUNT_ONLY, nothing here blocks anything.
# ENFORCE a filter match faults the policy; the caller gets a 400.
# DRY_RUN the scan still runs and the verdict is still in the trace,
# but the fault is swallowed and the turn continues.
# DRY_RUN is NOT "off": removing the feature means no evaluation at all.
# Use it to watch what a template would have blocked before letting it.
#
# Defaults to ENFORCE on purpose. A security control that silently does
# not protect is worse than one that visibly blocks, and silent
# non-protection is the failure class this whole skill exists to prevent.
# Toggling requires a redeploy (~2 min) -- deliberate, which suits a
# change that decides whether live agent turns can be refused.
mode: ENFORCE
semanticCache:
# A CACHE HIT CROSSES CALLER BOUNDARIES. The key is the embedding of the
# prompt and nothing else -- no caller, no model, no wire shape, no
# tenant. One model and one wire shape does NOT make this safe: two
# callers whose prompts are merely SIMILAR share an answer, so anything
# caller-specific leaks from whoever asked first. Identity is on by
# default and agw.client_id is available, but the cache policies accept
# no discriminator, so it cannot be scoped.
#
# Enable this only where every caller is entitled to every other
# caller's answer for the same question.
#
# Two further effects once more than one model answers here. Across wire
# shapes the cached body is in the wrong format, the client parses
# nothing, and the turn returns an EMPTY SUCCESS rather than an error --
# which reads as "the agent stopped working" and sends you into the agent
# code, the one place the cause is not. Reproduced across three
# consecutive runs. Within one shape it is quieter and worse: the body
# parses, and only model_version differs.
#
# KNOWN ISSUE, NOT A BLOCK. The skill builds the cache and warns rather
# than refusing, and it warns whenever the cache is enabled -- not only
# when matchPaths carries more than one entry. The defect is upstream and
# a fix is expected. See references/gotchas.md (Runtime) for mitigations
# and the upstream bug.
enabled: false
threshold: 0.95
ttlSeconds: 60
# PICK THIS BEFORE YOU BUILD THE INDEX, NOT AFTER. The policy takes only
# a URL, so the model's native width is what the index must be, and index
# width is fixed at creation. Changing it later is an index rebuild, not
# a config edit. Measured widths:
#
# gemini-embedding-001 3072 stronger; 4x storage
# text-embedding-005 768 <- default, supported
# text-multilingual-embedding-002 768
# text-embedding-004 768 still serves, but has dropped
# off the supported-models list
#
# 768 is ample for cache duty. Use gemini-embedding-001 only if you
# deliberately want the stronger model and a 3072 index to match.
embeddingsModel: text-embedding-005
# <DeployedIndexID> -- all-caps ID. DeployedIndexId fails validation.
# Lowercase, digits and underscores only; hyphens are rejected.
deployedIndexId: agent_gateway_llm_cache
# CREATED BY THE SKILL if absent: scripts/ensure_vector_search.sh builds
# the index and endpoint, deploys one onto the other, and prints these
# ids as JSON. It is --yes gated and resumable, which matters because the
# deploy step alone takes about 34 minutes.
#
# THIS IS THE ONLY PART OF THE SKILL THAT BILLS CONTINUOUSLY: a deployed
# index costs per node-hour for as long as it is deployed, with or
# without traffic. To stop the cost, undeploy it -- see the teardown
# order the script prints, which matters because SCL-lookup is
# fail-closed and undeploying underneath a live proxy faults every
# request.
#
# There is deliberately no field for the endpoint's domain. It cannot be
# derived from either id, so deploy_proxy.sh reads it back at deploy
# time from --index-endpoint-id.
indexEndpointId: ""
indexId: ""
# Needs roles/aiplatform.user on deploymentServiceAccount.
apigee-proxy-template.yaml 9.4 KB
# Apigee Feature Template: Agent Gateway ext-proc processor.
#
# Compiles to a NO-ROUTE proxy: <RouteRule name="noroute"/> with no
# <TargetEndpoint>. The Agent Gateway calls this proxy as a Service Extension
# callout; it inspects the LLM request/response the gateway hands it and
# returns a verdict. It never calls a backend.
#
# Compile + deploy:
# gcloud apigee apis import organizations/$ORG/apis/$PROXY \
# --from-template=apigee-proxy-template.yaml
#
# Every flow step comes from a feature. The template only declares the endpoint
# shell and the no-route rule, because AFT's Template.endpoints accepts
# name/basePath/routes only -- flows live on features' defaultEndpoint and are
# merged in feature `priority` order.
#
# Parameter override: gcloud's `apis import` passes an EMPTY caller-parameter
# map to the AFT compiler, so values are taken from the `default` fields below.
# To customise, rewrite these defaults before compiling. Do not rely on a
# --parameters flag; none exists today.
gateway: apigee
schemaVersion: 1.0.0
name: agent-gateway-governance
type: template
description: >-
Apigee proxy invoked by a GCP Agent Gateway as an ext-proc (Service
Extension) callout on LLM and agent-tool egress. Extracts caller identity,
meters LLM token usage per model, and optionally applies Model Armor,
semantic cache. No backend.
features:
- feature-identity.yaml
# Priority 15, between identity (10) and every consumer of a request-body
# value. Kept in the base list rather than treated as optional: Model Armor
# and the semantic cache both read agw.user_prompt, and enabling either one
# without this present makes Model Armor fail CLOSED on every matching
# request. Costs one gated JS step when nothing consumes it.
# See references/gotchas.md, Runtime.
- feature-normalize.yaml
- feature-token-metering.yaml
# Optional -- uncomment to enable:
# - feature-token-enforce.yaml (turns the budget into a limit)
# - feature-model-armor.yaml (Model Armor template + IAM)
# - feature-semantic-cache.yaml (Vector Search index + endpoint)
#
# feature-token-enforce.yaml needs no external resource -- it reads the
# counters feature-token-metering.yaml already writes. Off by default
# because it REFUSES traffic: it is the only part of this template besides
# Model Armor that fails closed, and enforcement is one request late by
# construction. Verified live on ext-proc traffic. Its
# *_TOKEN_LIMIT values must stay in step with the metering ones, and
# compile_check.py fails the build if they drift.
parameters:
# READ THIS BEFORE EDITING A DEFAULT BELOW.
#
# These declarations are INERT for features. Editing one changes nothing.
#
# `gcloud apigee apis import --from-template` calls the compiler with an
# EMPTY caller-parameter map, so every feature resolves its OWN declared
# default and the template's declaration of the same name is never read.
# The compile still succeeds -- the macro resolves, just to the other value
# -- so there is no error to notice.
#
# Measured: setting MA_CONTINUE_ON_ERROR to "true" (DRY_RUN) here while
# feature-model-armor.yaml kept "false" produced a bundle with
# continueOnError="false", i.e. ENFORCE, on a fail-closed security policy.
# The operator had explicitly chosen DRY_RUN.
#
# TO CHANGE A SHARED PARAMETER, EDIT IT IN EVERY FEATURE THAT DECLARES IT.
# LLM_URI_MATCH is declared in four feature files; all four must agree.
# `scripts/compile_check.py` now FAILS on any template/feature disagreement
# and warns about template parameters no feature reads, so this cannot be
# shipped silently again -- but it only catches it if you run it.
#
# The declarations are kept because they document the knobs and their
# defaults in one place, and because the compile check uses them to detect
# drift. They are documentation, not configuration.
#
# Separately: macro substitution runs over FEATURE content only. A {MACRO}
# written in the template's own body (basePath, for instance) is not
# replaced and would reach Apigee literally.
# ---- routing / shape -----------------------------------------------------
- name: LLM_URI_MATCH
displayName: LLM call match condition
description: >-
Flow condition identifying the real model call. The ext-proc sees EVERY
agent egress (session create/read, appendEvent, OpenTelemetry exports),
so every step must be gated or it fires on traffic carrying no prompt and
breaks the agent turn.
DERIVED FROM gateway.matchPaths in the input file: one
(request.uri Like "*<entry>*") clause per list entry, OR-ed together.
This is the compiled form of that list, not an independent knob -- the
input file is the reviewable contract. A one-entry list is legitimate
and means "govern one shape".
Matching BOTH shapes lets one proxy govern a Gemini-native agent and an
OpenAI-shape agent at the same time. The default does that, and matches
the two-entry default in the shipped input file.
The OpenAI tail is *chat/completions* with NO leading /v1. Vertex's
OpenAI-compatible endpoint ends openapi/chat/completions, and the
AuthzPolicy matches on SUFFIX, so a "*/v1/chat/completions*" pattern
never fires against it -- that form is literal-OpenAI only. Measured:
0 transactions across two successful agent turns, 1 after the switch.
THIS CONDITION IS SHARED by feature-normalize, Model Armor and the
cache. Widening it widens all of their blast radii at once, which is
why the prompt is normalised once at priority 15 rather than inside
whichever feature needs it first. See references/gotchas.md, Runtime.
default: '((request.uri Like "*generateContent*") or (request.uri Like "*chat/completions*"))'
examples:
- '(request.uri Like "*generateContent*")'
- '(request.uri Like "*chat/completions*")'
- '((request.uri Like "*generateContent*") or (request.uri Like "*chat/completions*"))'
# ---- Model Armor enforcement mode ----------------------------------------
- name: MA_CONTINUE_ON_ERROR
displayName: Model Armor enforcement mode
description: >-
Only meaningful when feature-model-armor is enabled. "false" = ENFORCE,
a filter match faults the policy and the caller gets a 400. "true" =
DRY_RUN, the scan still runs and the verdict is still in the trace, but
the fault is swallowed and the turn continues.
This is the blocking switch, not an on/off switch: removing the feature
means no evaluation at all, which is "off" rather than dry-run.
Model Armor is the only policy that blocks in the DEFAULT feature set:
the shipped quotas are CountOnly. Adding feature-token-enforce.yaml puts
a second blocking policy in the request flow -- check which features are
enabled before telling anyone nothing here can refuse a request.
Toggling needs a redeploy, which is deliberate, and suits a change that
decides whether live turns can be refused.
default: "false"
examples:
- "false"
- "true"
# ---- identity ------------------------------------------------------------
- name: CLIENT_ID_DEFAULT
displayName: Default client id
description: >-
Value for agw.client_id when the gateway's IAP-egress JWT is absent. An
absent header skips the VerifyJWT step entirely; only a present-but-
invalid token fails closed.
default: anonymous
# ---- token metering ------------------------------------------------------
# No TOKEN_USAGE_JSONPATH parameter. The count is normalised in JS and read
# from agw.total_tokens, because a JSONPath can only select a field that
# exists -- it cannot choose between wire shapes, and it cannot compute a
# total for a shape that reports input and output separately. Adding a
# shape is an || branch in extract-model.js, not a config change.
# See references/gotchas.md, Runtime.
- name: PRO_TOKEN_LIMIT
displayName: Pro model token allowance
description: Token allowance per interval for the gemini-pro bucket.
default: "10000"
- name: FLASH_TOKEN_LIMIT
displayName: Flash model token allowance
description: Token allowance per interval for the gemini-flash bucket.
default: "40000"
- name: OTHER_TOKEN_LIMIT
displayName: Non-Gemini model token allowance
description: >-
Token allowance per interval for the catch-all "other" bucket, which is
every model whose name contains neither "pro"/"argon" nor
"flash"/"hydrogen" -- gpt-oss, Llama, Qwen, DeepSeek. Without it those
calls consume no quota at all
and nothing reports the gap. See references/gotchas.md, Runtime.
default: "40000"
- name: QUOTA_INTERVAL
displayName: Quota interval
default: "1"
- name: QUOTA_TIME_UNIT
displayName: Quota time unit
default: hour
examples: ["minute", "hour", "day"]
# No `endpoints:` here, and no `targets:`.
#
# gcloud 588.0.0 ignores a template's `endpoints`/`targets` whenever the template
# supplies features -- "they are only used when the template supplies no
# features" -- and logs a warning. Before 588 the two were combined, which is how
# the no-route endpoint used to get here.
#
# It now lives in feature-identity.yaml (priority 10, the lowest), declared as a
# real `endpoints:` entry so the later features' `defaultEndpoint` fragments have
# something to merge into. Put one back here and it is silently discarded.
authz-extension.example.yaml 1.7 KB
# AuthzExtension -- the gateway's pointer at your Apigee callout.
#
# gcloud service-extensions authz-extensions import <NAME> \
# --source=authz-extension.yaml --location=$REGION --project=$PROJECT
#
# Create this BEFORE the AuthzPolicy that references it, and only once the
# callout hostname resolves and the proxy is deployed. Creating it earlier
# succeeds and reports nothing wrong -- it simply stays inert, so "the
# extension exists" is not evidence that this leg works.
name: projects/PROJECT_ID/locations/REGION/authzExtensions/GATEWAY-apigee-governance-extension
# Both carry the BARE callout hostname -- no scheme, no port, no trailing
# slash -- and both must equal the Apigee envgroup hostname and the private
# DNS A record exactly. Any mismatch and the callout silently never lands.
authority: agent-gateway-callout.internal.example.local
service: agent-gateway-callout.internal.example.local
wireFormat: EXT_PROC_GRPC
# true = a callout failure lets the request through. Correct for this skill,
# which meters and inspects but does not gate: a metering bug must not be able
# to break LLM traffic. Set false ONLY if you have added a policy that is
# genuinely meant to block, and you accept that its failure blocks too.
failOpen: true
timeout: 5s
# LOAD-BEARING. Omit the body flags and body extraction silently sees nothing:
# the policies run, extract empty, and report no error. This is the most
# common cause of "the policy runs but extracts nothing".
metadata:
apigee-extension-processor: agent-gateway-governance # which proxy runs
apigee-request-body: 'true' # -> request.content
apigee-response-body: 'true' # -> response.content
authz-policy.example.yaml 2.1 KB
# AuthzPolicy -- what makes the gateway actually call the extension.
#
# gcloud beta network-security authz-policies import <NAME> \
# --source=authz-policy.yaml --location=$REGION --project=$PROJECT
#
# Import this AFTER the AuthzExtension it references. This is the outer gate:
# a suffix list narrower than gateway.matchPaths means the missing shape never
# reaches Apigee at all, and the proxy's own condition is irrelevant.
name: projects/PROJECT_ID/locations/REGION/authzPolicies/GATEWAY-apigee-governance-policy
action: CUSTOM
# CONTENT_AUTHZ sees request and response bodies, which is what metering needs.
# REQUEST_AUTHZ runs first and sees headers only -- that profile is what an IAP
# extension uses. A gateway allows at most 4 CUSTOM policies across both
# profiles.
#
# Ordering WITHIN one profile is UNDEFINED. It is not alphabetical, not
# creation order, and AuthzPolicy has no priority field. Do not state a
# tie-break to a user -- see references/gotchas.md, Agent Gateway.
policyProfile: CONTENT_AUTHZ
# !! PROJECT *NUMBER*, NOT PROJECT ID -- in BOTH resource lists below.
# !! And NOT the number in the gateway's serviceExtensionsServiceAccount.
# !! That SA reads service-<NUMBER>@gcp-sa-dep.iam.gserviceaccount.com and is
# !! printed by assess_integration.sh as a PASS row, but that number belongs to
# !! the Google-managed tenant project, not yours. Using it produces a policy
# !! that imports cleanly, reports no error, and targets nothing.
# !! Get yours with:
# !! gcloud projects describe $PROJECT --format='value(projectNumber)'
customProvider:
authzExtension:
resources:
- projects/PROJECT_NUMBER/locations/REGION/authzExtensions/GATEWAY-apigee-governance-extension
target:
resources:
- projects/PROJECT_NUMBER/locations/REGION/agentGateways/GATEWAY
# One entry per gateway.matchPaths entry, copied VERBATIM with leading
# punctuation kept -- ":generateContent", "/chat/completions". These are
# suffix matches, so the OpenAI entry has no "/v1".
httpRules:
- to:
operations:
- paths:
- suffix: ":generateContent"
feature-identity.yaml 6.0 KB
# Feature: caller identity from the gateway's IAP-egress JWT.
#
# Runs in the Request PreFlow. The VerifyJWT step is conditional on the header
# being PRESENT: an absent header skips it and the client falls back to
# CLIENT_ID_DEFAULT; only a present-but-invalid token fails closed.
#
# NAMESPACING: the compiler renames every policy in this feature to
# "<feature name>-<policy name>", i.e. VJ-iap-egress-jwt becomes
# identity-VJ-iap-egress-jwt. It rewrites <Step><Name> references, but it does
# NOT rewrite policy-derived flow variables such as jwt.<policy>.decoded.*.
# The Ref below is therefore written pre-namespaced on purpose. If you rename
# this feature or set a `uid`, update it to match.
gateway: apigee
schemaVersion: 1.0.0
name: identity
uid: identity
type: feature
priority: 10
description: >-
Extracts the calling agent identity from the Agent Gateway's IAP-egress JWT
assertion and publishes it as agw.client_id for downstream metering and
quota identifiers.
parameters:
- name: CLIENT_ID_DEFAULT
displayName: Default client id
description: Fallback when no IAP-egress JWT is present.
default: anonymous
- name: IAP_JWKS_URI
displayName: IAP egress JWKS URI
description: >-
JWKS endpoint used to verify the gateway's egress assertion. VERIFIED
LIVE: the assertion's header carries kid 1F5uEQ, and that key is present
in this JWK set (5 keys, all ES256), so this default is correct as
shipped -- an earlier note here said it pointed at "plain IAP" and that
the signature therefore did not verify. It does:
jwt.<policy>.signed and jwt.<policy>.valid both read true on a live turn.
default: https://www.gstatic.com/iap/verify/public_key-jwk
- name: IAP_JWT_ISSUER
displayName: IAP egress JWT issuer
description: >-
Asserted against the token's iss claim. VERIFIED LIVE on a real Agent
Gateway turn.
Pinning this matters because the JWKS above is Google's shared IAP key
set, which signs assertions for purposes other than gateway egress.
Without an Issuer assertion any IAP-signed token passes verification, so
a token minted for something else would be accepted as if it were this
gateway's. There is no Audience assertion by design: aud on this token is
the upstream MODEL endpoint, not Apigee -- the proxy is reading a copy of
the agent's egress authorization, not a token addressed to it -- so
pinning aud would mean enumerating every model URL and would be wrong in
principle.
default: https://cloud.google.com/iap-egress
- name: CLIENT_ID_CLAIM
displayName: Claim to use as the caller identity
description: >-
Flow variable read into agw.client_id, which is what the token quotas key
on. VERIFIED LIVE: the gateway's assertion carries no email claim -- its
claims are [iss, aud, exp, iat, iam_principal, azp] -- so iam_principal
is the identity. Written PRE-NAMESPACED; rename this feature or give it a
uid and it stops resolving, and the failure is silent (every caller falls
back to CLIENT_ID_DEFAULT and shares one quota bucket).
default: jwt.identity-VJ-iap-egress-jwt.decoded.claim.iam_principal
- name: IAP_JWT_ALGORITHM
displayName: IAP egress JWT algorithm
description: >-
Signing algorithm of the gateway's IAP-egress assertion. VERIFIED LIVE as
ES256 against a real Agent Gateway turn. The source playbook does not
state it, and RS256 is the natural guess -- it is wrong, and it fails
closed: VerifyJWT raises steps.jwt.AlgorithmMismatch, which reaches the
agent as an opaque HTTP 500 and breaks the turn.
default: ES256
examples: ["ES256", "RS256"]
policies:
- name: VJ-iap-egress-jwt
type: VerifyJWT
content:
VerifyJWT:
metadata:
name: VJ-iap-egress-jwt
continueOnError: false
enabled: true
Algorithm: "{IAP_JWT_ALGORITHM}"
# No Audience element on purpose -- see IAP_JWT_ISSUER above.
Issuer: "{IAP_JWT_ISSUER}"
Source: request.header.x-goog-iap-egress-jwt-assertion
PublicKey:
JWKS:
metadata:
uri: "{IAP_JWKS_URI}"
- name: AM-set-client-id
type: AssignMessage
content:
AssignMessage:
metadata:
name: AM-set-client-id
continueOnError: true
enabled: true
IgnoreUnresolvedVariables: true
AssignVariable:
Name: agw.client_id
# Value is the fallback; Ref wins when it resolves.
Value: "{CLIENT_ID_DEFAULT}"
# VERIFIED LIVE: the gateway's IAP-egress assertion carries NO email
# claim. Its claim set is [iss, aud, exp, iat, iam_principal, azp],
# and the identity is iam_principal --
# principal://agents.global.org-<N>.system.id.goog/resources/aiplatform/projects/<P>/...
# Referencing .claim.email silently resolves to nothing, so every
# caller meters as the CLIENT_ID_DEFAULT and per-caller quota becomes
# one shared bucket. Change this only if your gateway mints a
# different assertion.
Ref: "{CLIENT_ID_CLAIM}"
# Declared as a real `endpoints:` entry, not `defaultEndpoint`. This feature is
# the lowest priority (10), so it creates the single no-route endpoint that every
# later feature's `defaultEndpoint` fragment merges into. The template cannot
# supply it: gcloud 588 ignores a template's `endpoints` whenever features are
# present, and a defaultEndpoint merges into endpoints that already exist, so
# with nothing declaring one every flow in every feature is silently discarded.
# Identity's own steps therefore live here rather than under defaultEndpoint,
# which is processed BEFORE feature-declared endpoints are added.
endpoints:
- name: default
basePath: "/"
routes:
- name: noroute
flows:
- name: PreFlow
mode: Request
steps:
- name: VJ-iap-egress-jwt
condition: request.header.x-goog-iap-egress-jwt-assertion != null
- name: AM-set-client-id
feature-model-armor.yaml 3.5 KB
# Feature: Model Armor prompt sanitization.
#
# Blocks unsafe prompts before they reach the model. Unlike the metering
# policies this one is deliberately fail-CLOSED (continueOnError=false) -- a
# safety filter that fails open is not a safety filter.
#
# Because it fails closed, the step condition is load-bearing: ungated it
# fires on session/appendEvent/telemetry calls that carry no prompt, the
# extraction resolves empty, the policy raises, and the agent's turn dies.
#
# Enable by adding this file to the template's `features` list.
#
# REQUIRES feature-normalize.yaml (priority 15). The prompt is read from
# agw.user_prompt, which that feature sets before this one runs. Enabling this
# feature without it leaves the variable unset, the scan resolves empty, and
# because the policy fails closed every matching request 500s.
# See references/gotchas.md, Runtime.
#
# Requires: a Model Armor template in the same region, roles/modelarmor.user
# on the deployment service account, and deploying with ?serviceAccount=.
gateway: apigee
schemaVersion: 1.0.0
name: modelarmor
uid: modelarmor
type: feature
priority: 20
description: >-
Screens the user prompt through a Model Armor template before the model is
called. Blocks on a filter match; the caller sees a 400 with
steps.sanitize.user.prompt.FilterMatched.
parameters:
- name: MA_TEMPLATE_NAME
displayName: Model Armor template resource name
description: Full resource name, projects/<p>/locations/<r>/templates/<t>.
default: projects/PROJECT/locations/REGION/templates/MA_TEMPLATE
- name: LLM_URI_MATCH
displayName: LLM call match condition
description: >-
Gate for the sanitize step. MUST match only calls that actually carry a
prompt. Gemini-native is *generateContent*; the OpenAI tail is
*chat/completions*. Shared with feature-normalize and the cache, so
widening it here widens their blast radius too.
default: '((request.uri Like "*generateContent*") or (request.uri Like "*chat/completions*"))'
- name: MA_CONTINUE_ON_ERROR
displayName: Model Armor enforcement mode
description: >-
"false" = ENFORCE: a filter match faults the policy and the caller gets a
400. "true" = DRY_RUN: the scan still runs and the verdict is still in the
trace, but the fault is swallowed and the turn continues.
This is the blocking switch, NOT an on/off switch -- dropping the step
entirely would mean no evaluation at all, which is "off", not dry-run.
Default is ENFORCE: a security control that silently does not protect is
worse than one that visibly blocks, and silent non-protection is the exact
failure class this skill exists to prevent.
default: "false"
policies:
- name: SUP-sanitize
type: SanitizeUserPrompt
content:
SanitizeUserPrompt:
metadata:
name: SUP-sanitize
# The enforcement switch. See MA_CONTINUE_ON_ERROR above.
continueOnError: "{MA_CONTINUE_ON_ERROR}"
enabled: true
IgnoreUnresolvedVariables: true
ModelArmor:
TemplateName: "{MA_TEMPLATE_NAME}"
# Shape-agnostic, set by feature-normalize at priority 15. A raw
# JSONPath here is written for exactly one wire shape and fails
# closed on any other -- HTTP 500 per request, not a skipped scan.
UserPromptSource: "{agw.user_prompt}"
defaultEndpoint:
name: default
flows:
- name: PreFlow
mode: Request
steps:
- name: SUP-sanitize
condition: "{LLM_URI_MATCH}"
feature-normalize.yaml 4.0 KB
# Feature: shape normalisation (request path).
#
# WHY THIS IS ITS OWN FEATURE, AND WHY IT IS EARLY
#
# More than one feature needs the user's prompt, and each one reads it from a
# JSONPath that assumes a single wire shape:
#
# modelArmor UserPromptSource (priority 20)
# semanticCache UserPromptSource (priority 30)
#
# Point LLM_URI_MATCH at two shapes and those JSONPaths silently stop
# resolving for the shape they were not written for. Model Armor is
# continueOnError=false by design -- it fails CLOSED -- so the result is not a
# missed scan, it is an HTTP 500 on every request of the other shape.
# Verified: widening LLM_URI_MATCH alone took a working OpenAI-shape agent to
# a hard 500, with the trace showing modelarmor-SUP-sanitize faulting and the
# cache policies never reached. See references/gotchas.md, Runtime.
#
# So the prompt has to be normalised ONCE, before anything consumes it. This
# feature sits at priority 15: after identity (10), before Model Armor (20)
# and the cache (30). Both of those then read agw.user_prompt and stop caring
# about the wire shape.
#
# The response-path equivalent -- agw.total_tokens -- lives in
# feature-token-metering.yaml, because it can only run once a response exists.
gateway: apigee
schemaVersion: 1.0.0
name: normalize
uid: normalize
type: feature
priority: 15
description: >-
Extracts the user prompt into agw.user_prompt regardless of wire shape, so
Model Armor and the semantic cache can be shape-agnostic.
parameters:
- name: LLM_URI_MATCH
displayName: LLM call match condition
default: '((request.uri Like "*generateContent*") or (request.uri Like "*chat/completions*"))'
resources:
- name: extract-prompt.js
type: jsc
content: |
// Normalises the user prompt across wire shapes into agw.user_prompt.
// Request-path counterpart to agw.total_tokens in the metering feature.
// Same rationale: one JSONPath cannot select from two body layouts, so
// the choice has to happen in code.
//
// continueOnError is true on the policy below. A failure here must
// leave agw.user_prompt unset rather than break the turn -- consumers
// then behave as they would for an unparseable body.
function lastText(body) {
try {
var j = JSON.parse(body);
// Gemini: contents[-1].parts[-1].text
if (j && j.contents && j.contents.length) {
var c = j.contents[j.contents.length - 1];
if (c && c.parts && c.parts.length) {
var p = c.parts[c.parts.length - 1];
if (p && p.text) return String(p.text);
}
}
// OpenAI: messages[-1].content, which is a string in the simple
// case and an array of {type,text} blocks in the multimodal one.
if (j && j.messages && j.messages.length) {
var m = j.messages[j.messages.length - 1];
if (m && typeof m.content === "string") return m.content;
if (m && m.content && m.content.length) {
var out = "";
for (var i = 0; i < m.content.length; i++) {
if (m.content[i] && m.content[i].text) out += m.content[i].text;
}
if (out) return out;
}
}
} catch (e) {}
return "";
}
var body = context.getVariable("request.content");
var prompt = body ? lastText(body) : "";
if (prompt) { context.setVariable("agw.user_prompt", prompt); }
// Always set, so a trace distinguishes "no prompt found" from "policy
// never ran".
context.setVariable("agw.prompt_len", prompt ? String(prompt.length) : "0");
policies:
- name: JS-extract-prompt
type: Javascript
content:
Javascript:
metadata:
name: JS-extract-prompt
continueOnError: true
enabled: true
timeLimit: "200"
ResourceURL: jsc://extract-prompt.js
defaultEndpoint:
name: default
flows:
- name: PreFlow
mode: Request
steps:
- name: JS-extract-prompt
condition: "{LLM_URI_MATCH}"
feature-semantic-cache.yaml 7.9 KB
# Feature: semantic cache (E2).
#
# Lookup in the Request PreFlow, populate on the response path. On a live
# setup this took a repeat ask from 4743 ms to 336 ms with the model never
# called.
#
# TWO TRAPS, both specific to a no-route proxy. Read before changing anything.
#
# 1. The response flow runs on a cache HIT as well. A conventional proxy hangs
# populate off the target response flow, which a hit never reaches; here
# there is no target, so populate sits in the proxy response flow and a hit
# short-circuits straight into it. Ungated, populate re-embeds and
# re-upserts the answer it just served -- a wasted embed, findNeighbors and
# upsert on the supposedly fast path, plus a duplicate datapoint per hit.
#
# 2. The cache-hit variable is NOT the documented name. Runtime emits
# SemanticCacheLookup.<policy>.cache_hit; the policy reference documents
# semanticcache.lookup.<policy>.cache_hit, which never resolves. An
# unresolved variable makes `!= true` true, so a condition written from the
# docs fails OPEN and the symptom looks exactly like trap 1.
#
# Both are handled by the populate condition below. It is written
# PRE-NAMESPACED because the compiler rewrites step names and jsc:// URLs but
# NOT policy-derived flow variables -- if you rename this feature or give it a
# uid, this condition silently stops matching and you are back to trap 1.
# Both boolean and string comparisons are present because the runtime type was
# not pinned down.
#
# REQUIRES feature-normalize.yaml (priority 15). The prompt is read from
# agw.user_prompt, which that feature sets before this one runs. Without it
# the lookup has nothing to embed and the cache never hits.
#
# Requires: a Vertex AI Vector Search index and index endpoint with a deployed
# index id, an embeddings model, roles/aiplatform.user on the deployment SA,
# and a deploy with ?serviceAccount=.
gateway: apigee
schemaVersion: 1.0.0
name: semanticcache
uid: semanticcache
type: feature
priority: 30
description: >-
Answers a repeated prompt from Vertex AI Vector Search without calling the
model. Looks up on the request path and populates on the response path,
skipping populate on a hit.
parameters:
- name: LLM_URI_MATCH
displayName: LLM call match condition
description: >-
Matches both wire shapes. A single-shape condition disables the cache
for the other one with no error -- indistinguishable from a cache that
works and never hits. Shared with Model Armor, which fails closed, so
never widen this without feature-normalize present.
default: '((request.uri Like "*generateContent*") or (request.uri Like "*chat/completions*"))'
- name: EMBEDDINGS_URL
displayName: Embeddings predict URL
description: >-
THE MODEL FIXES THE INDEX WIDTH, AND THE INDEX IS IMMUTABLE. This policy
takes a URL and nothing else -- <Embeddings><VertexAI><URL> has no
dimensionality parameter -- so the model's NATIVE output width is what
lands in the index, and gemini-embedding-001's MRL truncation cannot be
reached through it. Changing this later is not a config change, it is an
index rebuild. Widths measured live, one :predict call each:
gemini-embedding-001 3072
text-embedding-005 768 <- default
text-multilingual-embedding-002 768
text-embedding-004 768 (still serves, but has dropped
off the supported-models list)
text-embedding-005 is the default because it is supported and 768 is
ample for cache duty -- deciding whether a prompt resembles one seen in
the last 60 seconds. gemini-embedding-001 is the stronger model but costs
4x the vector storage and more compute per query for no gain at this job,
and needs a 3072 index built for it.
scripts/ensure_vector_search.sh refuses on a width mismatch rather than
letting it surface at runtime.
default: https://REGION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/REGION/publishers/google/models/text-embedding-005:predict
- name: FIND_NEIGHBORS_URL
displayName: Vector Search findNeighbors URL
description: >-
Host is the index endpoint's OWN domain, not the regional aiplatform
host. INDEX_ENDPOINT_DOMAIN is substituted at deploy time by
deploy_proxy.sh (--index-endpoint-id), NOT supplied by the user: the
domain's leading label is assigned at endpoint-creation time and matches
neither the index id, the endpoint id, nor the project number, so it can
only be read back with
`gcloud ai index-endpoints describe ... --format='value(publicEndpointDomainName)'`.
That is why the input file has no field for it.
default: https://INDEX_ENDPOINT_DOMAIN/v1/projects/PROJECT/locations/REGION/indexEndpoints/INDEX_ENDPOINT_ID:findNeighbors
- name: UPSERT_URL
displayName: Vector Search upsertDatapoints URL
default: https://REGION-aiplatform.googleapis.com/v1/projects/PROJECT/locations/REGION/indexes/INDEX_ID:upsertDatapoints
- name: DEPLOYED_INDEX_ID
displayName: Deployed index id
description: Rendered into <DeployedIndexID>. All-caps ID; DeployedIndexId fails bundle validation.
default: agent_gateway_llm_cache
- name: SIMILARITY_THRESHOLD
default: "0.95"
- name: CACHE_TTL_SECONDS
default: "60"
policies:
- name: SCL-lookup
type: SemanticCacheLookup
content:
SemanticCacheLookup:
metadata:
name: SCL-lookup
continueOnError: false
enabled: true
IgnoreUnresolvedVariables: false
# Shape-agnostic, set by feature-normalize at priority 15.
UserPromptSource: "{agw.user_prompt}"
Embeddings:
VertexAI:
URL: "{EMBEDDINGS_URL}"
SimilaritySearch:
VertexAI:
URL: "{FIND_NEIGHBORS_URL}"
DeployedIndexID: "{DEPLOYED_INDEX_ID}"
Threshold: "{SIMILARITY_THRESHOLD}"
- name: SCP-populate
type: SemanticCachePopulate
content:
SemanticCachePopulate:
metadata:
name: SCP-populate
continueOnError: false
enabled: true
IgnoreUnresolvedVariables: true
SimilaritySearch:
VertexAI:
URL: "{UPSERT_URL}"
TTLInSeconds: "{CACHE_TTL_SECONDS}"
defaultEndpoint:
name: default
flows:
- name: PreFlow
mode: Request
steps:
- name: SCL-lookup
condition: "{LLM_URI_MATCH}"
# PostFlow/Response, not PreFlow/Response: AFT emits one element per Flow
# entry, so a second Flow named PreFlow would produce invalid XML. See
# references/gotchas.md.
- name: PostFlow
mode: Response
steps:
- name: SCP-populate
# response.status.code is load-bearing, and is the ONLY defence
# available today. SemanticCachePopulate is status-blind: gated
# only on cache_hit it will store ANY response, an upstream error
# included. Measured -- a transient 429 from a throttled model was
# written to the cache and then replayed, as HTTP 200, to every
# identical prompt for the whole TTL. A momentary blip became a
# persistent wrong answer served with a success status, invisible
# to metering (token_source=none, used.count=0 throughout).
#
# Raised with the Apigee team: the policy should not cache non-2xx
# by default, or should expose an eligibility control. Until that
# lands, keep this gate.
#
# 200-only is deliberate. It also declines 3xx and any future
# partial-success shape, which is right for a cache whose entries
# are replayed without further inspection.
condition: >-
{LLM_URI_MATCH}
and (response.status.code = 200)
and (SemanticCacheLookup.semanticcache-SCL-lookup.cache_hit != true)
and (SemanticCacheLookup.semanticcache-SCL-lookup.cache_hit != "true")
feature-token-enforce.yaml 16.4 KB
# Feature: per-model LLM token ENFORCEMENT.
#
# Optional and off by default, because it REFUSES traffic. Add it to the
# template's feature list to turn a budget into a limit.
#
# ---------------------------------------------------------------------------
# HOW IT WORKS
# ---------------------------------------------------------------------------
# LLMTokenQuota splits enforcement from counting across two policies that
# share a <SharedName>:
#
# request flow EnforceOnly=true reads the counter, refuses if over
# response flow CountOnly=true increments the counter, never refuses
#
# feature-token-metering.yaml owns the CountOnly half and runs unchanged.
# Exactly one of CountOnly/EnforceOnly may be set on a given policy.
#
# ENFORCEMENT IS ONE REQUEST LATE, BY CONSTRUCTION. The counter cannot include
# the current turn, because its cost does not exist until the model has
# answered. The turn that crosses the limit COMPLETES, and the caller's NEXT
# request is refused. Inherent, not a defect -- state it when offering this.
#
# ---------------------------------------------------------------------------
# VERIFIED LIVE
# ---------------------------------------------------------------------------
# Confirmed in the shape that matters: a no-route proxy invoked as
# EXT_PROC_GRPC by an Agent Gateway, on real Agent Runtime traffic, where the
# request and response phases arrive as separate gRPC messages.
#
# The over-budget turn was refused and the caller received:
#
# 429 Too Many Requests
# faultstring: "Rate limit LLM Token quota violation. Quota limit exceeded.
# Identifier : principal://agents.global.org-..."
#
# From that transaction's trace, flash budget 500/hour:
#
# ratelimit.enforce-LTQ-flash.used.count = 1086 <- written by CountOnly
# ratelimit.enforce-LTQ-flash.allowed.count = 500
# ratelimit.enforce-LTQ-flash.exceed.count = 586
# ratelimit.enforce-LTQ-flash.failed = true
# error.state = PROXY_REQ_FLOW
#
# The request-path EnforceOnly policy read 1086 -- exactly what the
# response-path CountOnly policy had accumulated under the same SharedName --
# compared it against 500, and refused before the model was called. So the
# SharedName linkage does join the two halves in a no-route ext-proc proxy.
#
# <Identifier> ALSO SCOPES PER CALLER on the enforce half, confirmed in the
# same trace: ratelimit.*.identifier resolved to the calling agent's
# principal, not a shared bucket. It behaves the same as on the count half.
#
# An earlier report of "0 refusals at any budget" was a test harness pointed
# at a different project, so that traffic never reached the proxy under test.
# Not a platform defect.
#
# ---------------------------------------------------------------------------
# TWO TRAPS THAT BOTH PRODUCE "IT NEVER REFUSES"
# ---------------------------------------------------------------------------
# 1. BUCKETING ON A RAW URI SUBSTRING. The enforce half must bucket on the
# REQUESTED model, derived from the request. Testing the whole URI for a
# model name is unsafe, because
# /v1beta1/projects/.../models/gemini-4-hydrogen:generateContent
# contains "pro" inside *pro*jects. A `request.uri Like "*pro*"` condition
# therefore matches a FLASH request, routes it to the pro bucket, finds
# headroom there and allows -- while the count half correctly bills flash.
# That is indistinguishable from a broken platform and is a config error.
#
# The JS below anchors the match after `models/` precisely for this, and
# buckets on the extracted name rather than on the URI. Do not "simplify"
# it into a substring test on request.uri.
#
# 2. OMITTING <LLMModelSource>, which is required -- see the note on the
# policies below. That one fails loudly rather than silently.
#
# ---------------------------------------------------------------------------
# THE BUCKET DISAGREEMENT, WHICH IS REAL AND DELIBERATE
# ---------------------------------------------------------------------------
# The counting side buckets on the RESOLVED model, read from the response
# body. At request time that does not exist, so this side buckets on the
# REQUESTED model -- the alias in the request body, or the name in the URI.
#
# For Gemini-native traffic the two agree: the URI carries the real model.
# For an OpenAI-compatible endpoint the request carries an ALIAS, which the
# provider may resolve to a different model. A caller asking for "fast-model"
# that resolves to a pro model is ENFORCED against the flash bucket and
# COUNTED against the pro bucket. Everything is still counted and still
# checked; it is only unsafe if someone assumes a per-model limit is exact
# under aliasing.
#
# ---------------------------------------------------------------------------
# continueOnError IS false HERE, AND ONLY HERE
# ---------------------------------------------------------------------------
# The skill's standing rule is that metering must never fail closed: a bug in
# your own observability must not break LLM traffic. These policies are the
# deliberate exception, because refusing is their entire purpose -- a quota
# violation that is swallowed is not enforcement. The cost is that a quota
# policy ERROR also refuses, which is what the missing LLMModelSource did to
# every turn before it was found.
gateway: apigee
schemaVersion: 1.0.0
name: enforce
uid: enforce
# After identity (10), which sets agw.client_id -- the Identifier below needs
# it. Before normalize (15) and everything downstream: a refused request
# should not pay for prompt extraction, Model Armor or a cache lookup.
priority: 12
type: feature
description: >-
Refuses a request when the caller has already exhausted its token budget
for the model it is asking for. Reads the counters feature-token-metering
writes; never increments them. One request late by construction.
parameters:
# These MUST match the corresponding *_TOKEN_LIMIT values in
# feature-token-metering.yaml. They are separate parameters because AFT does
# not share parameters across features, and a mismatch is silent: the
# enforce half would refuse at a different threshold than the count half
# reports against. Keep them in step, and prefer changing both or neither.
- name: PRO_TOKEN_LIMIT
default: "10000"
- name: FLASH_TOKEN_LIMIT
default: "40000"
- name: OTHER_TOKEN_LIMIT
default: "40000"
- name: QUOTA_INTERVAL
default: "1"
- name: QUOTA_TIME_UNIT
default: hour
# Byte-identical to the other features that declare it. They must match:
# each feature resolves its OWN default (gcloud passes an empty caller map),
# so a difference here is a silently different gate, not an override.
- name: LLM_URI_MATCH
default: '((request.uri Like "*generateContent*") or (request.uri Like "*chat/completions*"))'
resources:
- name: extract-model-request.js
type: jsc
content: |
// Request-phase model bucket, for the enforce-only quotas.
//
// Only request-available sources: the OpenAI-compatible alias in the
// body, and the Gemini-native model name in the URI. The resolved name
// lives in the response body and does not exist yet -- which is exactly
// why enforcement buckets on the requested model and can disagree with
// the bucket the counting side later uses. See the header.
//
// Bucketing is kept byte-identical to extract-model.js so the two sides
// agree whenever the requested and resolved names agree. If you change
// one, change the other.
function readField(v, field) {
try {
var b = context.getVariable(v);
if (b) { var j = JSON.parse(b); if (j && j[field]) return String(j[field]); }
} catch (e) {}
return "";
}
function readModelFromUri() {
try {
var u = context.getVariable("request.uri");
if (u) { var m = String(u).match(/\/models\/([^:\/?]+)/); if (m) return m[1]; }
} catch (e) {}
return "";
}
var raw = readField("request.content", "model")
|| readModelFromUri()
|| "unknown";
var ml = raw.toLowerCase(), bucket = "other";
if (ml.indexOf("pro") >= 0 || ml.indexOf("argon") >= 0) bucket = "gemini-pro";
else if (ml.indexOf("flash") >= 0 || ml.indexOf("hydrogen") >= 0) bucket = "gemini-flash";
context.setVariable("agw.req_model_bucket", bucket);
context.setVariable("agw.req_model_raw", raw);
policies:
- name: JS-extract-model-request
type: Javascript
content:
Javascript:
metadata:
name: JS-extract-model-request
# Stays true: a bucketing failure must not refuse the request. It
# falls through to the "other" bucket, which is still enforced.
continueOnError: true
enabled: true
timeLimit: "200"
ResourceURL: jsc://extract-model-request.js
# Three enforce policies, one per SharedName, because <SharedName> is a
# static literal per policy -- it is the join key to the CountOnly half and
# cannot be templated per request. One bucket therefore needs one policy,
# each with its own Allow count. The step condition picks which one runs.
# (Each still sets <LLMModelSource>; see the note on the first policy.)
- name: LTQ-enforce-pro
type: LLMTokenQuota
content:
LLMTokenQuota:
metadata:
name: LTQ-enforce-pro
# false ON PURPOSE -- see the header. This is the only place in the
# skill that fails closed on a quota.
continueOnError: false
enabled: true
SharedName: llm-tokens-pro
Allow:
metadata:
count: "{PRO_TOKEN_LIMIT}"
Interval: "{QUOTA_INTERVAL}"
TimeUnit: "{QUOTA_TIME_UNIT}"
EnforceOnly: "true"
Distributed: true
Synchronous: true
Identifier:
metadata:
ref: agw.client_id
# REQUIRED. Omitting this does NOT mean "this policy needs no model".
# The policy substitutes a DEFAULT of
# jsonPath('$.model', request.content, true)
# and on a Gemini-native :generateContent call the model is in the URI,
# not the body -- so it resolves to nothing, raises
# FailedToResolveModelName, and because these policies are
# continueOnError="false" the fault kills EVERY governed turn, not just
# over-budget ones. Confirmed as a live outage (FINDINGS F12).
# Feed it the bucket this feature's own JS computed one step earlier.
LLMModelSource: "{agw.req_model_bucket}"
- name: LTQ-enforce-flash
type: LLMTokenQuota
content:
LLMTokenQuota:
metadata:
name: LTQ-enforce-flash
continueOnError: false
enabled: true
SharedName: llm-tokens-flash
Allow:
metadata:
count: "{FLASH_TOKEN_LIMIT}"
Interval: "{QUOTA_INTERVAL}"
TimeUnit: "{QUOTA_TIME_UNIT}"
EnforceOnly: "true"
Distributed: true
Synchronous: true
Identifier:
metadata:
ref: agw.client_id
# REQUIRED. Omitting this does NOT mean "this policy needs no model".
# The policy substitutes a DEFAULT of
# jsonPath('$.model', request.content, true)
# and on a Gemini-native :generateContent call the model is in the URI,
# not the body -- so it resolves to nothing, raises
# FailedToResolveModelName, and because these policies are
# continueOnError="false" the fault kills EVERY governed turn, not just
# over-budget ones. Confirmed as a live outage (FINDINGS F12).
# Feed it the bucket this feature's own JS computed one step earlier.
LLMModelSource: "{agw.req_model_bucket}"
- name: LTQ-enforce-other
type: LLMTokenQuota
content:
LLMTokenQuota:
metadata:
name: LTQ-enforce-other
continueOnError: false
enabled: true
SharedName: llm-tokens-other
Allow:
metadata:
count: "{OTHER_TOKEN_LIMIT}"
Interval: "{QUOTA_INTERVAL}"
TimeUnit: "{QUOTA_TIME_UNIT}"
EnforceOnly: "true"
Distributed: true
Synchronous: true
Identifier:
metadata:
ref: agw.client_id
# REQUIRED. Omitting this does NOT mean "this policy needs no model".
# The policy substitutes a DEFAULT of
# jsonPath('$.model', request.content, true)
# and on a Gemini-native :generateContent call the model is in the URI,
# not the body -- so it resolves to nothing, raises
# FailedToResolveModelName, and because these policies are
# continueOnError="false" the fault kills EVERY governed turn, not just
# over-budget ones. Confirmed as a live outage (FINDINGS F12).
# Feed it the bucket this feature's own JS computed one step earlier.
LLMModelSource: "{agw.req_model_bucket}"
# Sanitises the refusal the caller sees. LLMTokenQuota's own faultstring
# interpolates <Identifier>, and ours is a ref to agw.client_id -- the
# gateway's assertion about the calling workload. Unmodified, an over-budget
# caller is handed the full principal:
#
# Identifier : principal://agents.global.org-<ORG_NUMBER>.system.id.goog
# /resources/aiplatform/projects/<PROJECT_NUMBER>/locations/<REGION>
# /reasoningEngines/<ENGINE_ID>
#
# That is the org number, the project number, the region and the agent's
# resource id, in an error body that reaches whoever called the agent. Fine
# in a demo you own end to end; an information-disclosure finding in a
# customer deployment, where the caller may be an end user.
#
# The replacement keeps the SHAPE and the ERRORCODE so anything branching on
# `policies.llmtokenquota.LLMTokenQuotaViolation` keeps working, and drops
# only the `Identifier : ...` clause. The identifier is still in the proxy's
# own analytics and debug trace, which is where it belongs.
#
# continueOnError is TRUE on purpose, and it is the opposite of the quota
# policies above. This policy does not decide anything: if it fails, the
# original fault still stands and the caller is still refused, just with the
# unsanitised message. Failing closed here would turn a cosmetic problem
# into a dropped refusal.
- name: AM-quota-refusal
type: AssignMessage
content:
AssignMessage:
metadata:
name: AM-quota-refusal
continueOnError: true
enabled: true
IgnoreUnresolvedVariables: true
Set:
StatusCode: "429"
ReasonPhrase: Too Many Requests
Payload:
metadata:
contentType: application/json
_text: >-
{"fault":{"faultstring":"Rate limit LLM Token quota violation.
Quota limit exceeded.","detail":{"errorcode":"policies.llmtokenquota.LLMTokenQuotaViolation"}}}
AssignTo:
metadata:
createNew: "false"
type: response
defaultEndpoint:
name: default
flows:
- name: PreFlow
mode: Request
steps:
# Gated on LLM_URI_MATCH like every other step in this template. The
# ext-proc sees every agent egress -- session create/read,
# appendEvent, OpenTelemetry exports -- and refusing one of those
# because a model budget is exhausted would break the turn for a call
# that consumed no tokens.
- name: JS-extract-model-request
condition: "{LLM_URI_MATCH}"
- name: LTQ-enforce-pro
condition: >-
{LLM_URI_MATCH} and agw.req_model_bucket = "gemini-pro"
- name: LTQ-enforce-flash
condition: >-
{LLM_URI_MATCH} and agw.req_model_bucket = "gemini-flash"
- name: LTQ-enforce-other
condition: >-
{LLM_URI_MATCH} and agw.req_model_bucket = "other"
# A fault rule, not a flow step: the quota policies run continueOnError
# "false", so the moment one refuses, the request flow stops and no later
# step runs. The only place left to touch the response is fault handling.
#
# A fault rule has no request/response phase -- do NOT give it a `mode`.
# models.FaultRule inherits `mode` from Flow, so it parses, but the
# converter logs "Ignoring mode ... a fault rule has no request or
# response" and drops it.
#
# The fault still happens and the caller is still refused. This only
# rewrites what they are shown.
faultRules:
- name: quota-refusal
condition: (fault.name = "LLMTokenQuotaViolation")
steps:
- name: AM-quota-refusal
feature-token-metering.yaml 15.0 KB
# Feature: per-model LLM token metering.
#
# Runs in the Response PreFlow, because both request.content (persisted) and
# response.content are available there and response.content is the documented
# source for `usage`.
#
# Model normalisation matters: with an OpenAI-compatible endpoint the model is
# an alias in the REQUEST body ($.model, e.g. "gemini-flash") while the
# RESOLVED name is in the RESPONSE body ("google/gemini-4-argon"). Exact-match
# step conditions on the raw string therefore fail on the response path. The
# JS below collapses both into a stable bucket and the per-model counters key
# on that bucket.
#
# One LLMTokenQuota per model, each with its own SharedName -- distinct
# SharedName is what makes the counters independent.
gateway: apigee
schemaVersion: 1.0.0
name: metering
uid: metering
type: feature
priority: 50
description: >-
Meters LLM token usage per model bucket, keyed on the caller identity.
Count-only by default: it observes and meters, it does not gate.
# No TOKEN_USAGE_JSONPATH parameter, deliberately. The token count is
# normalised in JS below and read from agw.total_tokens instead. A JSONPath
# can only SELECT a field that already exists: it cannot choose between wire
# shapes, and it cannot compute. Anthropic's Messages API reports
# input_tokens and output_tokens with no total, so no single JSONPath can
# express it at all. Keeping the parameter would leave a knob that appears to
# select the source and no longer does -- see the COUNT_ONLY note below for
# why that shape of knob was removed rather than reworded.
parameters:
- name: PRO_TOKEN_LIMIT
default: "10000"
- name: FLASH_TOKEN_LIMIT
default: "40000"
# Catch-all. Every model that is not Gemini pro/argon or flash/hydrogen lands
# in the "other" bucket -- gpt-oss, Llama, Qwen, DeepSeek, anything reached
# through model
# routing later. Without a quota bound to it those calls consume NO quota
# at all and nothing reports the gap. Measured with gpt-oss-120b-maas: the
# token count extracted correctly, then zero ratelimit references in the
# whole transaction. That is worse than a resolution failure, which at
# least surfaces FailedToResolveTokenUsageCount in a trace.
# See references/gotchas.md, Runtime.
- name: OTHER_TOKEN_LIMIT
default: "40000"
- name: QUOTA_INTERVAL
default: "1"
- name: QUOTA_TIME_UNIT
default: hour
# These quotas ship CountOnly=true. That is a DEFAULT, not a limitation --
# see the correction below.
#
# What is true, and was verified live: a single quota with CountOnly=false in
# the RESPONSE flow cannot deny, and breaks counting while failing to gate.
#
# 1. It cannot deny. These policies run in PostFlow/Response, because the
# token count only exists once the model has answered. By then the
# response is already on the wire, so there is nothing left to withhold:
# Apigee aborts and emits 429 while the caller still receives the full
# answer with finish_reason STOP.
# 2. It breaks counting. A blocking quota refuses to count the request that
# violated it, so the counter freezes at the limit for the rest of the
# window. You lose the metering that was working and gain no gating.
#
# CORRECTION. An earlier version of this comment concluded from the above
# that enforcement "cannot work" here. That is wrong, and the conclusion did
# not follow: it is a property of putting ONE policy in the response flow,
# not of the policy type. LLMTokenQuota has a first-class split for exactly
# this, documented under "Configuring shared quota counters":
#
# request flow LLMTokenQuota <EnforceOnly>true</EnforceOnly>
# response flow LLMTokenQuota <CountOnly>true</CountOnly>
#
# Both carry the SAME <SharedName>, so the request-flow policy checks the
# counter the response-flow policy increments. Exactly one of CountOnly and
# EnforceOnly may be set on a given policy. The enforce policy carries no
# <LLMTokenUsageSource> -- it only reads the counter -- but it DOES still
# need <LLMModelSource>, which is not optional: omitting it substitutes a
# body JSONPath that cannot resolve a Gemini-native model and refuses every
# turn. See feature-token-enforce.yaml and references/gotchas.md.
#
# The product's own sample for this pattern is a <RouteRule name="noroute"/>
# proxy, i.e. our shape, so a no-target processor is not an obstacle.
#
# Enforcement is therefore one request LATE by construction, and that is
# inherent rather than a defect: the turn that crosses the limit still
# completes, and the NEXT request for that caller is refused. A token budget
# cannot be enforced before the tokens are known.
#
# Shipped as feature-token-enforce.yaml, and verified live: an over-budget
# caller was refused with 429 on ext-proc gateway traffic, the model was
# never called, used.count 1086 against allowed.count 500. This file owns
# the CountOnly half only and runs unchanged when enforcement is added.
resources:
- name: extract-model.js
type: jsc
content: |
// Reads a field out of a JSON body variable. Returns "" on anything
// unexpected -- this runs continueOnError="true" and must never throw.
function readField(v, field) {
try {
var b = context.getVariable(v);
if (b) { var j = JSON.parse(b); if (j && j[field]) return String(j[field]); }
} catch (e) {}
return "";
}
// Gemini-native puts the model in the URI, not the body:
// .../publishers/google/models/gemini-4-hydrogen:generateContent
function readModelFromUri() {
try {
var u = context.getVariable("request.uri");
if (u) { var m = String(u).match(/\/models\/([^:\/?]+)/); if (m) return m[1]; }
} catch (e) {}
return "";
}
// Order matters. OpenAI-compatible carries $.model in the request (an
// alias) and in the response (resolved). Gemini-native carries NO model
// in the request at all and "modelVersion" in the response, so the body
// lookups below must not stop at the OpenAI names.
var raw = readField("request.content", "model")
|| readField("response.content", "modelVersion")
|| readField("response.content", "model")
|| readModelFromUri()
|| "unknown";
var ml = raw.toLowerCase(), bucket = "other";
if (ml.indexOf("pro") >= 0 || ml.indexOf("argon") >= 0) bucket = "gemini-pro";
else if (ml.indexOf("flash") >= 0 || ml.indexOf("hydrogen") >= 0) bucket = "gemini-flash";
context.setVariable("agw.model_name", bucket);
context.setVariable("agw.requested_model", raw);
// ---- token count, normalised across wire shapes --------------------
// This file already normalises the MODEL across shapes; the count is
// the other half, and doing it here is what lets ONE proxy meter more
// than one shape. readField above is top-level only; the Gemini count
// is nested, so this needs a path walker.
function readPath(v, path) {
try {
var b = context.getVariable(v);
if (!b) return "";
var j = JSON.parse(b);
for (var i = 0; i < path.length; i++) {
if (j === null || typeof j !== "object") return "";
j = j[path[i]];
if (j === undefined || j === null) return "";
}
return String(j);
} catch (e) {}
return "";
}
var tot = "", src = "";
tot = readPath("response.content", ["usageMetadata", "totalTokenCount"]);
if (tot) { src = "gemini"; }
if (!tot) {
tot = readPath("response.content", ["usage", "total_tokens"]);
if (tot) { src = "openai"; }
}
if (!tot) {
// Shapes reporting no single total -- Anthropic's Messages API is
// the usual example, carrying input_tokens and output_tokens
// separately. Summing is precisely what a JSONPath cannot express.
// NOT VERIFIED: Claude is not enabled in the test project, so this
// branch is written from the documented shape and is untested.
var pin = readPath("response.content", ["usage", "input_tokens"]);
var out = readPath("response.content", ["usage", "output_tokens"]);
if (pin || out) {
tot = String((parseInt(pin || "0", 10)) + (parseInt(out || "0", 10)));
src = "sum";
}
}
// Deliberately NOT defaulted to 0. A zero meters silently and wrongly;
// leaving it unset lets LLMTokenQuota raise
// FailedToResolveTokenUsageCount, which at least appears in a trace.
// agw.token_source is always set -- "none" when nothing matched -- so
// an unmetered request can be diagnosed without guessing.
if (tot) { context.setVariable("agw.total_tokens", tot); }
context.setVariable("agw.token_source", src || "none");
policies:
- name: JS-extract-model
type: Javascript
content:
Javascript:
metadata:
name: JS-extract-model
continueOnError: true
enabled: true
timeLimit: "200"
# ResourceURL is namespace-rewritten by the compiler (the "://<name>"
# form is recognised), so it is written un-prefixed here.
ResourceURL: jsc://extract-model.js
- name: LTQ-count-pro
type: LLMTokenQuota
content:
LLMTokenQuota:
metadata:
name: LTQ-count-pro
continueOnError: true
enabled: true
SharedName: llm-tokens-pro
Allow:
metadata:
count: "{PRO_TOKEN_LIMIT}"
Interval: "{QUOTA_INTERVAL}"
TimeUnit: "{QUOTA_TIME_UNIT}"
CountOnly: "true" # hardcoded -- see the note above the parameter list
Distributed: true
Synchronous: true
Identifier:
metadata:
ref: agw.client_id
LLMTokenUsageSource: "{agw.total_tokens}"
LLMModelSource: "{agw.model_name}"
- name: LTQ-count-flash
type: LLMTokenQuota
content:
LLMTokenQuota:
metadata:
name: LTQ-count-flash
continueOnError: true
enabled: true
SharedName: llm-tokens-flash
Allow:
metadata:
count: "{FLASH_TOKEN_LIMIT}"
Interval: "{QUOTA_INTERVAL}"
TimeUnit: "{QUOTA_TIME_UNIT}"
CountOnly: "true" # hardcoded -- see the note above the parameter list
Distributed: true
Synchronous: true
Identifier:
metadata:
ref: agw.client_id
LLMTokenUsageSource: "{agw.total_tokens}"
LLMModelSource: "{agw.model_name}"
# Catch-all quota. Identical in shape to the two above, bound to the bucket
# every non-Gemini model falls into, with its own SharedName so third-party
# traffic does not consume a Gemini allowance.
#
# This is the cheap fix for the silently-unmetered non-Gemini model
# described in references/gotchas.md. Note the limitation it leaves: the
# `models:` list in apigee-agent-gateway-governance.yaml reads as
# authoritative but generates nothing, so adding a model is a feature-file
# edit rather than a config change.
- name: LTQ-count-other
type: LLMTokenQuota
content:
LLMTokenQuota:
metadata:
name: LTQ-count-other
continueOnError: true
enabled: true
SharedName: llm-tokens-other
Allow:
metadata:
count: "{OTHER_TOKEN_LIMIT}"
Interval: "{QUOTA_INTERVAL}"
TimeUnit: "{QUOTA_TIME_UNIT}"
CountOnly: "true" # hardcoded -- see the note above the parameter list
Distributed: true
Synchronous: true
Identifier:
metadata:
ref: agw.client_id
LLMTokenUsageSource: "{agw.total_tokens}"
LLMModelSource: "{agw.model_name}"
- name: AM-quota-headers
type: AssignMessage
content:
AssignMessage:
metadata:
name: AM-quota-headers
continueOnError: true
enabled: true
IgnoreUnresolvedVariables: true
Set:
Headers:
Header:
- metadata:
name: x-agw-model
_text: "{agw.model_name}"
- metadata:
name: x-agw-client-id
_text: "{agw.client_id}"
# NOTE ON FLOW PLACEMENT. The source playbook puts these steps in the
# ProxyEndpoint *PreFlow* Response. AFT cannot express that alongside a
# PreFlow Request: models.Flow carries a single `mode`, so a PreFlow with both
# phases would have to be two Flow entries named PreFlow, and the converter
# emits one <PreFlow> element per entry -- two sibling <PreFlow> elements,
# which is not valid ProxyEndpoint XML. PostFlow/Response is the shape AFT's
# own fixtures use and emits a distinct, valid <PostFlow>. Both run on the
# response path; PostFlow simply runs later in it.
# VERIFY ON A LIVE ORG: this is a deviation from the verified playbook setup.
defaultEndpoint:
name: default
flows:
- name: PostFlow
mode: Response
steps:
# Deliberately UNGATED on cache_hit: it sets agw.model_name, which
# AM-quota-headers still needs in order to report a model on a cache
# hit. Gating it would save a little wasted work and empty the header.
- name: JS-extract-model
# The cache_hit clauses stop a cache hit being billed as an inference.
# On a hit the replayed response still carries usageMetadata and
# request.uri still ends in :generateContent, so without them the quota
# counts tokens the model never produced. Measured: the flash counter
# moved 683 -> 780 on a hit -- exactly the 97 tokens of the replayed
# answer -- with Gemini never called.
#
# This references a policy owned by feature-semantic-cache.yaml, the
# one cross-feature coupling in this template. It degrades safely: with
# the cache disabled the variable never resolves, and an unresolved
# variable makes `!= true` true, so metering is unchanged. The same
# fail-open that is a bug for populate is the correct behaviour here.
- name: LTQ-count-pro
condition: >-
agw.model_name = "gemini-pro"
and (SemanticCacheLookup.semanticcache-SCL-lookup.cache_hit != true)
and (SemanticCacheLookup.semanticcache-SCL-lookup.cache_hit != "true")
- name: LTQ-count-flash
condition: >-
agw.model_name = "gemini-flash"
and (SemanticCacheLookup.semanticcache-SCL-lookup.cache_hit != true)
and (SemanticCacheLookup.semanticcache-SCL-lookup.cache_hit != "true")
# Same cache_hit gating as the two above -- a replayed answer is not
# an inference whichever bucket served it.
- name: LTQ-count-other
condition: >-
agw.model_name = "other"
and (SemanticCacheLookup.semanticcache-SCL-lookup.cache_hit != true)
and (SemanticCacheLookup.semanticcache-SCL-lookup.cache_hit != "true")
# Ungated: a hit should still return the model and client-id headers.
- name: AM-quota-headers
attribution.md 1.9 KB
# Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command with
this skill, follow these usage attribution instructions. Tag every command you
execute directly in the terminal so usage can be attributed. The tag identifies
only the skill and its version; it carries no user data.
- **`gcloud` CLI Commands**: Prefix every `gcloud` invocation, whatever the
subcommand, with the metrics environment variable. Set it inline on each
command because shell state may not persist between commands:
```bash
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:apigee-agent-gateway-governance)" \
gcloud <command> [flags]
```
Do not use `gcloud config set` for this: it would persist beyond the current
task and mislabel unrelated usage.
- **Direct HTTP, REST, and MCP Requests**: On direct HTTP calls to Google
Cloud APIs (for example with `curl`) or HTTP requests to a remote MCP
server, include
`agent-skills/1.0 (skill:apigee-agent-gateway-governance)`
in the `User-Agent` header. If a `User-Agent` header is already specified,
append this string to the end of it rather than overwriting existing
`User-Agent` data — the collection pipeline parses the
`agent-skills/<version>` and `skill:<name>` tokens, so any rewording breaks
attribution:
```text
User-Agent: <existing_user_agent> agent-skills/1.0 (skill:apigee-agent-gateway-governance)
```
- **Constraint for Generated Code**: The tracking prefix is strictly for
commands you execute directly in the terminal. Do NOT include this tracking
prefix in generated scripts, Terraform templates, or code provided to the
user for their own repositories.
- **User Opt-Out**: If the user asks to disable or remove tracking or
attribution tags, omit the `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` variable
and custom `User-Agent` suffix from all commands.
gotchas.md 43.6 KB
# Failure modes, by symptom
Four groups. **Runtime** gotchas come from a working ext-proc setup and were
observed live. **Authoring** gotchas were found compiling this template through
the gcloud AFT compiler and apply to anyone writing AFT features. **Tooling**
and **Agent Gateway** gotchas were hit standing this up against a live org.
## Contents
- [Runtime](#runtime): lines 15-566
- [Authoring (AFT)](#authoring-aft): lines 567-635
- [Tooling and environment](#tooling-and-environment): lines 636-720
- [Agent Gateway](#agent-gateway): lines 721-836
## Runtime
**Every agent request returns 404 the moment you attach the AuthzPolicy, and the
extension is never invoked.** The environment hosting the ext-proc proxy is
attached to more than one envgroup. It must be in exactly one.
A debug session captures nothing and Cloud Monitoring records no requests, so it
looks like a networking or callout problem — but the callout target is fine.
**The one curl below is a reachability probe and nothing more.** From *inside
the VPC*, `curl -k -H "Host: <hostname>" https://<psc-ip>/` returns HTTP 200,
which proves only that the PSC endpoint and DNS resolve. It carries no
IAP-egress JWT and no agent body, so it exercises neither the callout nor a
single policy. **Never offer it as a way to test whether the integration
works** — that is a debug session against live agent traffic, and there is no
substitute. Count the environment's envgroups before suspecting anything else:
```bash
for g in $(curl -s -H "Authorization: Bearer $TOKEN" \
".../organizations/$ORG/envgroups" | python3 -c \
"import json,sys; print(' '.join(g['name'] for g in json.load(sys.stdin)['environmentGroups']))"); do
echo -n "$g -> "; curl -s -H "Authorization: Bearer $TOKEN" \
".../organizations/$ORG/envgroups/${g}/attachments" | python3 -c \
"import json,sys; print([a.get('environment') for a in json.load(sys.stdin).get('environmentGroupAttachments',[])])"
done
```
Isolated by changing one variable at a time against a working setup. These are
**not** causes, each individually disproved: a second CUSTOM AuthzPolicy on the
gateway, gateway `registries`, the extension's `wireFormat` / `failOpen`, a
`.local` callout domain, and a leading colon in the AuthzPolicy path suffix.
Two of those are worth stating positively, because both look plausible enough to
cost someone an afternoon. A `.local` callout domain resolves fine — the gateway
reaches it over DNS peering, where multicast DNS never enters the picture. And
the shipped `:generateContent` suffix, colon included, was re-confirmed against
live traffic on a dedicated environment: the transaction was captured, the
client ID and model were extracted, and the quota counted.
**Attaching a just-created environment fails with `FAILED_PRECONDITION: the
resource is locked by another operation that is 1 percent completed`.** The
environment is *readable* long before it is *ready*. `GET /environments/{env}`
returns 200 while the create operation is still at 1%, so a "wait until I can
fetch it" loop exits immediately and the instance attach is then rejected for
holding a lock.
Poll the create operation instead — the POST returns it, and the error message
names it too:
```bash
curl -s -H "Authorization: Bearer $TOKEN" \
"https://apigee.googleapis.com/v1/organizations/$ORG/operations/$OP_ID"
# done:true, metadata.state:FINISHED, and `error` set if it failed
```
The same lock covers the instance attachment, which takes about four minutes —
a property PATCH issued in that window fails in a way that reads like a
permissions problem. `scripts/ensure_apigee_environment.sh` waits on both
operations.
**The gateway import is rejected: domain "x." does not exist as a private
zone.** `dnsPeeringConfig.domains` is validated against private zones that
already exist in the target VPC, so the zone has to be created *before* the
gateway is patched — earlier than the step order suggests. The zone may be
empty; only its existence is checked, and the A record cannot be written until
the PSC endpoint has an IP anyway. `scripts/ensure_gateway_connectivity.sh`
creates it.
**Deploy fails with `CONFLICTING_DEPLOYMENT`.** Apigee allows one proxy per base
path per environment, and this proxy sits at `/`. On the dedicated environment
the skill now requires, `/` is free and this cannot happen — so hitting it means
the environment is shared, and the 404 above is coming for you next. Fix the
environment, not the base path. The failure surfaces only at deploy time, after
the import has already left an undeployed revision behind, so
`deploy_proxy.sh` enumerates base paths first and names the occupant.
**A non-root base path does work, if you need one.** Verified live: the same
proxy rebuilt with `basePath: "/v1beta1"` was invoked normally and the whole
policy chain ran — the Vertex path the gateway forwards is
`/v1beta1/projects/…/models/gemini-4-hydrogen:generateContent`, so `/v1beta1`
matches it. Proof it really metered rather than merely returning 200: the flash
counter moved 235 → 302, exactly the turn's own 67 tokens.
Two limits before reaching for it. It does **not** let you share an environment
— the 404 is caused by the envgroup count, which base paths have nothing to do
with. And it narrows the proxy permanently: the template also matches
`*/v1/chat/completions*`, and a `/v1beta1` base path can never see those. Use it
only to run a second processor alongside this one in the same dedicated
environment.
**The callout never lands — check the gateway first.** Before suspecting
anything you built, confirm the gateway can reach the VPC at all:
```bash
gcloud network-services agent-gateways describe "$GATEWAY" \
--location="$REGION" --project="$PROJECT" --format='value(networkConfig)'
```
Empty output means the gateway has no egress `networkAttachment` and no
`dnsPeeringConfig`, so it has no route to the Apigee PSC endpoint and cannot
resolve the callout host. Everything downstream still builds and deploys
cleanly. The trap is that the gateway keeps serving ordinary agent traffic
perfectly — that path goes to public Google endpoints and never enters the VPC —
so the agent looks healthy while the callout is dead.
`scripts/ensure_gateway_connectivity.sh` fixes it.
**The callout never lands, and the gateway is fine.** Then it is the hostnames.
The Apigee envgroup hostname, the AuthzExtension `authority`/`service`, and the
private DNS A record must be the same string. Any divergence and nothing arrives
— with no error anywhere.
Check the build order at the same time: **the AuthzExtension is inert until the
callout host resolves and the proxy is deployed.** Creating the extension and
policy before those exist succeeds and reports nothing wrong, and the callout
stays dead until the two catch up. An extension created too early is not
self-healing in any visible way — re-check it once the host and deployment are
in place.
**Policies run but extract nothing.** The AuthzExtension `metadata` needs
`apigee-request-body: 'true'` and `apigee-response-body: 'true'`. Without them
`request.content` and `response.content` are empty and body extraction yields
nothing.
**No error is raised anywhere** — not in the trace, not in the policy, not on
the gateway. The extraction simply resolves empty and everything downstream
carries on, so there is nothing to search for and no failure to diagnose. Do not
go looking for an error message; check the two metadata flags first. This is the
single most common cause of "the policy runs but extracts nothing".
**The agent's turn breaks the moment you add a policy.** Most AI policies
default to `continueOnError="false"`, so on a call carrying no prompt the
extraction resolves empty, the policy raises, and the turn fails.
Whether this bites depends on how broadly the AuthzPolicy matches. With a
suffix list holding only model-call paths, only model calls reach Apigee —
with `:generateContent` alone, unfiltered debug sessions capture exactly one
transaction per turn — so every call the proxy sees carries a prompt. Broaden
the match and the ext-proc sees
*every* agent egress instead: session create and read, `appendEvent`, and the
OpenTelemetry `/v1/metrics`, `/v1/logs` and `/v1/traces` posts. Measured by
widening the policy to `prefix: /` for one single-question turn: **12
transactions, exactly one of them the model call.** The other 11 are promptless,
and each one is a chance for an ungated policy to fault. Gate every step anyway;
it costs a condition and it is what lets the policy be widened safely.
**Token counts never match the per-model counter.** Normalize the model to a
bucket. On an OpenAI-compatible endpoint the request body carries an alias
(`gemini-flash`) and the response body carries the resolved name
(`google/gemini-4-argon`); an exact-match condition on the raw string fails on
the response path.
**The quota policy errors on the token source.** `jsonPath` needs its third
argument `true` to return a scalar. Without it the policy receives a node or
array it cannot parse.
**`total_tokens` exceeds prompt + completion.** Observed: 1135 against 223 for a
thinking model. Metering `usage.total_tokens` bills the full amount, which is
usually intended. The payload does not label the excess, so don't report a
breakdown it doesn't contain.
**A response-path deny does not reach the caller at all.** This is the one to
read twice, because the intuitive failure — an ugly error — is not what happens.
The caller gets a **complete, successful answer** while Apigee believes it
denied the request.
The token quota runs in `PostFlow/Response`, because the token count does not
exist until the model has answered. By then the response is already on the wire.
Verified live, paired by token count against client output:
| quota `continueOnError` | extension `failOpen` | Apigee | what the client got |
| --- | --- | --- | --- |
| `true` (as shipped) | `true` | CONTINUE, 200 | full answer |
| `false` | `true` | ABORT, 429 | full answer |
| `false` | `false` | ABORT, 429→500 | full answer |
**The 500 in the trace is a decoy.** It appears only after `RESP_SENT`, in
Mint/Analytics bookkeeping, carrying the 429's reason phrase
(`status=500, reason="Too Many Requests"`). It is never transmitted. It is also
the first thing an operator sees, which is how this was mis-documented for so
long.
**Switching the quota to blocking also destroys the metering.** A blocking quota
refuses to count the request that violated it, so `used.count` freezes at the
limit for the remainder of the window — observed stalling at 149/200. Count-only
gives accurate metering and no gating; blocking gives neither.
**Request-path faults do propagate, so enforcement belongs there — and the
policy has a first-class way to do it.** Use the documented `SharedName` split
rather than hand-rolling an observer:
```xml
<!-- request flow: checks the counter, never increments it.
LLMModelSource is REQUIRED here even though this half never counts --
omitting it is a live outage, see "LLMModelSource is REQUIRED" below. -->
<LLMTokenQuota name="LTQ-enforce-pro" type="rollingwindow">
<SharedName>llm-tokens-pro</SharedName>
<EnforceOnly>true</EnforceOnly>
<Allow count="40000"/>
<Interval>1</Interval><TimeUnit>hour</TimeUnit>
<Distributed>true</Distributed>
<LLMModelSource>{agw.req_model_bucket}</LLMModelSource>
</LLMTokenQuota>
<!-- response flow: increments it, never refuses -->
<LLMTokenQuota name="LTQ-count-pro" type="rollingwindow">
<SharedName>llm-tokens-pro</SharedName>
<CountOnly>true</CountOnly>
<Allow count="40000"/>
<Interval>1</Interval><TimeUnit>hour</TimeUnit>
<Distributed>true</Distributed>
<LLMTokenUsageSource>{agw.total_tokens}</LLMTokenUsageSource>
<LLMModelSource>{agw.model_name}</LLMModelSource>
</LLMTokenQuota>
```
Exactly one of `CountOnly` and `EnforceOnly` may be set on a policy. The
enforce half carries no `LLMTokenUsageSource` — it only reads the counter the
other half writes — but it **does** still require `LLMModelSource`, which is
not optional and not implied by the absence of counting. Apigee's own sample
for this pattern is a
`<RouteRule name="noroute"/>` proxy, which is our shape, so a processor with no
target is not a blocker.
An **earlier version of this file said enforcement "cannot work" here.** That
was wrong and the inference was bad: it generalised a real observation about one
`CountOnly=false` policy in the *response* flow into a claim about the policy
type. Do not repeat it to a user.
**Shipped as `assets/feature-token-enforce.yaml`** — three enforce policies,
one per `SharedName`, gated on the requested-model bucket, off by default.
**Verified live in the shape that matters**: a no-route proxy
invoked as `EXT_PROC_GRPC` by an Agent Gateway, on real Agent Runtime traffic,
where request and response arrive as separate gRPC messages. The over-budget
turn was refused with `429 Too Many Requests` and *"Rate limit LLM Token quota
violation"*, before the model was called. From that trace, flash budget 500:
```
ratelimit.enforce-LTQ-flash.used.count = 1086 <- written by CountOnly
ratelimit.enforce-LTQ-flash.allowed.count = 500
ratelimit.enforce-LTQ-flash.exceed.count = 586
error.state = PROXY_REQ_FLOW
```
The request-path policy read exactly what the response-path policy had
accumulated under the same `SharedName`, so **the linkage does join the two
halves in a no-route ext-proc proxy.** `<Identifier>` also scopes per caller
on the enforce half — `ratelimit.*.identifier` resolved to the calling agent's
principal, not a shared bucket.
An earlier report of "0 refusals at any budget" was a test harness pointed at
a different project, so that traffic never reached the proxy under test. Not a
platform defect — but worth keeping as a reminder to confirm traffic arrives
before concluding a policy does not fire.
**Two traps that both present identically as "it never refuses".**
*The nasty one: bucketing on a raw URI substring.* The enforce half buckets on
the requested model, and testing the whole URI for a model name is unsafe:
```
/v1beta1/projects/.../models/gemini-4-hydrogen:generateContent
^^^ contains "pro" inside *pro*jects
```
A `request.uri Like "*pro*"` condition therefore matches a **flash** request,
sends it to the pro bucket, finds headroom and allows — while the count half
correctly bills flash. Indistinguishable from a broken platform, and entirely
a config error. The shipped JS anchors the match after `models/` and buckets
on the extracted name for exactly this reason; do not simplify it into a
substring test on `request.uri`.
*The loud one:* omitting `LLMModelSource`, below.
**`LLMModelSource` is REQUIRED on the enforce half.** It is tempting to infer
that a policy which never counts needs no source elements at all; that
inference caused an outage. The restriction is on `LLMTokenUsageSource`
only — the enforce half must not *count*. It must still know *which bucket* to
check. Omit `LLMModelSource` and the policy substitutes a default of
`jsonPath('$.model', request.content, true)`, which does not resolve on a
Gemini-native `:generateContent` call because the model is in the URI, not the
body. It then raises `FailedToResolveModelName`, and at
`continueOnError="false"` that refuses **every** governed turn, not just
over-budget ones. Measured: 100% of traffic down for 8 minutes.
One limitation by construction: the enforce half buckets on the **requested**
model, because the resolved name only exists in the response. On an
OpenAI-compatible endpoint an alias may resolve to a different model, so a call
can be enforced against one bucket and counted against another. Everything is
still counted and still checked; it is only unsafe if someone assumes a
per-model limit is exact under aliasing.
Two further properties to accept — one a design constraint, one a `RaiseFault`
defect.
**Enforcement is one turn late.** The check reads the counter as it stood before
the current turn, because that turn's cost is unknown until the model answers.
Callers can overshoot by one turn. Unavoidable when enforcing in this position.
**`RaiseFault` discards `FaultResponse.Set` entirely — and this is NOT a general
property of request-path faults.** Easy to get backwards, and Model Armor is a
live counter-example in this same proxy:
| fault source | client status | client payload |
| --- | --- | --- |
| a policy's own error carrying an HTTP mapping — `SanitizeUserPrompt` raising `steps.sanitize.user.prompt.FilterMatched` | **400**, preserved | preserved in full, naming the matched filter |
| `RaiseFault`, whatever `StatusCode` is configured | **always 500** | always `Raising fault. Fault name : <policy>` |
Confirmed by single-variable test: a `RaiseFault`'s `StatusCode` changed `429` →
`400` with `ReasonPhrase` to match, verified in the deployed bundle, changed
nothing at the client. Status, reason phrase and body are all dropped, and no
configuration recovers them.
Two consequences. Do not promise an opaque 500 from a policy that raises its own
mapped error — Model Armor returns a clean 400 with detail. And because the
policy name is provably the only field a `RaiseFault` transmits, **naming one is
load-bearing, not cosmetic**: it is the entire diagnostic the caller gets.
**A tool policy "doesn't fire".** Check `proxyDeploymentType`. A proxy carrying
only generic policies deploys `STANDARD` and does not see the agent's calls to
off-Apigee tools or MCP servers. It must be `EXTENSIBLE`.
**Analytics went dark.** Not caused by the Service Extension. Setting
`apigee-service-extension-enabled=true` does **not** disable Apigee Analytics —
they coexist. On a Pay-as-you-go org, Apigee API Analytics is a paid
per-environment add-on that is simply off at environment creation; enable it
with `addonsConfig:setAddonEnablement {"analyticsEnabled":true}`. On a
Subscription org it is on already. Check `billingType` on the org before
concluding anything. Cloud Monitoring (`apigee.googleapis.com/proxyv2/*`) works
either way.
**A property you did not touch disappeared.** The environment PATCH replaces the
entire properties map. Read it first, re-send everything you want to keep.
**Deploy is rejected with `MISSING_SERVICE_ACCOUNT`.** Any policy calling a
Google API needs `?serviceAccount=` on deploy, plus the matching role —
`roles/modelarmor.user`, `roles/aiplatform.user`.
**Token metering bills for cache hits.** The two features are individually
correct and wrong together, and nothing surfaces it. Measured: the flash
counter moved 683 → 780 across a cache hit — exactly the 97 tokens of the
replayed answer — with Gemini never called.
Nothing in the metering steps is conditional on anything the cache sets.
`JS-extract-model` reads `request.uri`, which on a hit still ends
`:generateContent`, so `agw.model_name` is set as usual; the quota then reads
`usageMetadata` out of the replayed response and counts it. Populate is the
only step in the proxy that knows about `cache_hit`.
It inverts the point of the feature. The cache avoids model spend, but the
caller is metered as though every hit were an inference, so a high-hit-rate
workload exhausts its quota while costing almost nothing to serve.
Fixed in `feature-token-metering.yaml` by adding populate's cache-hit clause to
both quota steps, keeping the model-name gate. `AM-quota-headers` stays ungated
so a hit still returns headers, and `JS-extract-model` stays ungated because it
sets the model name those headers report. This is the one cross-feature
reference in the template, and it degrades safely: with the cache disabled the
variable never resolves and `!= true` is true.
**Placeholder substitution corrupts `DEPLOYED_INDEX_ID` silently.**
`DEPLOYED_INDEX_ID` *contains* `INDEX_ID`, so an ordered `sed` over the feature
file rewrites the parameter's own name:
```
sed 's|INDEX_ID|3873425533026959360|g'
- name: DEPLOYED_INDEX_ID -> - name: DEPLOYED_3873425533026959360
DeployedIndexID: "{DEPLOYED_INDEX_ID}" -> "{DEPLOYED_3873425533026959360}"
```
What makes it dangerous is that it survives: declaration and reference are
renamed consistently, so the bundle compiles and runs. It only surfaces later,
when the template supplies a `DEPLOYED_INDEX_ID` that no longer exists. Use
word boundaries (`\bINDEX_ID\b`) or replace longest-first, and assert that no
placeholder survives. `INDEX_ENDPOINT_ID` and `INDEX_ENDPOINT_DOMAIN` share a
prefix the same way. `deploy_proxy.sh` does both and refuses to import a
half-substituted bundle.
**The findNeighbors host cannot be derived, so it is not an input.** The index
endpoint's domain has a leading label assigned at creation time that matches
neither the index id, the endpoint id, nor the project number. It can only be
read back, which is why `apigee-agent-gateway-governance.example.yaml` has no
field for it and
`deploy_proxy.sh --index-endpoint-id` substitutes it at deploy time.
**Semantic cache re-populates on a hit.** On a no-route proxy the response flow
runs on a cache hit too, because there is no target flow for populate to live
in. Ungated, it re-embeds and re-upserts the answer it just served. Gate
populate on the lookup's cache-hit flag.
**The cache-hit condition never matches.** Runtime emits
`SemanticCacheLookup.<policy>.cache_hit`. The policy reference documents
`semanticcache.lookup.<policy>.cache_hit`, which does not resolve — and because
an unresolved variable makes `!= true` true, it fails *open*. Read real variable
names out of a trace before conditioning on them.
**`<DeployedIndexId>` fails bundle validation.** It is `<DeployedIndexID>`,
all-caps ID.
**The transaction you wanted isn't in the debug session.** First check how many
there are, because the answer differs completely.
**One per governed shape, and each is a model call** — that is correct, not
truncation. A suffix list of model-call paths routes only those, so one
transaction per turn per shape is the healthy result. With `:generateContent`
alone that is exactly one.
**Zero** — the callout is not landing at all. Work the entries above: gateway
`networkConfig`, then the three hostnames, then the envgroup count.
**Many, and yours got pushed out** — only happens with a broadly-matching
AuthzPolicy. Measured at `prefix: /`: 12 transactions for one single-question
turn against a `count` cap of 15. Arm the session with a `filter` rather than
firing more traffic, which only makes it worse.
**Something that worked an hour ago returns nothing.** In sandbox orgs an IAM
reaper may strip non-baseline bindings on the deployment SA roughly every 30
minutes. The symptom is not a clean 403 — it is an empty agent turn. Re-grant
immediately before a test run.
**`ServiceCallout` runs despite being unsupported.** It is on the Extension
Processor unsupported-policy list, yet imports, deploys `EXTENSIBLE` and
executes from both request and response flows. Docs and platform disagree; don't
build on it until that is resolved.
**An OpenAI-shape agent is governed by nothing and reports nothing, because its
`matchPaths` entry has a `/v1` in it — or because there is no entry for it at
all.** The AuthzPolicy binds on path **suffix**, and
Vertex's OpenAI-compatible endpoint ends `openapi/chat/completions` — so
`/v1/chat/completions` is not a suffix of it and never matches. Measured: a
debug session open across two successful agent turns captured **0
transactions**; adding `/chat/completions` captured 1. Same signature as the
envgroup 404 — everything deploys clean and governs nothing. `/v1/...` is
correct only for literal `api.openai.com`.
The "no entry at all" case is the one to watch once a second shape has been
added. `matchPaths` compiles
to `LLM_URI_MATCH`, a one-entry list is a legal way to say "govern one shape",
and nothing distinguishes a deliberate single entry from a forgotten second
one. If a shape is reporting zero transactions, check the list length before
anything else.
**With the cache on and two models behind one proxy, an agent returns an
EMPTY answer and no error.** Recognise this symptom, because it sends you into
the agent code and the cause is in the proxy. `SemanticCacheLookup` keys on
the embedding of the prompt **and nothing else** — no model, no wire shape, no
tenant — so whichever model answers a given prompt first answers it for every
model. Reproduced across three consecutive runs, a Gemini agent and an
OpenAI-shape agent against one proxy:
```
cache_hit : true
agw.requested_model : openai/gpt-oss-120b-maas <- on a GEMINI request
response : {"choices":[{"message":{"content":"Mars."}}], ...}
```
The Gemini client looks for `candidates[].content.parts[]`, finds `choices[]`,
matches nothing, and returns `{'parts': [], 'role': 'model'}`. No exception,
no fault, a 200 — an empty success.
Three consequences, worst first: **cross-shape corruption**, which degrades to
empty rather than erroring; **wrong-model answers**, since any model's answer
satisfies any model's question; and **metering misattribution**, because
`extract-model.js` reads the model out of `response.content`, which on a hit
is the *cached* response, so the request is billed to the wrong bucket.
The priority-15 normalisation is what makes this reachable — giving Model Armor
and the cache a shape-agnostic `agw.user_prompt` is exactly what lets a Gemini
prompt and an OpenAI prompt produce the same key. Both changes are still
right; this is the seam between them.
The policy exposes no key composition, so there is no clean fix. Pick a
trade-off:
| mitigation | cost |
| --- | --- |
| disable the cache when >1 model is behind the proxy | loses the feature; the right default |
| one index per model bucket, keyed on `agw.model_name` | multiplies the most expensive resource in the design |
| prefix `agw.user_prompt` with `agw.model_name` in `extract-prompt.js` | one line and it works, but perturbs the semantic space so near-miss prompts stop matching |
**Vector Search `restricts` cannot be used for this, and it is the first idea
everyone has.** The API does support namespace/allow-list filtering on
`upsertDatapoints` and `findNeighbors`, so writing the resolved bucket as a
restrict on populate and filtering on it at lookup would scope hits to one
model without touching the embedding or the index geometry. The obstacle is
not Vector Search, it is the policy surface: `SemanticCacheLookup` exposes
only `UserPromptSource`, `Embeddings.VertexAI.URL` and
`SimilaritySearch.VertexAI.{URL, DeployedIndexID, Threshold}`, and
`SemanticCachePopulate` only `SimilaritySearch.VertexAI.URL` and
`TTLInSeconds`. Both build their request bodies internally and neither takes a
restricts element, so there is nowhere to put one. This is not a
prototype-and-see — there is no seam.
A fix is open with the Apigee team: make the cache key a configurable composite
identifier, so it can carry something beyond the prompt embedding. Model and
wire shape are the same missing dimension as tenant, so the evidence above was
attached to that request rather than raised separately. That request is the
restricts idea asked at the layer that can grant it.
**A non-Gemini model consumes no quota at all, silently.** `agw.model_name`
buckets on the substrings `pro`/`argon` and `flash`/`hydrogen`, and only those
two buckets had a quota bound to them. Measured with `gpt-oss-120b-maas`: the
token count was
extracted correctly (`agw.total_tokens = 223`) and then discarded — **zero**
`ratelimit` references in the whole transaction. This is worse than a
resolution failure, which at least raises `FailedToResolveTokenUsageCount`
into the trace. The shipped fix is a catch-all `LTQ-count-other` on
`OTHER_TOKEN_LIMIT`. The real fix is generating one quota per entry in the
`models:` list, which today reads as authoritative and generates nothing.
**Widening `LLM_URI_MATCH` to a second wire shape makes Model Armor return 500
on every request of that shape.** The condition is shared by every feature
gated on it, so widening it arms them all at once — and Model Armor is
`continueOnError: false` by design. Its `UserPromptSource` JSONPath is written
for one body layout, does not resolve against the other, and the policy fails
**closed**. The result is not a skipped scan, it is a hard failure per
request, with the trace showing `modelarmor-SUP-sanitize` faulting and the
cache policies never reached.
The fix is structural, not a typo fix: anything derived from the request body
is normalised **once**, in `feature-normalize.yaml` at priority 15, which runs
after identity (10) and before Model Armor (20) and the cache (30). Putting
the normalisation inside the cache feature at priority 30 compiles, deploys,
and does nothing — it runs after its consumer. Check the compiled order, which
makes it obvious:
```
identity-VJ, identity-AM, normalize-JS-extract-prompt, modelarmor-SUP-sanitize, semanticcache-SCL-lookup
```
Note the failure direction was lucky. A fail-open policy would have degraded
quietly; Model Armor failing closed is what made this findable in one request.
**The semantic cache stores upstream errors and replays them as HTTP 200.**
`SemanticCachePopulate` is status-blind — gated only on `cache_hit`, it will
cache any response the flow produces. Observed: a transient 429 from a
throttled model was written to the cache, then served to every identical
prompt for the whole TTL, **with a 200 status**. A momentary blip became a
persistent wrong answer that defeats status checking, and metering saw
nothing (`token_source = none`, `used.count = 0` throughout). Client-side the
symptom was a crash — Vertex wraps error envelopes in a JSON array while
success bodies are bare objects.
Gate populate on `response.status.code = 200`. Verified across ten
transactions: populate executed on the one successful response and skipped
all nine 429s. Raised with the Apigee team — the policy should not cache
non-2xx by default, or should expose an eligibility control. Two caveats went
with it: this was seen on a
**no-route** proxy, where the response flow runs for every outcome, and the
200 on replay may come from the ext-proc short-circuit rather than the cache
policy — the composite behaviour is what was measured.
## Authoring (AFT)
Found while compiling this template. Reproduce with `scripts/compile_check.py`.
**gcloud 588.0.0 changed two AFT compiler behaviours, and both fail silently.**
Tracked upstream as a compiler regression. Neither breaks the shipped bundle —
all six features set `uid` and the template declares no `endpoints`/`targets` —
but both become load-bearing from 588.0.0 on, and the guard is invisible.
1. **Policy names are namespaced only for features that declare a `uid`.**
Before 588.0.0 the feature name was always prefixed. Now, with `uid:
semanticcache` set, `SCL-lookup` still compiles to
`semanticcache-SCL-lookup`. Remove the `uid` and the prefix disappears,
while every condition naming the policy in full keeps the old name —
including `SemanticCacheLookup.semanticcache-SCL-lookup.cache_hit`, which
gates all three quota steps. The bundle compiles, deploys, and the
cache-hit guard silently stops matching.
2. **Template-level `endpoints`/`targets` are dropped whenever the template
supplies features.** A feature's `defaultEndpoint` is only a fragment
merged into endpoints that already exist, so a template that declares its
endpoint *and* features ends up with zero endpoints and every flow
discarded. This template keeps its endpoint inside
`feature-identity.yaml` (priority 10) for that reason. Do not move it back.
The import fails with `The proxy must contain a ProxyEndpoint`, which names
the wrong cause.
Evidence note: read off the compiler's own behaviour change plus the feature
files, not a live 588.0.0 import. Worth one real import to confirm.
**A macro in the template's own body is never substituted.** The compiler runs
parameter replacement over *feature* content only; the template's `endpoints`
are copied verbatim. A `{BASE_PATH}` written in the template's `basePath`
reaches Apigee as the literal string `{BASE_PATH}`. Template-level parameters
exist to supply override *values* to features that declare a parameter of the
same name — they are not usable inside the template itself. Write literals
there.
**Two Flow entries named `PreFlow` emit two `<PreFlow>` elements.**
`models.Flow` carries a single `mode`, so a PreFlow with both a Request and a
Response phase cannot be expressed as one entry; the converter emits one element
per entry, producing invalid ProxyEndpoint XML. Put response-phase steps in
`PostFlow`/`Response`, which is what AFT's own fixtures do. Note this is a
deviation from a playbook that specifies PreFlow Response — verify on a live
org.
**Cross-policy variable references are not namespaced.** Every policy is renamed
`<feature>-<policy>`, and `<Step><Name>` references and `jsc://` resource URLs
are rewritten to match. Policy-derived *flow variables* are not:
`jwt.<policy>.decoded.claim.*`, `SemanticCacheLookup.<policy>.cache_hit`,
`parsepayload.<policy>.operation`, and the `stepName` attribute on
`UseQuotaConfigInAPIProduct` all keep whatever you wrote. Write them
pre-namespaced (`jwt.identity-VJ-iap-egress-jwt.decoded.claim.email`) and they
will break if the feature is renamed or given a `uid`.
**A feature file is not found.** Each `features:` entry is joined onto the
template file's own directory, never the working directory. Moving a feature
into `assets/features/` without changing its `features:` entry to
`features/<name>.yaml` breaks the import with a bare `FileNotFoundError`. The
subdirectory itself is fine — verified by compiling a template whose entries
carry the subpath — so it is the mismatch that breaks it, not the nesting.
**An empty `targets:` list still emits `<TargetEndpoints></TargetEndpoints>`.**
Harmless in the bundles compiled here, but confirm against bundle validation on
first deploy.
**Apigee message templates and AFT macros share `{}`.** `{agw.model_name}` is
left alone only because no declared parameter is named that. Never name an AFT
parameter after a runtime variable.
## Tooling and environment
**"Extensible proxy can not be deployed to a base environment" — on an
environment the scripts created minutes earlier, where every prior step
passed.** The environment type is `BASE`, and `BASE` cannot host an extensible
proxy. The remedy is a PATCH, not a rebuild:
```bash
curl -X PATCH -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
".../organizations/$ORG/environments/$ENV?updateMask=type" \
-d '{"type":"COMPREHENSIVE"}'
```
It is `BASE` on purpose. The create deliberately omits `type`, because sending
it is rejected outright on a `SUBSCRIPTION_2021` org with a message about
pricing plans — so the org default applies, and that default is `BASE`.
**What makes this one disorienting is where it lands.** The create, the
instance attach and the `apigee-service-extension-enabled` property PATCH all
succeed against a `BASE` environment. Nothing warns. The failure surfaces only
at proxy deploy, several steps and roughly four minutes of attachment later,
which points suspicion at the proxy or the template rather than at an
environment that was reported healthy. Patching to `COMPREHENSIVE` *before* the
instance attach turns a four-minute round trip into a few seconds, and is
idempotent — patching an already-`COMPREHENSIVE` environment is a no-op, and
the service-extension property survives it.
Reading the type back has its own trap: a healthy environment commonly returns
**no `type` key at all**. Absent is not `BASE`. Only an explicit `BASE` blocks
the deploy — see `scripts/ensure_apigee_environment.sh` and the matching check
in `scripts/assess_integration.sh`.
**`apigee-service-extension-enabled=true` does not disable Apigee Analytics.**
The two coexist; a claim to the contrary circulated in an earlier playbook and
is wrong. Apigee API Analytics is a per-environment add-on orthogonal to the
property: on by default on a **Subscription** org, and on **Pay-as-you-go** a
paid add-on that is off at environment creation and must be enabled explicitly.
So analytics missing on a service-extension environment is almost always the
add-on, not the property. Enable it with:
```bash
curl -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
".../organizations/$ORG/environments/$ENV/addonsConfig:setAddonEnablement" \
-d '{"analyticsEnabled":true}'
```
It bills from the moment enablement begins, so check `billingType` on the org
before telling a customer either way.
Hit while running this against a live org.
**`--from-template` used to be beta-only. It is on GA as of gcloud 588.0.0.**
Verified by a real import: plain `gcloud apigee apis import --from-template`
succeeds. On an older SDK the GA command rejects the flag, which is easy to
misdiagnose as "the command does not exist in this SDK version" -- the fix
there is `gcloud beta apigee apis import`, or upgrading.
**"Permission denied on resource ... (or it may not exist)" can be a credential
path, not access.** With context-aware access enabled, gcloud's default account
credential was rejected on an org the same user could reach fine over REST with
an ADC token. The error names the resource, which points you at IAM rather than
at the credential. Workaround:
```bash
CLOUDSDK_AUTH_ACCESS_TOKEN=$(gcloud auth application-default print-access-token) \
gcloud apigee apis import ...
```
**`compile_check.py` dies on `ModuleNotFoundError: No module named 'yaml'`.**
The interpreter you ran it with does not carry PyYAML. The script now says so
by name rather than raising a bare traceback. `pip install pyyaml`, or re-run
with a Python 3 that already has it. Note the gcloud SDK's bundled interpreter
does not, and the SDK's vendored `yaml` is Python 2 -- neither is the answer.
The script needs PyYAML and the in-repo gcloud AFT modules, nothing else.
**An environment is locked while an instance attachment runs.** Setting the
`apigee-service-extension-enabled` property returns `400 FAILED_PRECONDITION ...
resource is locked by another operation` until the attachment LRO finishes.
Attach first, then set properties.
**The environment property PATCH is asynchronous.** It returns a long-running
operation, not the updated Environment, and a readback immediately afterwards
shows empty properties. Poll the operation before concluding the property did
not stick.
## Agent Gateway
**Two `CONTENT_AUTHZ` policies on one gateway: the execution order is
undefined. Do not invent one.**
This is the single most tempting place in the whole integration to fabricate an
answer, because every instinct says a deterministic system must have a
documented tie-break. There is none. Specifically, none of these is the rule,
and stating any of them to a customer is worse than saying "unknown":
- **not** alphabetical by resource name
- **not** creation order, or last-writer-wins
- **not** any `priority` field — `AuthzPolicy` has none for this
- **not** the order they appear in a `list` response
The honest answer is that precedence between two `CONTENT_AUTHZ` policies on
the same gateway is not defined or documented, so the safe assumption is that
either may run first and neither may depend on the other's effect. If ordering
actually matters for a design, that design needs changing.
Coexistence itself is normal and expected: a gateway acquires a policy
automatically when agents are registered, and other governance products add
their own. A
`REQUEST_AUTHZ` policy alongside a `CONTENT_AUTHZ` one is a different phase
entirely and chains cleanly — that case is not ambiguous and should not be
described as if it were.
**They also cannot be merged.** An `AuthzPolicy` carries a single custom
provider, so each product needs its own and the pair has to coexist. A gateway
allows 4 CUSTOM policies, so there is room. Expect "then can we combine them"
as the immediate follow-up to the precedence answer, and answer it unprompted.
**Every invocation of a gateway-attached agent returns 401, and the agent's own
code never runs.** The container fails on its own outbound `sessions.create`
with `401 UNAUTHENTICATED`, which reaches the client wrapped as a `400
INVALID_ARGUMENT Reasoning Engine Execution failed`.
Fix, in the agent's deploy config:
```python
"env_vars": {
"GOOGLE_API_PREVENT_AGENT_TOKEN_SHARING_FOR_GCP_SERVICES": "False",
},
```
Two conditions are both required: the agent is attached to an Agent Gateway,
**and** it was built after 2026-09-30. Neither alone reproduces -- the same
agent without the gateway serves fine, and an engine built before that date
with byte-identical config still serves.
Three things make it expensive to diagnose. It is **invisible at deploy time**:
the deploy succeeds and the engine reports healthy. The failing spec and a
working one differ in nothing readable -- the operative setting is *absent*
from both and resolves to a runtime default that `GetReasoningEngine` does not
report, so a field-by-field diff shows only name and timestamps. And the
traceback points at ADK session code, which reads like an agent bug rather
than a platform one.
Tracked upstream with the full isolation table; it is an instance of the
cert-bound-token family where an Agent Identity token reaches a non-mTLS
endpoint. The gateway is what enforces the cert binding, which is why removing
it appears to "fix" the agent.
The gateway itself is out of scope for this skill, but these cost hours if you
are standing one up to test against. Background:
[Agent Gateway overview](https://docs.cloud.google.com/gemini-enterprise-agent-platform/govern/gateways/agent-gateway-overview.md.txt)
and
[Set up an Agent Gateway](https://docs.cloud.google.com/gemini-enterprise-agent-platform/govern/gateways/set-up-agent-gateway.md.txt).
**Everything is built, and no traffic arrives.** Check where the agent runs
before anything else. A GCE VM can never reach the gateway — the supported
compute is GKE or Cloud Run, and Cloud Run must be in ambient networking mode.
Use Agent Runtime with `agent_gateway_config`. See
`references/networking-psc.md`.
**A consumer PSC endpoint to the gateway stays `PENDING`.** Expected, and not
fixable with gcloud: acceptance needs an internal `References.CreateReference`
call. It presents as TCP 443 closed, which looks like a firewall rule you are
missing.
**Agent Runtime creation fails with "Permission denied to get Agent Gateway".**
The Vertex AI service agent
(`service-<project-number>@gcp-sa-aiplatform.iam.gserviceaccount.com`) resolves
the gateway on your behalf and needs `networkservices.agentGateways.get` on the
gateway project. Grant `roles/networkservices.viewer` — it is the narrowest
predefined role that carries the permission, and neither
`roles/networkservices.agentGatewayUser` nor `…agentGatewayViewer` does, despite
the names. The error suggests waiting for API-enablement propagation, which will
send you off waiting for something that never arrives if the binding is simply
absent.
**There is no `gcloud` surface for Agent Runtime.** No `agent-engines` or
`reasoning-engines` group on GA, beta or alpha. Attaching an agent to a gateway
is SDK-only, which is easy to misread as the feature being unavailable.
**`AgentGateway` has no `create` verb.** Only import, export, describe, list and
delete. It is declarative YAML or nothing.
**`dnsPeeringConfig.targetNetwork` rejects a bare network name.** It wants
`projects/{project}/global/networks/{network}`, despite the field name.
**The two `dnsPeeringConfig` fields are different schemas.**
`AgentGatewayNetworkConfig` takes `{targetProject, targetNetwork, domains[]}`;
`EgressNetworkConfig` takes `{targetNetwork, domain}`, singular. Copying one
into the other fails validation.
**`agentConnectivityTemplate` wants the project *number*.** Not the ID. It is
also **mutually exclusive with `networkConfig`** — set both and the import is
rejected. Attaching one to an existing gateway returned `code 13, an internal
error has occurred` after ten minutes; treat the template path as unproven.
**Budget ten minutes per import.** `AgentGateway` and `AuthzPolicy` imports both
take roughly that. They have not stopped responding.
**A fresh VPC may have no firewall rules at all**, so SSH to a test instance
times out before you get far enough to debug anything else.
modes.md 44.5 KB
# Modes, capabilities and assessment
## Contents
- [When the user asks what you can do](#when-the-user-asks-what-you-can-do): lines 18-113
- [Output formatting](#output-formatting): lines 114-144
- [Assessing an existing setup](#assessing-an-existing-setup): lines 145-276
- [Choosing the mode](#choosing-the-mode): lines 277-296
- [What you ask for](#what-you-ask-for): lines 297-308
- [Defaults](#defaults): lines 309-371
- [Start with two features, not four](#start-with-two-features-not-four): lines 372-434
- [Discover before you plan](#discover-before-you-plan): lines 435-465
- [The plan](#the-plan): lines 466-608
- [What dev mode produces](#what-dev-mode-produces): lines 609-762
- [Hard refusal](#hard-refusal): lines 763-780
- [Reconcile, don't re-create](#reconcile-dont-re-create): lines 781-856
## When the user asks what you can do
Asked an open question — "what do you know how to do with Apigee and Agent
Gateway", "what can this skill do" — answer with the five areas below, not with
a list of files. Keep it to what is actually built; naming something that does
not exist is how a demo gets stopped.
> **1. Set it up** — wire Apigee in as an authz service extension on an Agent
> Gateway, from a conversation or from a version-controlled YAML file. Creates
> the Apigee environment, envgroup, proxy and deployment, plus the PSC endpoint,
> private DNS and the gateway binding.
>
> **2. Govern LLM traffic** — four capabilities, each a few lines of config:
> caller identity from the gateway's signed assertion, per-model token metering,
> Model Armor on prompts, and a semantic cache that answers repeats without
> calling the model.
>
> **3. Assess what is running** — a read-only health check across the whole
> setup, gateway to proxy, reporting PASS/FAIL/WARN per resource. Safe to run
> against production.
>
> **4. Explain what it found** — read a debug session against live agent traffic
> and say which agent called, which model, how many tokens, and whether anything
> was blocked.
>
> **5. Tell you what is wrong** — 63 documented failure modes, indexed by
> symptom rather than cause, because the symptom is what you have.
Then say what must already exist, as a short table and nothing more:
> | Prerequisite | What it means |
> | --- | --- |
> | **Agent Gateway** | already created; this skill never creates one |
> | **Agent on Agent Runtime** | the agent's traffic must actually route through that gateway. On Agent Runtime that is set with `agent_gateway_config` when the agent is created, and cannot be added afterwards |
> | **Apigee** | an org with a runtime instance **in the same region as the gateway**. It does not have to be the same project — the callout reaches it over PSC — but the region must match |
Then ask which of the five they want. Do not start provisioning off an open
question.
**In this opening overview only, defer these four caveats.** The scope of this
rule is the capability list above and nothing else. It is a narrow deferral of
four named items from one specific answer — it is **not** a general instruction
to be sparing with caveats, and it does not apply to any other reply. Each of
the four is true, matters, and belongs at the moment it bites:
| Caveat | Defer it to |
| --- | --- |
| enforcement is one request late, and buckets on the requested model | they ask for a hard cap, or enable `tokenMetering.mode: ENFORCE` |
| the semantic cache is unreliable across more than one wire shape | they enable the cache **and** `matchPaths` has more than one entry |
| Model Armor fails closed | they enable Model Armor |
| attaching gateway egress is irreversible | the plan reaches that step |
Volunteering these four up front trades a clear answer for a hedged one, and
the user cannot act on a caveat about a feature they have not chosen yet.
**Everywhere else, the caveat is the answer.** Once the user asks about a
specific step, resource or failure, the condition that makes it go wrong is the
substance of the reply, not an optional embellishment. Omitting it is a wrong
answer, not a concise one. Always state the gating condition when it applies:
| Answering about | Always state |
| --- | --- |
| building or deploying the proxy | the deployment must report `EXTENSIBLE`; `STANDARD` will not govern |
| the PSC endpoint or callout path | confirm `pscConnectionStatus=ACCEPTED`; the AuthzExtension is inert until the host resolves and the proxy is deployed |
| creating or attaching the environment | instance attachment **locks the environment** and takes ~4 minutes |
| Model Armor mode | `DRY_RUN` evaluates and logs but does **not** block — it is not the same as disabling Model Armor |
| a symptom with more than one precondition | every condition required, not just the first — a 401 on session create needs the gateway attached **and** a recent build |
This list is not exhaustive. The test is whether the user could act on the
answer and still be surprised; if so, the caveat was load-bearing and belonged
in the reply.
When a hard cap *is* asked for: this meters by default and **can** enforce.
`tokenMetering.mode: ENFORCE` adds a request-flow quota that refuses an
over-budget caller with a 429 before the model is called — one request late by
construction, because the turn that crosses the limit has to finish before its
cost is known. Model Armor is the other policy that refuses.
**Do not raise agent-to-tool governance or model routing unprompted.** Not in
the capability list, not as a caveat, and never as something planned. This
skill governs the agent's **LLM** traffic; those are different jobs, not
pending ones. Describing them at all — even to say they are absent — invites a
commitment nobody has made.
If the user asks directly — a per-tool quota, governing calls to an MCP
server, choosing which model a request reaches — answer once, plainly, in
terms of what this skill *does*: caller identity, per-model token metering,
Model Armor on prompts, and the semantic cache. Then move on. Do not
speculate about whether it might arrive later; you do not know, and guessing
reads as a roadmap.
Fronting an MCP server is a different **shape** regardless, which is the
durable reason rather than a scheduling one: that is a proxy with a
**target**, receiving a request and routing it onward, where this one only
inspects and returns a verdict.
## Output formatting
Every surface a human reads uses the same palette, so the skill looks like one
tool rather than five scripts and a narrator.
| Colour | Means | Where |
| --- | --- | --- |
| green | exists, untouched, healthy | `PASS`, `REUSE`/`REUSED`, `EXTENSIBLE` |
| cyan | something new | `CREATE`/`CREATED`, `RESERVE`, `TODO`, `DRY-RUN` |
| yellow | a resource the user owns is modified, or money | `WARN`, `APPEND`/`APPENDED`, `MODIFY`, `COST`, `IRREVERSIBLE` |
| red | actually wrong | `FAIL`, a non-`EXTENSIBLE` deployment |
| dim | structure and asides | rules, headers, "not checked" |
All five scripts carry the same preamble and degrade to plain text off a tty,
under `NO_COLOR`, or with `TERM=dumb`. **The tty test is on fd 2**, because the
scripts log to stderr — testing stdout would colour a piped run and leave an
interactive one plain, which is exactly backwards.
Tables are box-drawn with a header rule. Reuse the same table shape when the
same information recurs: the plan table and the completion table differ only in
their last column, and that is deliberate — the reader learned the shape once.
When you render a plan, a status summary or a completion report yourself rather
than running a script, follow the same scheme. A report that looks different
from the one the script printed two minutes earlier reads as a different tool.
**Never emit raw HTML in chat output** — no `<sub>`, `<br>`, `<span>` or
similar. Terminals show the tag literally and it reads as a rendering bug.
Use plain text or markdown; if something needs a subscript or a line break
inside a table cell, restructure it instead.
## Assessing an existing setup
`scripts/assess_integration.sh` is the read-only verb. Use it when the user asks how
things are running, when something is broken, and before planning any change.
**Say that it changes nothing — before running it, and again when reporting.**
It inspects and never writes: nothing is created, modified or deleted, so it is
safe to run against production. State that explicitly rather than leaving it to
be inferred from the word "assessment". Someone who has just been told their
setup may be misconfigured will not assume that a diagnostic is non-destructive,
and on a production gateway that doubt is enough to stall the whole
conversation.
Output is two tables. **Lead with the first one when reporting to the user.**
A **Setup Status Summary** rolls the whole run into six category rows, where
the Status column carries a *value* rather than only a verdict and the Details
column states the *consequence*:
```
┌─ Setup Status Summary ────────────────────────────────────────────────────────────────────────
CATEGORY STATUS DETAILS
Overall Health OK, WITH NOTES 19 PASS, 0 FAIL, 1 WARN, 0 TODO -- built and healthy
Proxy EXTENSIBLE rev 4 agent-gateway-governance on agent-gateway-govern
Enforcement METER + ARMOR:ENFORCE Model Armor DOES refuse a matching request (400); quotas count only
Caching ON (e2-standard-2 x1) deployed index 5589640038682984448 -- BILLING per node-hour
Governed Shapes 1 :generateContent
Callout Path Verified PSC 10.138.0.9 ACCEPTED, zone resolves the hostname
AuthZ Wiring Verified <gateway>-apigee-governance-policy
────────────────────────────────────────────────────────────────────────────────────────────────
```
That block is copied from a real run, not composed. Keep it that way when the
output changes: a documented example that has drifted from the tool is worse
than none, because a reader diffs their output against it and concludes
something is wrong.
**Read the Proxy row first whenever the complaint is that governance does not
seem to be doing anything.** Its deployment type settles that question on its
own: `EXTENSIBLE` means the gateway is able to call the proxy, `STANDARD` means
it never will. A `STANDARD` deployment is not invoked at all — no error, no
transaction, nothing in a debug session — so every other check in the run can
pass while not one request is governed. Confirm `EXTENSIBLE` before
investigating anything downstream of it; `STANDARD` makes the rest moot.
**The Enforcement row is the one to read out loud.** It answers the question a
reader cannot otherwise get without opening a feature file: does anything here
block a request? `METER ONLY` means no. `METER + ARMOR` means Model Armor is
deployed at `modelArmor.mode: ENFORCE`, where the policy is
`continueOnError: false` and fails **closed**. `METER + ARMOR:DRY_RUN` means it
is deployed in observe-only mode — it evaluates and logs, and blocks nothing.
Read the mode, not just the presence of the policy.
**Report that row as it stands. Do not revise it by reading the bundle.** The
script derives Enforcement from the deployed revision, not from config, and it
is the answer. Finding `LLMTokenQuota` policies in the bundle and concluding
the proxy enforces is wrong: **the shipped quotas are `CountOnly`, and a
`CountOnly` quota counts without ever refusing.** The enforcing half is a
separate request-flow `EnforceOnly` policy that only exists if
`feature-token-enforce.yaml` was added — which is exactly what the script
already tested. So:
| Row says | Answer | Never say |
| --- | --- | --- |
| `METER ONLY` | nothing blocks — the quotas are `CountOnly`, so they count without ever refusing | that quotas or Model Armor can refuse here |
| `METER + QUOTA LIMIT` | the token budget is enforced, one request late | that it refuses the turn that crosses the limit |
| `METER + ARMOR:ENFORCE` | Model Armor refuses a matching request (400) | that the quotas also refuse, unless the row says so |
| `METER + ARMOR:DRY_RUN` | nothing blocks — Model Armor evaluates and logs | that Model Armor is protecting traffic |
Give the **reason**, not just the value — even in a one-line answer. "Nothing
blocks: the quotas are CountOnly" is one line and tells the reader why; "no"
makes them run the assessment again themselves.
If you believe the row is wrong, say so **and** say the row disagrees. Quietly
upgrading `METER ONLY` to `METER + QUOTA LIMIT` reports a protection the user
does not have, which is the worst failure this assessment can produce. Never
report a mode or status for a resource the assessment did not find.
**Four statuses, and TODO vs FAIL is the one that matters.** `TODO` means this
skill creates the resource and has not yet — the expected state of a greenfield
project, not a defect. `FAIL` means something no build step will resolve: a
missing user prerequisite, or a conflict. `SKIP` means the check did not run,
either because a flag was not passed or because its precondition is still a
`TODO`. Never report a never-built setup as a wall of failures; say `NOT BUILT`
or `PARTIALLY BUILT` and read the TODOs as the build plan they are. The exit
status follows the same rule — only a real `FAIL` is non-zero.
A bare `--project --region --gateway` invocation **assumes the documented
default names** for the environment, envgroup, proxy and hostname, and prints
which ones it assumed. If the setup under test uses different names, pass the
matching flags or every Apigee row will read as not-yet-built.
Then a **Checks** table, one row per resource with PASS, FAIL, WARN, TODO or
SKIP, and a
count. Read the FAILs top-down and fix in that order: a gateway with no route
into the VPC makes every check below it meaningless, so fixing a lower one
first wastes the cycle.
`--json` carries both: `summary`, `rollup`, and `checks`.
Two things the rollup deliberately does not do. It does not replace the Checks
table — a category row cannot tell you *which* of nineteen checks failed. And
it never infers: Enforcement and the feature flags are read off the deployed
revision's policy list, not off the config the user handed in, so it reports
what is actually running.
WARN is not a defect. The two that matter:
- **Another CONTENT_AUTHZ policy on the same gateway.** Coexistence is
expected — a gateway acquires one automatically when agents are registered,
and other governance products add their own. A `REQUEST_AUTHZ` policy
alongside ours is a
different phase and chains cleanly. Two `CONTENT_AUTHZ` policies is the one
ambiguous case: **precedence between them is undefined, and there is no
tie-break rule to fall back on — not alphabetical, not creation order, not a
priority field.** Say it is undefined; never guess an order. They cannot be
merged either, since an AuthzPolicy takes a single custom provider. Full
answer, including the wrong rules people reach for:
`references/gotchas.md`, Agent Gateway.
- **DNS peering that does not cover your hostname.** Peering is per-domain, so
this is an append, not a conflict.
Exit status is 0 when there are no FAILs, 1 otherwise, so it is usable as a gate
in a script.
# Two modes: dev and prod
The same skill, the same schema, two entry points. **Dev mode writes
`apigee-agent-gateway-governance.yaml`; prod mode reads it.** What dev mode emits must be consumable by
prod mode unchanged — one schema, or the determinism prod mode promises is not
real.
## Choosing the mode
Do not ask the user which mode they want. Decide it:
| Situation | Mode |
| --- | --- |
| An input file exists and the user points at it | **prod** |
| The user asks for a specific file to be applied | **prod** |
| No input file, and the user describes an outcome | **dev** |
| User says "deterministic", "production", "check this in" | **prod** |
State which mode you picked and why, in one line, before doing anything.
---
# Dev mode
For an FDE or a customer meeting this for the first time. They do not know the
schema exists, and **they should not see YAML during setup.**
## What you ask for
Only what cannot be defaulted or discovered:
- `project`, `region` — region must match the Apigee runtime instance
- `gateway.name` — must already exist; list them rather than asking them to type one
- `network.vpc`, `network.subnet` — must be the VPC the gateway egresses into
Everything else gets a default (below). Discover what you can with `gcloud`
before asking: if the project has exactly one Agent Gateway in the region, name
it and confirm rather than asking.
## Defaults
Apply these silently. Show them in the plan; do not interrogate the user
field by field.
| Field | Default | Note |
| --- | --- | --- |
| `apigee.org` | = `project` | |
| `apigee.environment` | `agent-gateway-govern` | created if absent, dedicated to this proxy |
| `apigee.envgroup` | `agent-gateway-govern-group` | |
| `apigee.hostname` | `agent-gateway-callout.internal.<project>.local` | private to the VPC; nothing resolves it publicly |
| `apigee.proxy` | `agent-gateway-governance` | |
| `network.networkAttachment` | `agent-gateway-egress-attachment` | created if absent |
| `network.dns.zone` | `agent-gateway-callout-zone` | |
| `network.dns.domain` | `internal.<project>.local.` | parent of the hostname, trailing dot |
| `gateway.manageNetworkConfig` | `true` | prints a diff and waits for confirmation |
| `gateway.matchPaths` | `[":generateContent", "/chat/completions"]` | **two shapes**, matching the template's `LLM_URI_MATCH` default and `assets/apigee-agent-gateway-governance.example.yaml`. Drop the second entry for a Gemini-only agent — but then also drop the matching clause from `LLM_URI_MATCH` in every feature that declares it, or the two disagree. If the semantic cache is on, two shapes triggers the known-issue warning |
| `gateway.timeout` | `5s` | |
| `identity.enabled` | `true` | |
| `identity.defaultClientId` | `anonymous` | |
| `tokenMetering.enabled` | `true` | |
| `tokenMetering.interval` / `timeUnit` | `1` / `hour` | |
| `tokenMetering.models` | pro 10000, flash 40000, other 40000 | per-model buckets |
| `tokenMetering.mode` | `COUNT_ONLY` | `ENFORCE` refuses an over-budget caller on its **next** request (429); adds `feature-token-enforce.yaml` |
| `modelArmor.enabled` | `false` | opt-in, see below |
| `modelArmor.template` | **none** | required when enabled; refuse rather than invent one |
| `modelArmor.mode` | `ENFORCE` | `DRY_RUN` evaluates and logs but does not block |
| `semanticCache.enabled` | `false` | opt-in, see below |
| `semanticCache.deployedIndexId` | `agent_gateway_llm_cache` | underscores only — hyphens are rejected |
| `semanticCache` index display name | `agent-gateway-llm-cache-index` | `--index` for `ensure_vector_search.sh` |
| `semanticCache` endpoint display name | `agent-gateway-llm-cache-endpoint` | `--endpoint` for the same script |
**Two fields in the contract change the proxy's feature list rather than a
parameter**, and they are the only ones that do. Resolve them before building:
| Field | Value | Effect on the template's `features:` |
| --- | --- | --- |
| `tokenMetering.mode` | `COUNT_ONLY` | nothing added — metering only |
| | `ENFORCE` | add `feature-token-enforce.yaml` |
| `modelArmor.enabled` | `false` | nothing added |
| | `true` | add `feature-model-armor.yaml`; `mode` then sets `MA_CONTINUE_ON_ERROR` |
| `semanticCache.enabled` | `true` | add `feature-semantic-cache.yaml` |
`modelArmor.mode` is a **parameter** on an already-present feature, so toggling
it edits `MA_CONTINUE_ON_ERROR`. `tokenMetering.mode` is a **feature
membership** switch, because enforcement is a separate set of policies on a
different flow. Same shape in the contract, different mechanism underneath —
worth knowing when a mode change does not appear to take: for Model Armor
check the parameter in `feature-model-armor.yaml`, for metering check the
feature list.
Both `*_TOKEN_LIMIT` sets must agree between `feature-token-metering.yaml` and
`feature-token-enforce.yaml`, or enforcement refuses at a different threshold
than counting reports against. `compile_check.py` fails on the mismatch.
**Names are chosen so someone who finds these resources cold can tell what they
are for.** Inside Apigee the prefix is `agent-gateway-`, because what is unusual
about the proxy is that it serves an Agent Gateway. On the gateway side the
pattern is `<gateway>-apigee-llm-*`, because there what is unusual is that the
gateway calls Apigee. Do not name anything after `ext-proc`: that is the
mechanism, not the purpose, and it tells a reader nothing about what the
resource governs.
## Start with two features, not four
Identity and token metering only. They need no extra Google API, no service
account, and no provisioned resource, so the first run reaches a working,
verifiable state fast.
**Offer Model Armor and semantic cache only after the base setup verifies** —
after a real agent turn has shown up in a debug session. Enabling them before
the base works means a failure has two possible causes.
When the user asks for either, state what it costs before doing it:
**Model Armor** — needs a Model Armor template (ask for the name; there is no
sensible default) and `roles/modelarmor.user` on the deployment service
account. No standing cost. Adds one inline call per request.
**Model Armor has an observe-only mode.** `modelArmor.mode: DRY_RUN` keeps the
scan running and the verdict in the trace while swallowing the fault, so a
turn is never refused.
It is one of two capabilities with an observe-versus-refuse switch, and they
default in opposite directions on purpose:
| | observe | refuse | default |
| --- | --- | --- | --- |
| `modelArmor.mode` | `DRY_RUN` | `ENFORCE` | **`ENFORCE`** |
| `tokenMetering.mode` | `COUNT_ONLY` | `ENFORCE` | **`COUNT_ONLY`** |
A safety control that silently does not protect is worse than one that
visibly blocks, so Model Armor ships enforcing. A cost control that
unexpectedly refuses production traffic is worse than one that reports, so
metering ships counting. Do not describe either as "the only one with a
mode".
`ENFORCE` is the default and the shipped position: a security control that
silently does not protect is worse than one that visibly blocks. Offer DRY_RUN
when someone enables Model Armor on a proxy already carrying live traffic, so
they can see what a template *would* have blocked first. It is not an on/off
switch — disabling the feature removes the evaluation entirely. Toggling is a
redeploy, roughly two minutes.
**Semantic cache** — needs Vertex AI Vector Search. Say all three of these:
- The index endpoint deploy alone takes **about 34 minutes**.
- A deployed index **bills per node-hour for as long as it is deployed, with
or without traffic.** It is the only thing in this skill that bills
continuously.
- Turning it off later means undeploying the index, not just editing the YAML.
Undeploying underneath a live proxy faults every request, so the teardown has
an order.
Get explicit confirmation on the cost point. Do not infer it from "yes, enable
caching".
**This is the one approval you may not grant on the user's behalf.** Ask, then
stop and wait for an answer. "Enable semantic caching" is a request for the
feature, not consent to a continuously-billing resource, and the standing
*one approval, then execute to the end* rule does not cover it — that rule is
about not interrupting an **already-approved** plan, and the cost point is what
is being approved. If no answer comes, the correct outcome is to stop with the
cost stated and nothing provisioned. Never record this as assumed, implied or
automatic confirmation: a 34-minute deploy that bills per node-hour is not
recoverable by saying sorry afterwards.
## Discover before you plan
**Run `scripts/assess_integration.sh` first, in both modes.** It is read-only and
changes nothing, so it is safe before the user has agreed to anything. It is
also the only honest way to say what already exists — guessing produces a plan
that creates a second copy of something the project already has.
```bash
scripts/assess_integration.sh --project P --region R --gateway G \
[--env E --envgroup EG --hostname H --proxy PX --vpc V --subnet S] [--json]
```
`--json` is the form the plan reads. Every check maps to a plan row.
This matters most when another extension is already on the gateway. Another
governance product may bring its own network attachment, DNS zone, PSC
endpoint and authz policy. Some of that is shareable and some is not, and the
split is not obvious:
| Resource | With an existing extension present |
| --- | --- |
| VPC, subnet | **REUSE** |
| Gateway egress `networkAttachment` | **REUSE** — a route into the VPC, not to a service |
| Gateway `dnsPeeringConfig` | **APPEND** a domain — peering is per-domain |
| Private DNS zone | REUSE only if its domain is a parent of your hostname |
| PSC IP + forwarding rule | **CREATE** — must target the *Apigee* service attachment |
| AuthzExtension | **CREATE** — points at your hostname |
| AuthzPolicy | **CREATE** — one custom provider per policy, cannot merge |
Say which of these you found, not which you assumed.
## The plan
Before executing anything, print the plan and get approval. One line per step,
each with its duration. Do not start until they say go.
### Confirm everything up front
**This does not mean "discover until you are certain". It means the plan
carries every question, and you still stop at the plan.**
The sequence is fixed and short: run assess **once**, write the plan, print it,
**stop**. Do not re-run assess to resolve a detail, do not probe resources one
by one to firm up an estimate, and do not begin any step to find out whether it
would work. An unknown that assess did not answer belongs in the plan as an
unknown, with what you will do when you hit it. A plan printed from one
assessment and one pass of reasoning is the deliverable; a half-built
environment produced while "gathering decisions" is not.
**One approval, then execute to the end.** Do not stop halfway to ask for
something that was knowable at planning time — a build that pauses at minute 12
is worse than one that asked at minute zero, because the user has stopped
watching and the half-built state is the awkward one to abandon.
Three things need a human answer, and assess already tells you which of them
apply before you print the plan. "A human answer" means one the user actually
gave: none of the three may be self-granted, inferred from the original
request, or recorded as assumed or automatic confirmation. Ask them **at
planning time**, which is what makes the single-approval rule above work —
they are the content of that approval, not an interruption to it.
| Decision | Ask when | Why it cannot wait |
| --- | --- | --- |
| Attach gateway egress | `networkConfig` absent | One-way, and pins **all** the gateway's egress into that VPC — agents already running can lose access to Google APIs |
| Vector Search cost | `semanticCache.enabled` | Bills per node-hour from deploy, ~34 min to stand up, and undeploying underneath a live proxy faults every request |
| Enforcement, not just metering | user wants a budget | Changes what the proxy does to traffic; offer it, do not assume it |
Put each one in the plan with its consequence spelled out, take a single
approval covering all of them, and then run uninterrupted. If the user declines
one, say what the run produces without it rather than stopping — declining
Vector Search is a smaller setup, not a failed one.
The only legitimate mid-run stop is something assess could not have known: a
quota refusal, a permission the project turns out not to have, an API that
errors. Those are reports, not requests for permission.
**Every resource row carries an action, and the action comes from assess**, not
from a default. `REUSE` rows are the ones the user cares about — they are what
makes adding Apigee to an existing setup cheap.
Render it as a real table, grouped by leg, with the action column aligned and
colour-coded the same way `assess_integration.sh` colours its statuses — green
`REUSE` (nothing happens to it), cyan `CREATE` / `RESERVE` (new, and billable
where marked), yellow `APPEND` / `PATCH` (an existing resource the user owns is
modified). A flat 14-row monospace list is the thing being reviewed for consent,
so it has to be skimmable: the reader's question is "what are you touching that
already exists", and grouping plus colour answers it at a glance where an
unbroken column of names does not.
```
┌─ Plan · resources ────────────────────────────────────────────────────────────────────────────
GATEWAY LEG ACTION
─────────────────────────────────────────────────────────────────── ───────
VPC network default REUSE
Agent subnet default (10.142.0.0/20) REUSE
Gateway network attachment agent-gateway-egress-attachment REUSE
Gateway DNS peering internal.acme.local. APPEND ←modifies
APIGEE LEG ACTION
─────────────────────────────────────────────────────────────────── ───────
Apigee environment agent-gateway-govern CREATE
Environment group agent-gateway-govern-group CREATE
API proxy agent-gateway-governance CREATE
CALLOUT PATH ACTION
─────────────────────────────────────────────────────────────────── ───────
PSC static IP agent-gateway-callout-psc-ip RESERVE
PSC forwarding rule agent-gateway-callout-psc-endpoint CREATE
Private DNS zone agent-gateway-callout-zone REUSE
DNS A record agent-gateway-callout.internal.acme.local CREATE
AuthzExtension <gateway>-apigee-governance-extension CREATE
AuthzPolicy <gateway>-apigee-governance-policy CREATE
3 REUSE · 9 CREATE/RESERVE · 1 APPEND (modifies a resource you already own)
```
The footer line is the point of the table. Lead with it when you present the
plan: the count of things being modified is what the user is actually
approving.
**Gateway DNS peering is never `REUSE`.** It is the one row people get wrong,
because an existing peering config looks like something to reuse. Peering is
**per-domain**: an existing config covering another domain does not cover
yours, so your domain is **appended** to it. That makes the row `APPEND`, and
`APPEND` means the gateway — a resource the user already owns — is modified.
Marking it `REUSE` hides a modification inside a row that reads as free, which
is the one mistake this table exists to prevent.
Then the ordered steps. Keep it to one line each — a step list is scanned, not
read, and prose beside a duration is what makes a plan look longer than the
work.
```
┌─ Plan · steps ────────────────────────────────────────────────────────────────────────────────
LLM governance on my-agent-gateway acme-prod · us-east1
# STEP TIME NOTE
─ ─────────────────────────────────────── ───── ──────────────────────
1 Enable APIs ~1m
2 Environment + attach to instance ~4m env LOCKED while running
3 Envgroup on the callout hostname ~1m
4 Gateway egress attachment + DNS peering ~2m modifies your gateway
5 PSC endpoint + private DNS A record ~3m
6 Build and deploy the proxy ~2m must report EXTENSIBLE
7 AuthzExtension, then AuthzPolicy ~2m
8 Debug session, verify a live turn ~2m
─────
~20m step 2 is most of it
ON identity · token metering
OFF Model Armor · semantic cache · enforcement (offered after step 8)
OUT apigee-agent-gateway-governance.yaml — commit this
```
Colour the `NOTE` column the same way as the resource table: yellow for a row
that modifies something the user owns, plain otherwise.
**The `OUT` line is required.** The run ends with a file to commit and the user
has no idea one is coming otherwise; it is the whole bridge to re-running this
reproducibly. Durations are measured, not guessed — quote these. If a step runs
long say so rather than going quiet, because several of them look hung when
they are merely slow.
**Step 2 is not optional detail.** Whatever shape the plan takes — the full
table, a condensed list, a sentence — it must state that creating and attaching
the environment takes **several minutes (~4m)** and **locks the environment
while it runs**. That is the longest step, it is most of the ~20m total, and
the lock is the part the user cannot work around once it starts. Dropping the
`NOTE` cell to shorten the table drops the one thing they needed before
approving, so if the table is abbreviated, say it in prose instead. The same
goes for the other two `NOTE` cells: step 4 modifies the user's own gateway,
and step 6 must come up `EXTENSIBLE`.
## What dev mode produces
**Close with the same resource table, now showing what actually happened.**
The plan said what you intended; this says what exists. Same rows, same
grouping, same colours — only the action column changes, from intent to
outcome, with the elapsed time beside it. Reusing the shape is the point: the
reader already learned to read it ten minutes ago, and a diff between the two
tables is the whole report.
```
┌─ Done · LLM governance on my-agent-gateway ───────────────────────────────────────────────────
acme-prod · us-east1 elapsed 18m42s
GATEWAY LEG OUTCOME
─────────────────────────────────────────────────────────────── ─────────
VPC network default REUSED
Agent subnet default (10.142.0.0/20) REUSED
Gateway network attachment agent-gateway-egress-attachment REUSED
Gateway DNS peering internal.acme.local. APPENDED
APIGEE LEG OUTCOME
─────────────────────────────────────────────────────────────── ─────────
Apigee environment agent-gateway-govern CREATED
Environment group agent-gateway-govern-group CREATED
API proxy agent-gateway-governance rev 1 DEPLOYED EXTENSIBLE
CALLOUT PATH OUTCOME
─────────────────────────────────────────────────────────────── ─────────
PSC endpoint 10.142.0.42 CREATED ACCEPTED
Private DNS zone agent-gateway-callout-zone REUSED
DNS A record agent-gateway-callout.internal… CREATED
AuthzExtension my-agent-gateway-apigee-…-extension CREATED
AuthzPolicy my-agent-gateway-apigee-…-policy CREATED
VERIFIED 1 transaction captured on a live turn · identity + tokens present
OUT apigee-agent-gateway-governance.yaml
```
Green for `REUSED`, cyan for `CREATED`/`DEPLOYED`, yellow for `APPENDED`.
Carry the second value where there is one — `EXTENSIBLE` and `ACCEPTED` are the
two that decide whether any of this works, and burying them in prose is how a
run that silently governs nothing still reads as a success.
Anything that did **not** happen gets a row too, with the reason. A completion
table that lists only successes is the same failure as an assessment that
reports only what it checked.
Then write `apigee-agent-gateway-governance.yaml` into the working directory in the
schema `assets/apigee-agent-gateway-governance.example.yaml` documents, and show it to the user *then*
— as the handoff, not as an input:
> Everything above is captured in `apigee-agent-gateway-governance.yaml`. Commit it. From here you can
> change governance by editing that file and re-running, and the skill will
> reconcile to it — no conversation needed.
That sentence is the bridge to prod mode. It is the only point in dev mode
where the user sees YAML.
Emit exactly this shape — the same keys `assets/apigee-agent-gateway-governance.example.yaml`
documents. Prod mode has to be able to read back what dev mode wrote, unchanged,
so the **key set** must match with no drift in either direction.
**Carry a short comment header and a one-line comment on each non-obvious
field.** Not the example file's full explanations — a trimmed set. This file
gets committed and then read months later by someone who was not in the
conversation, and a bare key like `manageNetworkConfig: true` or a `matchPaths`
suffix list tells them nothing about what it controls or what breaks if they
change it. Comments cost nothing: they do not affect parsing, and the key-set
diff against the example ignores them.
What earns a comment: anything whose value was a decision (the match paths, the
feature toggles, `manageNetworkConfig`), anything with a non-obvious format (a
suffix rather than a path, a project number rather than an ID), and the header,
which should say what the file is, that it is the input to prod mode, and the
date and gateway it was generated against. What does not: `project`, `region`,
and anything self-describing.
The example file remains the full reference; this is the trimmed travelling
copy.
```yaml
apiVersion: apigee.googleapis.com/v1alpha1
kind: AgentGatewayGovernance
metadata:
name: agent-gateway-governance
description: Generated by apigee-agent-gateway-governance on <date>.
spec:
project: <project>
region: <region>
apigee:
org: <project>
environment: agent-gateway-govern
envgroup: agent-gateway-govern-group
hostname: agent-gateway-callout.internal.<project>.local
proxy: agent-gateway-governance
deploymentServiceAccount: "" # required once modelArmor or semanticCache is on
network:
vpc: <vpc>
subnet: <subnet>
networkAttachment: agent-gateway-egress-attachment
dns:
zone: agent-gateway-callout-zone
domain: internal.<project>.local.
record: agent-gateway-callout.internal.<project>.local # must equal apigee.hostname
gateway:
name: <gateway>
manageNetworkConfig: true
matchPaths:
- ":generateContent"
- "/chat/completions"
timeout: 5s
features:
identity:
enabled: true
defaultClientId: anonymous
tokenMetering:
enabled: true
mode: COUNT_ONLY
interval: 1
timeUnit: hour
models:
- bucket: gemini-pro
limit: 10000
- bucket: gemini-flash
limit: 40000
- bucket: other
limit: 40000
modelArmor:
enabled: false
mode: ENFORCE
template: ""
semanticCache:
enabled: false
threshold: 0.95
ttlSeconds: 60
embeddingsModel: text-embedding-005
deployedIndexId: agent_gateway_llm_cache
indexEndpointId: ""
indexId: ""
```
Write the values you actually used, not the placeholders. If the user enabled
Model Armor or the cache during the session, write them `enabled: true` with
the values that were provisioned — including `indexId` and `indexEndpointId`,
which `scripts/ensure_vector_search.sh` prints. A file that says `false` for a
feature that is live would make the next prod-mode run tear it down.
---
# Prod mode
The input file is the contract. The skill reconciles the setup to it.
## Hard refusal
**Refuse to run — do not improvise a config — when any of these hold:**
- No input file was supplied or found.
- `apiVersion` is not `apigee.googleapis.com/v1alpha1`, or `kind` is not
`AgentGatewayGovernance`.
- A required field under `spec.project`, `spec.region`, `spec.apigee` or
`spec.gateway` is missing or empty.
- A feature is enabled whose own required fields are absent — `modelArmor`
without `template`, `semanticCache` without `deployedIndexId`.
Say which field is wrong and stop. Do not fall back to dev mode and do not
substitute a default: silently inventing a value in prod mode destroys the
guarantee the file exists to provide.
Offer the fix as a diff against their file, and let them apply it.
## Reconcile, don't re-create
Everything in the workflow is idempotent and safe to re-run. Re-running against
an unchanged file should converge and report no change.
Run the plan step (above) in prod mode too — `scripts/deploy_proxy.sh` has
`--dry-run`, so the plan costs nothing and catches a bad file before it touches
the org.
---
# Interlocks
These hold in **both** modes. They are refusals, not warnings, except where
stated — each one is a failure that produces no error at runtime.
**Semantic cache with more than one wire shape — warn, then build it.** This is
the one interlock that is a warning rather than a refusal, in both directions,
because the defect is upstream and temporary.
**Trigger condition: the cache is being enabled, full stop.** Not only when
`matchPaths` has more than one entry. Do not raise it when describing what the
skill can do or when the cache is off — a caveat about a configuration the user
has not chosen is noise — but a single model behind a single wire shape does
**not** make the cache safe, so do not treat one shape as the all-clear.
The cache key is the embedding of the prompt and nothing else: no caller, no
model, no wire shape, no tenant.
The consequence that applies to **every** cache deployment is that a hit
crosses caller boundaries. Two callers whose prompts are merely similar share
an answer, so anything caller-specific is served from whoever asked first. A
gateway normally has several callers, and identity is on by default, so this is
the common configuration rather than an edge case. `agw.client_id` is available
and the cache policies accept no discriminator, so it cannot be scoped away.
Two further effects once more than one model answers here. Cross-shape the
second caller gets a body in the wrong format as an **empty HTTP 200** — a
success with no content, which reads as the agent breaking. Same-shape is
quieter and worse: the body parses perfectly and the only tell is
`model_version` in the payload.
Build the cache anyway when asked, in all three directions:
- `semanticCache.enabled: true` at all → **warn and proceed**, naming the
cross-caller exposure.
- `semanticCache.enabled: true` while `gateway.matchPaths` has more than one
entry → **warn and proceed**, adding the wrong-model effects.
- Adding a second entry to `matchPaths` while the cache is enabled → **warn and
proceed**.
The warning is not optional and must name the failure, not just gesture at it.
Emit it at plan time and again in the summary, in both modes:
> ⚠️ Known issue: the semantic cache keys on the prompt embedding alone — no
> caller, no model, no wire shape. **A hit is shared across callers**: two
> callers whose prompts are merely similar get the same answer, so anything
> caller-specific is served from whoever asked first. Enable it only where
> every caller may see every other caller's answer to the same question. One
> model behind one wire shape does not make this safe.
> With more than one wire shape a cached answer can also reach the wrong
> model's caller — an empty HTTP 200 across shapes, or a wrong-model body
> within one. The cross-shape case comes back as **success, not an error**: a
> 200 carrying no content, which reads as the agent itself being broken rather
> than as a cache fault, so it is looked for in the wrong place.
> Upstream fix expected; until it lands, treat cache hits as unverified.
Record it as a known issue in `apigee-agent-gateway-governance.yaml` whenever
dev mode writes a config with the cache on, so the next reader of the contract
sees it too.
**Model Armor without `feature-normalize`** — refuse. Model Armor reads
`agw.user_prompt`, which normalize sets at priority 15. Without it Model Armor
fails **closed** on every matching request. Normalize is in the base template,
so this only arises if someone has edited the feature list.
**A feature that calls a Google API without `deploymentServiceAccount`** —
refuse before deploying, not after. Model Armor and semantic cache both need
one; the deploy fails with `MISSING_SERVICE_ACCOUNT` otherwise, which reads as
a permissions problem rather than a missing field.
**Token metering does not gate on its own, and enforcement is a separate
feature.** The `CountOnly` quotas in `feature-token-metering.yaml` observe and
never block. To turn a budget into a limit, add
`assets/feature-token-enforce.yaml`, which puts `EnforceOnly` policies on the
request path under the same `SharedName`. Never improvise request-path
enforcement by making the metering quotas blocking: a blocking quota in the
response flow cannot withhold a response already on the wire, and it stops
counting the request that broke the limit. State that enforcement is one
request late by construction — the cost of a turn does not exist until the
model has answered, so the turn that crosses the limit completes and the
caller's next request is refused. See `gotchas.md`.
networking-psc.md 9.9 KB
# Networking
There are **two** network legs, and they fail for different reasons.
```
agent ──(1) client leg──▶ Agent Gateway ──(2) callout leg──▶ Apigee
proxy
```
- **Leg 2, gateway → Apigee**, is the one this skill builds. It is self-serve
and covered below.
- **Leg 1, agent → gateway**, is a *prerequisite you do not build by hand*.
Get it wrong and every other thing on this page still passes while no
traffic ever arrives. Read "The client leg" at the bottom before you start.
## Contents
- [Leg 2 — gateway to Apigee (the callout)](#leg-2-gateway-to-apigee-the-callout): lines 26-36
- [Prerequisites](#prerequisites): lines 37-51
- [Find the service attachment](#find-the-service-attachment): lines 52-60
- [Reserve the IP and create the endpoint](#reserve-the-ip-and-create-the-endpoint): lines 61-80
- [Private DNS](#private-dns): lines 81-94
- [Order of operations](#order-of-operations): lines 95-101
- [Leg 1 — the client leg (agent to gateway)](#leg-1-the-client-leg-agent-to-gateway): lines 102-227
## Leg 2 — gateway to Apigee (the callout)
The gateway egresses into your VPC, resolves the callout host on a private DNS
zone, and reaches the Apigee runtime through a PSC endpoint pointed at the
Apigee instance's service attachment.
```
CALLOUT_HOST --A--> PSC IP --> forwarding rule --> Apigee instance
serviceAttachment
```
## Prerequisites
- The Agent Gateway needs an **egress `networkAttachment`** into the VPC, and
a **`dnsPeeringConfig`** exposing your private domain to it. Without the
peering the host does not resolve from the gateway and nothing else matters.
This one the skill can supply: `scripts/ensure_gateway_connectivity.sh`
creates the attachment and adds both to the gateway, gated on
`gateway.manageNetworkConfig` and on the user confirming the diff. See
workflow step 0 in `SKILL.md`.
- Your project must be in the Apigee instance **`consumerAcceptList`** or the
PSC connection never reaches `ACCEPTED`.
- The gateway calls the ext-proc as its own Google-managed
`serviceExtensionsServiceAccount`
(`service-<num>@gcp-sa-dep.iam.gserviceaccount.com`).
## Find the service attachment
No `gcloud` equivalent; read it off the instance.
```bash
curl -s -H "Authorization: Bearer $TOKEN" \
"https://apigee.googleapis.com/v1/organizations/$ORG/instances"
```
## Reserve the IP and create the endpoint
```bash
gcloud compute addresses create agent-gateway-callout-psc-ip \
--region=$REGION --subnet=$SUBNET --purpose=GCE_ENDPOINT --project=$PROJECT
gcloud compute forwarding-rules create agent-gateway-callout-psc-endpoint \
--region=$REGION --network=$NETWORK --address=agent-gateway-callout-psc-ip \
--target-service-attachment=$APIGEE_INSTANCE_SERVICE_ATTACHMENT \
--project=$PROJECT
```
Confirm `pscConnectionStatus=ACCEPTED` before going further.
`--purpose=GCE_ENDPOINT` is verified — it is the correct value for this
endpoint.
Acceptance here is automatic *provided your project is on the instance's*
`consumerAcceptList`. This is the one PSC endpoint in the setup that you can
expect to reach `ACCEPTED` on your own; contrast the client leg below.
## Private DNS
```bash
gcloud dns managed-zones create $ZONE --dns-name=$DOMAIN \
--visibility=private --networks=$NETWORK --project=$PROJECT
gcloud dns record-sets create $CALLOUT_HOST. --type=A --ttl=300 \
--rrdatas=$PSC_IP --zone=$ZONE --project=$PROJECT
```
The A record name must be exactly the envgroup hostname and the AuthzExtension
`authority`. Check all three against each other before you conclude anything
else is broken.
## Order of operations
Environment property → build and deploy the proxy → envgroup host, DNS and PSC
(`ACCEPTED`) all in place → **then** the AuthzExtension → then the AuthzPolicy →
then traffic. The AuthzExtension is inert until the host resolves and the proxy
is deployed, so creating it early tells you nothing.
## Leg 1 — the client leg (agent to gateway)
**Where the agent runs decides whether this works at all.** This is a
prerequisite, not a step: nothing here is built with the commands above, and
getting it wrong is silent — leg 2 stays green and no traffic arrives.
Reference:
[Route traffic through Agent Gateway](https://docs.cloud.google.com/gemini-enterprise-agent-platform/scale/runtime/agent-gateway-runtime-deploy.md.txt),
[Set up VPC connectivity](https://docs.cloud.google.com/gemini-enterprise-agent-platform/govern/gateways/set-up-vpc-connectivity.md.txt),
and
[Delegate authorization](https://docs.cloud.google.com/gemini-enterprise-agent-platform/govern/gateways/delegate-authorization.md.txt).
### Use Agent Runtime
Agent Runtime is the supported path and the only self-serve one. Pass
`agent_gateway_config` at creation and the orchestrator builds the PSC endpoint,
routing, DNS and certificate trust for you:
```python
import agentplatform
client = agentplatform.Client(project=PROJECT, location=LOCATION)
client.runtimes.create(
agent=adk_app,
config={
"staging_bucket": "gs://…",
"requirements": ["google-cloud-aiplatform[agent_engines,adk]>=2.1,<3", "google-adk>=2.9,<3"],
"agent_gateway_config": {
"agent_to_anywhere_config": {"agent_gateway": AGENT_GATEWAY_RESOURCE},
},
"identity_type": "AGENT_IDENTITY",
# Required. Without it every invocation 401s -- see below.
"env_vars": {
"GOOGLE_API_PREVENT_AGENT_TOKEN_SHARING_FOR_GCP_SERVICES": "False",
},
# Required if the agent carries any custom class -- see below.
"extra_packages": ["my_agent_pkg"],
},
)
```
**`env_vars` is not optional here.** Omit it on a gateway-attached agent built
recently and *every* invocation fails, before any user code runs, with a
`400 INVALID_ARGUMENT` wrapping a `401 UNAUTHENTICATED` on the agent's own
`sessions.create`. Both conditions are needed — attached to a gateway, and a
recent build — which is why an older agent on the same gateway keeps working
and makes the new one look like a code problem. The deploy succeeds and the
engine reports healthy, so it stays invisible until the first request. Set the
variable explicitly rather than relying on the platform default, which has
already moved once.
The trap is where the symptom points: it is a 401 on a model call, so the first
suspect is the Apigee proxy you were just told to build. It is not. Rule this
out before debugging anything on the Apigee side.
**`extra_packages` matters as soon as the agent is non-trivial.** A plain
`Agent` is pickled by value and needs nothing. An agent carrying a custom class
is pickled by *reference*, and the remote cannot import it:
```
ModuleNotFoundError: No module named 'my_agent_pkg'
UserCodeControlPlaneError: Control plane operation failed due to user code
```
The create then fails and the engine is rolled back, so no resource is left to
pull logs from — diagnosis means searching Cloud Logging by resource type
alone. Name the package at create time instead. Drop the line only for an agent
with no custom classes.
Use `agentplatform`, not `vertexai`: `vertexai.Client` is deprecated and warns
(`Please use agentplatform.Client instead`), and `client.agent_engines` is
renamed `client.runtimes`. Both ship inside `google-cloud-aiplatform`, and
`agent_gateway_config` / `identity_type` are unchanged across the rename.
`AGENT_GATEWAY_RESOURCE` is the full
`projects/{p}/locations/{r}/agentGateways/{name}`. There is no `gcloud` surface
for Agent Runtime — no `agent-engines` group on any track — so this is SDK only.
**Grant the Vertex AI service agent read access to the gateway first.** It
resolves the gateway on your behalf, and without it creation fails at once with
a `400 FAILED_PRECONDITION`: *"Permission denied to get Agent Gateway … Please
ensure Vertex AI Service Agent has `networkservices.agentGateways.get`
permission on the gateway project."* The error suggests waiting for propagation,
which sends you off to wait for something that will never arrive if the binding
simply is not there.
```bash
gcloud projects add-iam-policy-binding $GATEWAY_PROJECT \
--member="serviceAccount:service-$PROJECT_NUMBER@gcp-sa-aiplatform.iam.gserviceaccount.com" \
--role="roles/networkservices.viewer"
```
`roles/networkservices.viewer` is the narrowest predefined role carrying that
permission — the `agentGatewayUser` and `agentGatewayViewer` roles do **not**
include it, despite the names.
### A GCE VM will never work
The supported compute is GKE or Cloud Run — there is no GCE. The egress guide is
explicit that the gateway is only compatible with Cloud Run in **ambient
networking** mode (`--ambient-networking=regional`, `--vpc-egress=all-traffic`,
plus an env var installing the SWP TLS-inspection root cert). Do not spend time
on a VM; it is a dead end.
### Do not hand-build the consumer PSC endpoint
The gateway's client entry point is an **mTLS PSC service attachment in a Google
tenant project**. You can create a consumer forwarding rule to it, and it will
sit at `PENDING` forever: acceptance requires an internal
`References.CreateReference` call that gcloud does not expose. A `PENDING`
endpoint presents as TCP 443 simply closed, which reads like a firewall problem
and is not.
Raw Cloud Run is possible but is explicitly "the hard way": it additionally
needs a catch-all Cloud DNS response policy, a `ClientTlsPolicy`, a
`BackendService` onto the gateway attachment, and project-level `HTTPRoute` and
`TCPRoute` — resources that require a reserved `aersvd-` name prefix that
Traffic Director only lets specific P4SAs create. Treat it as not self-serve.
### Known limits
Agent Gateway governs agents **running on GCP only** (Agent Runtime, Gemini
Enterprise). Agents outside GCP are unsupported until a public endpoint ships.
Self-signed-cert destinations are also unsupported, and PSC automation and DNS
service binding are not yet available — which is why leg 2's network attachment
and DNS peering are built by hand above.
recipes.md 9.3 KB
# Recipes
Each recipe is an **AFT feature**, not a separate setup procedure. Enable one
by adding its file to the template's `features` list and recompiling:
```yaml
features:
- feature-identity.yaml
- feature-token-metering.yaml
- feature-model-armor.yaml # add this
```
```bash
python3 scripts/compile_check.py assets/apigee-proxy-template.yaml # offline; needs PyYAML
gcloud apigee apis import organizations/$ORG/apis/$PROXY \
--from-template=assets/apigee-proxy-template.yaml
```
Features merge by `priority`: identity 10, token enforcement 12, normalize 15,
Model Armor 20, semantic cache 30, metering 50. Steps land in that order within
each flow.
**Every recipe must be gated.** A fail-closed policy with no condition kills the
agent's turn on the first call that carries no prompt. How exposed you are
depends on the AuthzPolicy: a suffix list of model-call paths routes only those
(measured with `:generateContent` alone), but widen it and the ext-proc sees all
agent egress — 12 calls for one measured turn, 11 of them promptless. Gate regardless, so the
policy stays safe to widen.
## Contents
- [Status](#status): lines 37-98
- [E1 — Model Armor](#e1-model-armor): lines 99-113
- [E2 — Semantic cache](#e2-semantic-cache): lines 114-178
- [E3 — ServiceCallout](#e3-servicecallout): lines 179-184
## Status
The `Live traffic` column is the one that decides risk. "No" does not mean
broken; it means nothing has proved its runtime behaviour, which is a
different claim from "it compiles".
| Recipe | Feature file | Compiles | Live traffic |
| --- | --- | --- | --- |
| Identity | `feature-identity.yaml` | yes | **yes** — JWT verified, `agw.client_id` set on a real turn |
| Token metering | `feature-token-metering.yaml` | yes | **yes** — per-model counters moved on real turns |
| E1 Model Armor | `feature-model-armor.yaml` | yes | **yes, thinly** — injections refused through ENFORCE; one benign prompt passed `NO_MATCH_FOUND`. No false-positive rate |
| E2 Semantic cache | `feature-semantic-cache.yaml` | yes | **yes** — miss/hit measured end to end, see below |
| Token enforcement | `feature-token-enforce.yaml` | yes | **yes** — over-budget caller refused with 429 on live gateway traffic, model never called (`used.count` 1086 vs `allowed.count` 500) |
| E3 ServiceCallout | — | — | deliberately not authored, see below |
**E1 is still the one to be careful with**, but for a narrower reason than
before. It now has live evidence in both directions: injections were refused
through ENFORCE, and one ordinary prompt (`"name a planet"`) returned
`filterMatchState = NO_MATCH_FOUND` and completed normally, so routine traffic
does survive `MEDIUM_AND_ABOVE`. One benign sample is not a false-positive
rate. It remains the only recipe that fails **closed**, so on a proxy already
serving turns recommend `DRY_RUN` first and say why: the unknown is not
whether it works, it is how often it refuses something it should not.
**E2 measured live** — one prompt sent twice inside the 60s TTL:
| | miss | hit |
| --- | --- | --- |
| proxy-side elapsed | 2410 ms | **375 ms** |
| `cache_hit` | false | true |
| `nearest_neighbor_measure` | — | 0.999999 (threshold 0.95) |
| `SCP-populate` upsert | ran | **skipped** |
| flash quota counter | moved | **absent — quota skipped** |
| Model Armor | ran | **ran** |
Four documented traps confirmed correct by that pair: populate is skipped on a
hit, so the pre-namespaced `cache_hit` condition really does resolve (the
documented `semanticcache.lookup.*` form would have failed open and
re-upserted); metering does not double-count, because although
`metering-JS-extract-model` runs ungated and did extract 188 tokens from the
replayed body, every `LTQ` step was skipped; the matched key equals the
`datapointId` the miss wrote, so the round trip is real rather than a
coincidental neighbour; and **a hit still pays for Model Armor**, which runs
at priority 20 before the lookup at 30. The cache saves the model call, not
the scan — the 375 ms includes the scan, an embeddings call and
`findNeighbors`.
All six compile together: 16 policies and 22 bundle entries, steps ordered
identity → enforcement → normalize → Model Armor → cache lookup in
`PreFlow/Request`, and cache populate → metering in `PostFlow/Response`.
The **base** proxy — identity plus token metering — is deployed on a live org
and verified `EXTENSIBLE`.
**Verification status is per-recipe, and the table below is the only source of
truth for it.** Do not generalise from this paragraph; an earlier version of it
claimed none of the optional recipes had seen live traffic, which contradicted
E2's own live measurements twenty lines later. Where a recipe says
"compile-verified only", that means the check proved structure and nothing
proved runtime behaviour — which is the distinction that matters for Model
Armor, the one recipe that fails **closed**.
## E1 — Model Armor
Authored. Screens the prompt before the model; blocks on a filter match. A
benign prompt passes; an unsafe one is stopped **before Gemini** and surfaces
as `400 … steps.sanitize.user.prompt.FilterMatched`.
Needs `roles/modelarmor.user` on the deployment SA and a deploy with
`?serviceAccount=`. `SanitizeModelResponse` is the response-path analogue, its
source being `$.candidates[-1].content.parts[-1].text`.
**It reads `agw.user_prompt`, not a JSONPath**, and that variable is set by
`feature-normalize.yaml` at priority 15. Enabling Model Armor without that
feature leaves the variable unset — and because the policy fails closed, the
result is HTTP 500 on every matching request rather than a skipped scan.
## E2 — Semantic cache
Authored and verified live. Two policies: `SemanticCacheLookup` in the Request
PreFlow, `SemanticCachePopulate` in the response phase.
Two things make this harder than it looks on a no-route proxy:
- **Populate must be gated on the cache-hit flag.** With no target endpoint the
response flow runs on a hit too, so ungated populate re-embeds and re-upserts
the answer it just served.
- **The flag is not the documented name.** Runtime emits
`SemanticCacheLookup.<policy>.cache_hit`; the docs say
`semanticcache.lookup.<policy>.cache_hit`, which never resolves — and an
unresolved variable makes `!= true` true, so it fails open and looks exactly
like the ungated bug.
When authoring this as a feature, the condition must be written
**pre-namespaced** (`SemanticCacheLookup.semanticcache-SCL-lookup.cache_hit`),
because the compiler does not rewrite policy-derived flow variables.
- **Metering double-counts on a hit unless you gate that too.** The quota reads
the token count out of the replayed response and counts tokens the model
never produced — measured, the counter moved by exactly the replayed answer's
97 tokens. `feature-token-metering.yaml` carries the same cache-hit clause on
**all three** quota steps. Enabling the cache without it silently inverts
what the cache is for.
- **Populate must also be gated on `response.status.code = 200`.** The policy
is status-blind: gated only on the hit flag it caches upstream errors too.
Observed — a transient 429 written to the cache and then replayed **as HTTP
200** to every identical prompt for the whole TTL, turning a momentary blip
into a persistent wrong answer that defeats status checking. Raised with the
Apigee team; carry the gate regardless, it is the only defence today.
Measured on a live setup: cold 4743 ms versus 336 ms served from cache, with
the model never called. A second run on a different prompt measured 1396 ms
versus 382 ms — a 3.7x ratio.
**Measure proxy-side, from a debug session, not from the caller.** On that same
pair the client saw 15445 ms versus 13114 ms — a 15% difference
indistinguishable from noise, because agent session setup dominates the round
trip. Anyone timing the caller concludes the cache does nothing.
**A hit still pays for Model Armor.** Feature priority puts Model Armor (20)
ahead of the cache lookup (30), so the compiled request flow scans the prompt
before the cache is consulted. That order is the safer one — it stops a prompt
reaching a cached answer unscanned — but it means the floor on a hit is the
Model Armor latency, not zero.
**The cache reads `agw.user_prompt` too**, from the same priority-15 feature.
That is what lets one cache serve both wire shapes: `LLM_URI_MATCH` matches
`*generateContent*` and `*chat/completions*`, and the prompt is selected from
either body layout in JS. Verified — a repeat prompt hit across shapes.
Do not widen `LLM_URI_MATCH` without `feature-normalize` present; the same
condition arms Model Armor, which fails closed.
**Prerequisites are built by `scripts/ensure_vector_search.sh`**: the index
(width fixed by `embeddingsModel`, `STREAM_UPDATE`, both immutable), the
endpoint, and the deploy of one onto the other. `--yes` gated, idempotent and
resumable — resumable matters because the deploy step alone runs about 34
minutes. It is also the only part of this skill that bills continuously, per
node-hour for as long as the index stays deployed; the script prints the cost
note and the teardown order before asking. You also need
`roles/aiplatform.user` on the deployment service account, and
`<DeployedIndexID>` spelled all-caps.
## E3 — ServiceCallout
Deliberately not authored. `ServiceCallout` is on the Extension Processor
unsupported-policy list, yet it imports, deploys `EXTENSIBLE` and executes from
both flows. Docs and platform disagree; don't build on it until that is
resolved.
setup.md 7.2 KB
# Environment setup before you start
Everything here is a prerequisite the skill does **not** create. Work through
it once per project; `scripts/assess_integration.sh` checks the Apigee and
gateway side afterwards, but it cannot check your local toolchain or whether
billing is attached.
## Contents
- [1. Install the Google Cloud SDK](#1-install-the-google-cloud-sdk): lines 19-35
- [2. Select the project](#2-select-the-project): lines 36-48
- [3. Attach a billing account](#3-attach-a-billing-account): lines 49-69
- [4. Enable the APIs](#4-enable-the-apis): lines 70-106
- [5. Pick the region, once](#5-pick-the-region-once): lines 107-127
- [6. Authenticate](#6-authenticate): lines 128-153
- [7. IAM roles](#7-iam-roles): lines 154-180
- [8. What the skill still needs from you](#8-what-the-skill-still-needs-from-you): lines 181-189
## 1. Install the Google Cloud SDK
The skill drives `gcloud` throughout and several steps have no `gcloud`
equivalent, so it also calls the Apigee REST API with a token minted by
`gcloud`.
- [Install the gcloud CLI](https://docs.cloud.google.com/sdk/docs/install-sdk.md.txt)
Version **588.0.0 or later** is required: `gcloud apigee apis import
--from-template` is GA only from 588. `assess_integration.sh` checks this and
warns if the installed version is older.
```bash
gcloud version
gcloud components update
```
## 2. Select the project
```bash
gcloud config set project PROJECT_ID
```
The skill takes `project` from the input file in prod mode and from this
setting or the conversation in dev mode. One project holds the gateway, the
VPC and the network attachment. Apigee may live in **a different project** —
the callout reaches it over PSC — but the region must match (see 5).
- [Create and manage projects](https://docs.cloud.google.com/resource-manager/docs/creating-managing-projects.md.txt)
## 3. Attach a billing account
The project must have an **active billing account**. Apigee, Agent Gateway and
Vector Search are all billable, and a project without billing fails partway
through the build rather than up front — typically at the Apigee environment
or the index deploy, after earlier steps have already created resources.
```bash
gcloud billing projects describe PROJECT_ID
```
- [Enable, disable or change billing for a project](https://docs.cloud.google.com/billing/docs/how-to/modify-project.md.txt)
- For what each component costs, see the published pricing pages rather than
any figure quoted in a skill: [Google Cloud pricing](https://cloud.google.com/pricing)
Only one resource in this skill bills **continuously whether or not traffic
flows**: a deployed Vector Search index, used by the semantic cache. It is
off by default, disclosed before it is created, and
`scripts/teardown_vector_search.sh` removes it in the order that does not
fault live traffic.
## 4. Enable the APIs
Base set, always needed:
```bash
gcloud services enable \
apigee.googleapis.com \
networkservices.googleapis.com \
networksecurity.googleapis.com \
compute.googleapis.com \
dns.googleapis.com \
--project PROJECT_ID
```
| API | Used for |
| --- | --- |
| `apigee.googleapis.com` | the environment, envgroup, proxy and deployment |
| `networkservices.googleapis.com` | the Agent Gateway and the AuthzExtension |
| `networksecurity.googleapis.com` | the AuthzPolicy that routes traffic to the callout |
| `compute.googleapis.com` | the network attachment, PSC endpoint and subnet checks |
| `dns.googleapis.com` | the private zone and A record for the callout hostname |
Per feature, only if you enable it:
```bash
# semantic cache -- Vector Search index and index endpoint
gcloud services enable aiplatform.googleapis.com --project PROJECT_ID
# Model Armor prompt screening
gcloud services enable modelarmor.googleapis.com --project PROJECT_ID
```
`aiplatform.googleapis.com` is also what the agent itself runs on, so it is
usually already enabled in a project that has a working agent.
- [Enabling and disabling services](https://docs.cloud.google.com/service-usage/docs/enable-disable.md.txt)
## 5. Pick the region, once
**The Agent Gateway, the subnet and the Apigee runtime instance must all be in
the same region.** This is the constraint most likely to force a rebuild,
because an Apigee instance's region is fixed at creation.
```bash
gcloud config set compute/region REGION
```
Choose a region where **both** Apigee and Agent Gateway are available —
availability differs by product, so check before committing:
- [Google Cloud locations](https://docs.cloud.google.com/about/locations.md.txt)
- [Apigee locations](https://docs.cloud.google.com/apigee/docs/locations.md.txt)
This skill has been exercised in `us-west1` and `us-east1`. Preview features
are often restricted to `us-central1` or `global`, so if you are enabling
something still in preview, confirm it is offered in the region you picked
rather than assuming the general default.
## 6. Authenticate
Two credentials, for two different callers.
```bash
# for gcloud itself
gcloud auth login
# for the REST calls the scripts make, and for client libraries
gcloud auth application-default login
```
The scripts deliberately use **Application Default Credentials** for the
Apigee REST API. On some organizations a plain `gcloud auth
print-access-token` is rejected by `apigee.googleapis.com` with
`401 UNAUTHENTICATED / ACCESS_TOKEN_TYPE_UNSUPPORTED`; ADC is not. If you make
ad-hoc `curl` calls alongside the scripts, use ADC for those too:
```bash
TOKEN=$(gcloud auth application-default print-access-token)
```
For an unattended or CI run, use a service account instead:
- [Service account credentials](https://docs.cloud.google.com/iam/docs/service-account-creds.md.txt)
## 7. IAM roles
The identity running the skill needs, at minimum:
| Role | Why |
| --- | --- |
| `roles/apigee.admin` | create the environment, envgroup, proxy and deployment |
| `roles/compute.networkAdmin` | network attachment, PSC endpoint, subnet reads |
| `roles/dns.admin` | the private zone and A record |
| `roles/networkservices.agentGatewayUser` | read and modify the Agent Gateway |
| `roles/networkservices.serviceExtensionsAdmin` | create the authorization extension |
| `roles/networksecurity.admin` | create the authorization policy that attaches it |
Feature-specific, and granted to the **proxy's** service account rather than
to you:
| Role | Why |
| --- | --- |
| `roles/aiplatform.user` | the semantic cache calls Vector Search |
| `roles/modelarmor.user` | Model Armor prompt screening |
Granting a role to a service account is a **sensitive operation**: it widens
what the deployed proxy can reach. Review the grant before applying it, and
prefer a dedicated service account for the proxy over the Compute default.
- [Understanding IAM roles](https://docs.cloud.google.com/iam/docs/roles-overview.md.txt)
## 8. What the skill still needs from you
Three things it never creates, checked by `assess_integration.sh`:
- **An Agent Gateway.** This skill attaches to one; it does not create one.
- **An agent whose traffic actually routes through that gateway.** On Agent
Runtime that is set with `agent_gateway_config` at agent **creation** time
and cannot be added afterwards.
- **An Apigee org with a runtime instance in the gateway's region.**
verify.md 14.3 KB
# Verifying the callout
**You cannot test this with curl.** The endpoint is internal — only the gateway
reaches the PSC host — and the proxy expects the gateway's IAP-egress JWT.
Driving traffic also needs the gateway's client-facing ingress and mTLS.
The method is: arm an Apigee debug session, send real traffic through the
gateway, read the transactions back.
**Use the script.** Everything in this file below "What to confirm" is
implemented by `scripts/read_debug_session.sh`, which fetches the
transactions and prints the checklist as a table. The raw `curl` calls are
kept because you need them to diagnose the script itself, not because you
should be running them by hand:
```bash
scripts/read_debug_session.sh --org "$ORG" --env "$ENV" --proxy "$PROXY" \
--rev "$REV" --arm # prints the session id and when it closes
# ... drive one agent turn ...
scripts/read_debug_session.sh --org "$ORG" --env "$ENV" --proxy "$PROXY" \
--rev "$REV" --session "$SESSION" [--steps] [--json]
```
`--arm` reports the **absolute** expiry computed from the `validity` the
server returned, and says so when it was clamped — see the clamp note below.
The transaction shape is not guessable, and a parser that returns nothing
against a healthy trace is the normal first result; that is what the script
exists to stop.
## Contents
- [Arm a session](#arm-a-session): lines 40-88
- [Read it back](#read-it-back): lines 89-128
- [What to confirm, in order](#what-to-confirm-in-order): lines 129-209
- [Verifying enforcement](#verifying-enforcement): lines 210-246
- [Measure proxy-side, not from the caller](#measure-proxy-side-not-from-the-caller): lines 247-257
- [Checking deployment type](#checking-deployment-type): lines 258-267
- [Offline check](#offline-check): lines 268-277
## Arm a session
How much filtering you need depends on **how broadly your AuthzPolicy matches**,
and the shipped default matches narrowly.
With a suffix list of model-call paths, only those are routed to Apigee. With
`:generateContent` alone an unfiltered session captures exactly **one**
transaction per agent turn — one per governed shape if the list is longer —
verified across several unfiltered sessions, each of which returned a single
transaction. Filtering is optional there, and one transaction is the healthy
result rather than a truncated one. Zero transactions means the callout is not
landing.
Broaden the policy — drop the suffix, or match on a prefix — and the ext-proc
begins seeing every agent egress instead. Measured by widening the policy to
`prefix: /` and running one single-question turn: **12 transactions**, of which
exactly one was the model call. The rest were a session create, a session read,
two `/v1/metrics`, two `/v1/logs`, one `/v1/traces`, and four posts whose path
the trace did not record.
`count` maxes at 15, so that one turn used 12 of the 15 slots — it did not
truncate, but a turn with tool calls would. **Filter whenever the policy matches
broadly**, or the call you care about gets pushed out.
```bash
curl -s -X POST -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
".../environments/$ENV/apis/$PROXY/revisions/$REV/debugsessions?timeout=600" \
-d '{"count":15,"tracesize":5120,"filter":"(request.uri Like \"*generateContent*\")"}'
```
Bounds: `count` min 1 / max 15 / default 10, `tracesize` max 5120, `timeout`
min 60 / max 600 **seconds**. Passing 900 is rejected outright (*"debug session
timeout (900) should be >= minimum (60) seconds and <= maximum (600)
seconds"*). The `filter` is a flow-`Condition` expression evaluated against the
request.
**600 is what the API validates against, NOT necessarily what you get. Read
`validity` back off the create response and plan from that.** Observed on a
PAYG org (`subscriptionType: PAID`): `?timeout=600` was accepted with no error
and came back `"timeout": "300", "validity": 300` — silently halved. Whether
the 300 ceiling is tier-dependent or a platform change is not established.
This matters more than it sounds. The scenario it breaks is the common one —
arming a session, then going to drive an agent turn by hand. You believe you
have ten minutes, you have five, and the session expires into the *zero
transactions* state that this file teaches you to read as "the callout is not
landing". The wrong conclusion is right there and the clamp is invisible unless
you diff the response against the request.
## Read it back
```bash
curl -s -H "Authorization: Bearer $TOKEN" ".../debugsessions/$SESSION/data"
curl -s -H "Authorization: Bearer $TOKEN" ".../debugsessions/$SESSION/data/$TXN_ID"
```
**`/data` returns a BARE JSON LIST of transaction ids, not an object** -- `[]`
when nothing was captured. An empty list is a *meaningful result* here, not an
error.
**But `[]` does NOT prove the callout is dead. Corroborate before concluding
that, always.** Observed on a working proxy: every debug session on three
consecutive revisions returned `[]` while traffic flowed and was demonstrably
governed -- four sessions, one armed 75 seconds before traffic and polled for
over three minutes. The callout was landing; the tracing was not recording it.
Cause unknown, and not propagation delay.
This is the dangerous shape, because the AuthzExtension is `failOpen: true`:
a genuinely dead callout also looks like healthy traffic, so `[]` plus
"turns succeed" is exactly what both states look like. An operator trusting
`[]` alone will chase a networking fault that does not exist.
**The cheap corroboration is a refusal probe.** Send a prompt the governance
layer must refuse -- an injection, if Model Armor is on -- and look at the
error:
- A refusal carrying an Apigee fault (`400`, `errorcode:
steps.sanitize.user.prompt.FilterMatched`) proves the proxy is in the path.
Only Apigee produces that. The callout lands; your tracing is broken.
- No refusal, or a generic gateway error, is consistent with a dead callout.
Only after the probe fails should `[]` be read as "the callout is not
landing".
A helper written as `d.get("responses") or d.get("data")` raises
`AttributeError: 'list' object has no attribute 'get'` on precisely that case,
sending you to debug your own parser instead of the callout. Handle both
shapes. The ids come from `/data`; the flow variables below come from
`/data/$TXN_ID`, one fetch per transaction.
## What to confirm, in order
0. **A known-good baseline turn, captured BEFORE any of the build runs.**
Drive one agent turn and record that it succeeded. This checklist otherwise
assumes the only question is *does the new thing work*, when the question
that actually arises is *did the new thing break something that used to
work* -- and with no pre-build invocation in the logs there is nothing to
compare against. It matters here more than usual because
`ensure_gateway_connectivity.sh` makes a **one-way** change to a gateway
that is already carrying live agent traffic.
When you do reach for log archaeology, **match on the status NAME**
(`UNAUTHENTICATED`, `PERMISSION_DENIED`), never the numeric code. Cloud
Logging's `:` is a substring match and agent-engine streams carry Docker
digests, so `textPayload:"401"` matches the hex in a layer id like
`1940178d9f4c`. That produced three convincing hits timestamped before any
change and a confident, wrong "pre-existing failure" conclusion; searching
`UNAUTHENTICATED` moved the first real occurrence to *after* the change.
1. **The gateway has `networkConfig`.** Check this before reading any trace —
if it is absent there will be no transactions to read, because the gateway
has no route into the VPC. `describe ... --format='value(networkConfig)'`
printing nothing is the symptom; `scripts/ensure_gateway_connectivity.sh` is
the fix.
2. **The PreFlow steps ran at all.** If not, the callout isn't landing — check
the three hostnames and that the proxy is deployed. Also check the order
they were created in: **the AuthzExtension is inert until the host resolves
and the proxy is deployed**, so one created before those existed reports no
error and simply never fires. Its existence is not evidence it works.
3. **`request.content` and `response.content` are populated.** Empty means the
`apigee-request-body` / `apigee-response-body` metadata is missing from the
AuthzExtension.
4. **`agw.model_name` is the bucket you expect.** `other` is now a real,
metered bucket rather than a hole — but it still means the name matched
neither `pro`/`argon` nor `flash`/`hydrogen`, so check it is deliberate. On
a Gemini turn `other` means the normalization didn't find the model where it
looked.
5. **`agw.token_source` names the branch that matched** — `gemini`, `openai`,
`sum`, or `none`. `none` is the diagnostic: the count was not found in any
known shape, `agw.total_tokens` is deliberately left unset, and the quota
will raise `FailedToResolveTokenUsageCount` rather than meter a silent
zero. Check this before suspecting the quota itself.
6. **`agw.total_tokens` is numeric and the matching counter incremented.**
Pair it with `agw.token_source`: a count with no counter movement means
the bucket has no quota bound to it.
7. **`agw.user_prompt` is set on any request Model Armor or the cache will
see.** It comes from `feature-normalize` at priority 15. Unset means
either the body shape is unrecognised or that feature is missing from the
template — and with Model Armor enabled the second case is a 500 per
request, not a skipped scan.
8. **Gated steps are skipped on non-model calls.** Only observable if the
AuthzPolicy matches broadly — under a model-call-only suffix list those
calls never reach Apigee, so there is nothing to see. Where they do arrive, a step
skipped on `appendEvent` or `/v1/traces` is the gate working, not a failure.
9. **With the cache ON and more than one shape configured: on a
`cache_hit = true`, `agw.requested_model` matches the shape of the request
that produced it.** Today it will not — the cache key is the prompt
embedding alone, so the first model to answer a prompt answers it for all
of them. A mismatch here is the proxy-side signature of the empty-answer
symptom in `gotchas.md`; the caller sees a 200 with no content and nothing
in the agent is wrong. Check this before believing a dual-shape cache
demo.
10. **On any refusal path, read the body the CALLER receives — not just the
variables going in.** Checks 1-9 are all inbound: did the policies run,
did the bodies arrive, is the bucket right. Not one asks what comes back
out, and every refusal path in this skill *composes a response*: Model
Armor's 400, the quota's 429. Those are the only parts of the proxy an end
user ever sees.
This gap shipped a real defect. Enforcement was verified clean — 429,
counters correct, model never called — while the fault body handed the
caller the full `principal://...` assertion with org number, project
number and the agent's resource id. `agw.client_id` was visible in three
separate traces and nobody connected it to the fault body, because nothing
asked them to look at the fault body.
Concretely: take the terminal response `content` of a refused transaction
and grep it for `principal://`, your project number and your org number.
For the quota path that is now a regression test. For Model Armor it is
worth running once — what its faultstring exposes has not been checked.
`scripts/read_debug_session.sh` prints this body for any non-2xx
transaction so it is in front of you rather than one fetch away.
## Verifying enforcement
Enforcement is opt-in, and the only feature here that fails **closed**. Two
things mislead people who turn it on, both avoidable:
**It is one request LATE by construction.** The turn that crosses the budget
completes normally and returns 200; the *next* request from that caller is
refused. Sending one over-budget turn, seeing a 200 and concluding enforcement
is broken is the common mistake. A token budget cannot be enforced before the
tokens are known.
**Read the `enforce-*` counters, not the `metering-*` ones.** The metering
policies are `CountOnly`, and a CountOnly quota reports
`allowed.count = 9223372036854775807` — max int64. That is correct for
counting without a ceiling, and it looks exactly like "no limit is applied".
The ceiling lives on the request-flow `EnforceOnly` policy.
The procedure:
1. Arm a session: `scripts/read_debug_session.sh ... --arm`.
2. Drive turns against one caller until the budget is crossed. Watch
`ratelimit.enforce-LTQ-<bucket>.used.count` climb past `allowed.count`.
3. Expect the refusal on the **following** turn: `429`, errorcode
`policies.llmtokenquota.LLMTokenQuotaViolation`, and no model call in the
trace.
4. Confirm the executed steps stop at the quota — nothing after
`enforce-LTQ-<bucket>` runs, because those policies are
`continueOnError: false`.
5. Apply check 10 to the 429 body.
A worked example, flash budget 500/hour: `used.count 1086`,
`allowed.count 500`, `exceed.count 586`, `failed true`,
`error.state PROXY_REQ_FLOW`. The request-path `EnforceOnly` policy read the
count the response-path `CountOnly` policy accumulated under the same
`SharedName`, which is also the proof that `SharedName` joins the two halves
in a no-route proxy.
## Measure proxy-side, not from the caller
Timing the agent does not show you what the proxy did. On one semantic-cache
miss/hit pair the client saw 15445 ms versus 13114 ms — a 15% difference
indistinguishable from noise — while the proxy-side spans for the same two
calls were 1396 ms and 382 ms, a 3.7x gap. Agent session setup dominates the
round trip and hides everything the proxy changed.
Take the elapsed figure from the debug session's transaction, not from the
client, for any latency claim about the cache or a policy.
## Checking deployment type
```bash
curl -s -H "Authorization: Bearer $TOKEN" ".../environments/$ENV/deployments"
```
`proxyDeploymentType: EXTENSIBLE` is required. `STANDARD` will not govern the
agent's off-Apigee tool egress, and a tool policy that "doesn't fire" is usually
this.
## Offline check
Before any of the above, validate the template compiles and holds its invariants
— no org needed:
```bash
# Needs PyYAML -- the script names the interpreter if it is missing.
# pip install pyyaml, or use a python3 that has it. See gotchas.md.
python3 scripts/compile_check.py assets/apigee-proxy-template.yaml
```
assess_integration.sh 35.5 KB
#!/bin/bash
# Read the live state of an Agent Gateway + Apigee ext-proc setup and report it.
#
# Strictly READ-ONLY. It creates, modifies and deletes nothing, so it is safe to
# run against production and safe to run before the user has agreed to anything.
#
# Two callers, one discovery pass:
# - "assess" -- answer "how is this running, and what is wrong with it"
# - the PLAN -- decide CREATE vs REUSE per resource before a dev-mode run,
# which is the only honest way to say what is shared with an
# existing deployment (another governance extension, say)
# rather than guessed
#
# Every check that can fail silently in this stack has an entry here. That is
# the point: nothing below reports a problem at runtime on its own.
#
# Data goes to stdout as JSON with --json. The table goes to stdout otherwise.
# Diagnostics go to stderr.
set -euo pipefail
usage() {
cat <<'EOF'
Assess an Agent Gateway + Apigee ext-proc setup. Read-only.
Usage:
assess_integration.sh --project P --region R --gateway G [options]
Required:
--project P GCP project
--region R region; the gateway, the subnet and the Apigee
instance must all share it
--gateway G Agent Gateway name
Options:
--org ORG Apigee org (default: --project)
--env ENV environment expected to host the proxy
--envgroup EG environment group expected to carry the hostname
--hostname H callout hostname; must match the DNS record and the
AuthzExtension authority byte for byte
--proxy PROXY proxy name
--vpc VPC VPC the gateway egresses into
--subnet SUBNET subnet the PSC endpoint is reserved in
--json machine-readable; the plan reads this
--help this text
Exit status:
0 no FAILs (WARNs may be present)
1 at least one FAIL
2 bad invocation
EOF
}
PROJECT=""; REGION=""; GATEWAY=""; ORG=""; ENVNAME=""; ENVGROUP=""
HOSTNAME_=""; PROXY=""; VPC=""; SUBNET=""; JSON=0
# How this script recognises resources THIS skill created, as opposed to some
# other extension on the same gateway. Defined once: these used to be the bare
# string "extproc" scattered across three places, and renaming the resources
# silently broke every one of them.
readonly OUR_POLICY_MATCH="apigee-governance" # <gateway>-apigee-governance-policy
readonly OUR_PSC_MATCH="agent-gateway-callout-psc" # agent-gateway-callout-psc-endpoint
while [[ $# -gt 0 ]]; do
case "$1" in
--project) PROJECT="$2"; shift 2 ;;
--region) REGION="$2"; shift 2 ;;
--gateway) GATEWAY="$2"; shift 2 ;;
--org) ORG="$2"; shift 2 ;;
--env) ENVNAME="$2"; shift 2 ;;
--envgroup) ENVGROUP="$2"; shift 2 ;;
--hostname) HOSTNAME_="$2"; shift 2 ;;
--proxy) PROXY="$2"; shift 2 ;;
--vpc) VPC="$2"; shift 2 ;;
--subnet) SUBNET="$2"; shift 2 ;;
--json) JSON=1; shift ;;
--help) usage; exit 0 ;;
*) echo "unknown argument: $1" >&2; usage >&2; exit 2 ;;
esac
done
[[ -n "$PROJECT" && -n "$REGION" && -n "$GATEWAY" ]] || { usage >&2; exit 2; }
ORG="${ORG:-$PROJECT}"
# Apply the skill's own documented defaults for anything not passed, and
# remember which ones were assumed.
#
# These sections used to be guarded on the flag being set, so a bare
# `--project --region --gateway` invocation silently skipped the entire Apigee
# half -- environment, envgroup, proxy, PSC and DNS -- and still printed a
# confident Setup Status Summary over the six checks that did run. Six
# categories reported "missing" that had never been looked at. Defaulting to
# the documented layout means the common invocation assesses the whole thing,
# and ASSUMED records what was inferred rather than supplied, so the output can
# say so instead of implying it was told.
ASSUMED=()
[[ -z "$ENVNAME" ]] && { ENVNAME="agent-gateway-govern"; ASSUMED+=("env=$ENVNAME"); }
[[ -z "$ENVGROUP" ]] && { ENVGROUP="agent-gateway-govern-group"; ASSUMED+=("envgroup=$ENVGROUP"); }
[[ -z "$PROXY" ]] && { PROXY="agent-gateway-governance"; ASSUMED+=("proxy=$PROXY"); }
[[ -z "$HOSTNAME_" ]] && { HOSTNAME_="agent-gateway-callout.internal.${PROJECT}.local"; ASSUMED+=("hostname=$HOSTNAME_"); }
PASS=0; FAILN=0; WARN=0; TODO=0; SKIPN=0
ROWS=()
# Colour. Disabled when stdout is not a tty, when NO_COLOR is set (no-color.org),
# or under --json, so piped and captured output stays plain text.
#
# The tty test here is on fd 1, and in the four ensure_*/deploy_* scripts it is
# on fd 2. That is deliberate, not drift: this script prints its tables to
# STDOUT (they are the product, and --json replaces them), while the others log
# progress to STDERR. Each tests the stream it actually writes to. Normalising
# the two would colour a piped run and leave an interactive one plain in
# whichever script got the wrong fd.
if [[ -t 1 && -z "${NO_COLOR:-}" && "${TERM:-dumb}" != "dumb" ]]; then
C_RST=$'\033[0m'; C_DIM=$'\033[2m'; C_BLD=$'\033[1m'
C_GRN=$'\033[32m'; C_RED=$'\033[31m'; C_YEL=$'\033[33m'; C_BLU=$'\033[36m'
else
C_RST=; C_DIM=; C_BLD=; C_GRN=; C_RED=; C_YEL=; C_BLU=
fi
# hdr <title> -- byte-identical to the helper in the four ensure_*/deploy_*
# scripts, so a header looks the same wherever it is printed. Writes to stdout
# here because this script's output IS stdout; the others write theirs to
# stderr. Rule fills to a fixed 92 columns in both.
hdr() { printf '\n%s┌─ %s %s%s\n' "$C_DIM" "$1" "$(printf '─%.0s' $(seq 1 $(( 92 > ${#1} ? 92 - ${#1} : 3 ))))" "$C_RST"; }
# paint <status> -> the status word, coloured and padded to 6.
paint() {
case "$1" in
PASS) printf '%s%-6s%s' "$C_GRN" "PASS" "$C_RST" ;;
FAIL) printf '%s%-6s%s' "$C_RED" "FAIL" "$C_RST" ;;
WARN) printf '%s%-6s%s' "$C_YEL" "WARN" "$C_RST" ;;
TODO) printf '%s%-6s%s' "$C_BLU" "TODO" "$C_RST" ;;
SKIP) printf '%s%-6s%s' "$C_DIM" "SKIP" "$C_RST" ;;
*) printf '%-6s' "$1" ;;
esac
}
# record <status> <resource> <detail>
#
# Four statuses, and the TODO/FAIL split is the load-bearing one. TODO means
# "this skill creates it and has not yet" -- absence is the expected state of a
# greenfield project, not a defect. FAIL means something is actually wrong:
# a user prerequisite missing, or a conflict no build step will resolve.
# Reporting a never-built setup as a wall of FAIL reads as breakage and is the
# single most misleading thing this script used to do.
record() {
local st="$1" res="$2" det="$3"
case "$st" in
PASS) PASS=$((PASS+1)) ;;
FAIL) FAILN=$((FAILN+1)) ;;
WARN) WARN=$((WARN+1)) ;;
TODO) TODO=$((TODO+1)) ;;
SKIP) SKIPN=$((SKIPN+1)) ;;
esac
ROWS+=("$st|$res|$det")
}
api() { # api <url> -> body on stdout, empty on failure
curl -s -H "Authorization: Bearer ${TOKEN}" "$1" 2>/dev/null || true
}
jqf() { # jqf <json> <python-expr over d> -- no jq dependency
python3 -c '
import json,sys
try: d=json.loads(sys.stdin.read() or "{}")
except Exception: d={}
try: print(eval(sys.argv[1]))
except Exception: print("")
' "$1" 2>/dev/null || true
}
# ---------------------------------------------------------------- toolchain --
GCV="$(gcloud version 2>/dev/null | sed -n 's/^Google Cloud SDK //p' | head -1)"
if [[ -z "$GCV" ]]; then
record FAIL "gcloud" "not on PATH"
else
MAJOR="${GCV%%.*}"
# 588.0.0 is where `apis import --from-template` reached the GA track. Below
# it the GA command rejects the flag with an error that reads like the
# command does not exist, and `gcloud beta` is the fallback. This check used
# to say 585, which disagreed with every other statement of the minimum in
# this skill and would have passed an SDK the build then failed on.
if (( MAJOR < 588 )); then
record WARN "gcloud" "$GCV -- below 588.0.0; 'apis import --from-template' is GA only from 588, use 'gcloud beta' or upgrade"
else
record PASS "gcloud" "$GCV"
fi
fi
TOKEN="$(gcloud auth application-default print-access-token 2>/dev/null || true)"
if [[ -z "$TOKEN" ]]; then
record FAIL "credentials" "no ADC token; run gcloud auth application-default login"
else
record PASS "credentials" "ADC token present"
fi
# ------------------------------------------------------------------ gateway --
GW="$(gcloud network-services agent-gateways describe "$GATEWAY" \
--location="$REGION" --project="$PROJECT" --format=json 2>/dev/null || true)"
if [[ -z "$GW" ]]; then
record FAIL "agentGateway/$GATEWAY" "not found in $REGION"
else
record PASS "agentGateway/$GATEWAY" "exists"
GAP="$(jqf 'd.get("googleManaged",{}).get("governedAccessPath","")' <<<"$GW")"
if [[ "$GAP" == "AGENT_TO_ANYWHERE" ]]; then
record PASS " governedAccessPath" "$GAP"
else
record WARN " governedAccessPath" "${GAP:-unset} -- egress governance expects AGENT_TO_ANYWHERE"
fi
NA="$(jqf 'd.get("networkConfig",{}).get("egress",{}).get("networkAttachment","")' <<<"$GW")"
if [[ -n "$NA" ]]; then
record PASS " egress.networkAttachment" "${NA##*/} (REUSE: a route into the VPC, not to a service)"
else
record TODO " egress.networkAttachment" "absent -- ensure_gateway_connectivity.sh attaches it; until then the callout has no route into the VPC"
fi
DOMS="$(jqf '",".join(d.get("networkConfig",{}).get("dnsPeeringConfig",{}).get("domains",[]))' <<<"$GW")"
if [[ -n "$DOMS" ]]; then
if [[ -n "$HOSTNAME_" && "$DOMS" != *"${HOSTNAME_#*.}"* ]]; then
record WARN " dnsPeeringConfig" "$DOMS -- does not cover ${HOSTNAME_#*.}; APPEND a second domain, peering is per-domain"
else
record PASS " dnsPeeringConfig" "$DOMS"
fi
else
record TODO " dnsPeeringConfig" "absent -- ensure_gateway_connectivity.sh appends the domain; until then the host does not resolve"
fi
SESA="$(jqf 'd.get("agentGatewayCard",{}).get("serviceExtensionsServiceAccount","")' <<<"$GW")"
[[ -n "$SESA" ]] && record PASS " serviceExtensionsSA" "$SESA"
fi
# --------------------------------------------------------- authz policies ----
POLS="$(gcloud beta network-security authz-policies list --location="$REGION" \
--project="$PROJECT" --format='value(name)' 2>/dev/null || true)"
OURS=""; OUR_SUF=""; OTHER_CONTENT=0
while read -r p; do
[[ -z "$p" ]] && continue
PD="$(gcloud beta network-security authz-policies describe "${p##*/}" \
--location="$REGION" --project="$PROJECT" --format=json 2>/dev/null || true)"
TGT="$(jqf '",".join(r for r in d.get("target",{}).get("resources",[]))' <<<"$PD")"
[[ "$TGT" != *"/agentGateways/$GATEWAY"* ]] && continue
PROF="$(jqf 'd.get("policyProfile","")' <<<"$PD")"
SUF="$(jqf '",".join(s.get("suffix","") for r in d.get("httpRules",[]) for o in r.get("to",{}).get("operations",[]) for s in o.get("paths",[]))' <<<"$PD")"
# Semantic match first: does this policy's extension front OUR hostname?
MINE=0
if [[ "${p##*/}" == *"$OUR_POLICY_MATCH"* ]]; then
MINE=1
elif [[ "$PROF" == "CONTENT_AUTHZ" && -n "$HOSTNAME_" ]]; then
EXTR="$(jqf '",".join(d.get("customProvider",{}).get("authzExtension",{}).get("resources",[]))' <<<"$PD")"
if [[ -n "$EXTR" ]]; then
EXTSVC="$(gcloud service-extensions authz-extensions describe "${EXTR##*/}" \
--location="$REGION" --project="$PROJECT" --format='value(service)' 2>/dev/null || true)"
[[ "$EXTSVC" == "$HOSTNAME_" ]] && MINE=1
fi
fi
if (( MINE )); then
OURS="${p##*/}"; OUR_SUF="$SUF"
record PASS "authzPolicy/${p##*/}" "$PROF suffixes=[${SUF}]"
elif [[ "$PROF" == "CONTENT_AUTHZ" ]]; then
OTHER_CONTENT=$((OTHER_CONTENT+1))
record WARN "authzPolicy/${p##*/}" "$PROF on the same gateway -- precedence between two CONTENT_AUTHZ policies is undefined; another governance extension on this gateway looks like this"
else
record PASS "authzPolicy/${p##*/}" "$PROF -- different phase, coexists cleanly"
fi
done <<<"$POLS"
[[ -z "$OURS" ]] && record TODO "authzPolicy" "none targets $GATEWAY yet -- created in the bind step, last of all"
# ------------------------------------------------------------------- Apigee --
if [[ -n "$ENVNAME" ]]; then
EJ="$(api "https://apigee.googleapis.com/v1/organizations/$ORG/environments/$ENVNAME")"
ENV_EXISTS=0
if [[ -z "$EJ" || "$EJ" == *'"error"'* ]]; then
record TODO "apigee/env/$ENVNAME" "not created yet -- ensure_apigee_environment.sh creates and attaches it (~4 min)"
else
ENV_EXISTS=1
record PASS "apigee/env/$ENVNAME" "exists"
# BASE rejects extensible proxies, and nothing earlier in the build says so:
# create, attach and the property PATCH all succeed, then only the deploy
# fails -- "Extensible proxy can not be deployed to a base environment." --
# and it fails after the ~4 min attachment. Checked here so the read-only
# pass can predict it.
ETYPE="$(jqf 'd.get("type","")' <<<"$EJ")"
if [[ "$ETYPE" == "BASE" ]]; then
record TODO " type" "BASE cannot host an extensible proxy -- the build PATCHes ?updateMask=type to COMPREHENSIVE before attaching"
elif [[ -n "$ETYPE" ]]; then
record PASS " type" "$ETYPE"
else
# Healthy orgs often omit `type` entirely -- absent is NOT BASE, and
# failing on it reports a broken setup as broken for the wrong reason.
# The deployment check below is the real signal.
record PASS " type" "not reported (only an explicit BASE blocks extensible proxies)"
fi
SEP="$(jqf 'next((p["value"] for p in d.get("properties",{}).get("property",[]) if p.get("name")=="apigee-service-extension-enabled"),"")' <<<"$EJ")"
if [[ "$SEP" == "true" ]]; then
record PASS " apigee-service-extension-enabled" "true"
else
record TODO " apigee-service-extension-enabled" "${SEP:-unset} -- the build sets it; without it the proxy deploys STANDARD and never sees agent traffic"
fi
fi
# An environment in more than one envgroup makes the gateway 404 every agent
# request with the extension never invoked, and nothing anywhere reports it.
#
# Only meaningful once the environment exists. Running it anyway reports an
# envgroup "in no envgroup" and then a hostname mismatch against a group that
# was never built -- one absent resource cascading into several confident
# failures, which is the noise this script exists to avoid.
if (( ENV_EXISTS == 0 )); then
record SKIP "apigee/envgroup" "not checked -- $ENVNAME does not exist yet; checked once it is created"
else
EGS="$(api "https://apigee.googleapis.com/v1/organizations/$ORG/envgroups")"
INGRP="$(python3 -c '
import json,sys,urllib.request,os
d=json.loads(sys.stdin.read() or "{}")
print(" ".join(g.get("name","") for g in d.get("environmentGroups",[])))' <<<"$EGS" 2>/dev/null || true)"
HOLDING=()
for g in $INGRP; do
AT="$(api "https://apigee.googleapis.com/v1/organizations/$ORG/envgroups/${g}/attachments")"
grep -q "\"$ENVNAME\"" <<<"$AT" && HOLDING+=("$g")
done
case "${#HOLDING[@]}" in
0) record TODO "apigee/envgroup" "$ENVNAME is in no envgroup yet -- the build creates one and attaches it" ;;
1) record PASS "apigee/envgroup" "${HOLDING[0]} (exactly one, which is required)" ;;
*) record FAIL "apigee/envgroup" "$ENVNAME is in ${#HOLDING[@]} envgroups (${HOLDING[*]}) -- the gateway 404s every request and reports nothing" ;;
esac
if [[ -n "$ENVGROUP" && -n "$HOSTNAME_" ]]; then
EG="$(api "https://apigee.googleapis.com/v1/organizations/$ORG/envgroups/$ENVGROUP")"
if [[ -z "$EG" || "$EG" == *'"error"'* ]]; then
# The group itself is not there yet. Reporting a hostname mismatch
# against a group that does not exist states a real problem for an
# unreal reason, and sends the reader to check DNS.
record TODO " envgroup hostname" "$ENVGROUP does not exist yet -- the build creates it carrying $HOSTNAME_"
elif grep -q "$HOSTNAME_" <<<"$EG"; then
record PASS " envgroup hostname" "$ENVGROUP carries $HOSTNAME_"
else
record FAIL " envgroup hostname" "$ENVGROUP does not carry $HOSTNAME_ -- a hostname mismatch no build step resolves; the three names must be identical"
fi
fi
fi
fi
# ------------------------------------------------------------------- VPC -----
if [[ -n "$VPC" ]]; then
if gcloud compute networks describe "$VPC" --project="$PROJECT" >/dev/null 2>&1; then
record PASS "vpc/$VPC" "exists (REUSE: shared with any other extension on this gateway)"
else
record FAIL "vpc/$VPC" "not found"
fi
fi
if [[ -n "$SUBNET" ]]; then
SN="$(gcloud compute networks subnets describe "$SUBNET" --region="$REGION" \
--project="$PROJECT" --format='value(ipCidrRange)' 2>/dev/null || true)"
if [[ -n "$SN" ]]; then
record PASS "subnet/$SUBNET" "$SN (REUSE: the PSC IP is drawn from here)"
else
record FAIL "subnet/$SUBNET" "not found in $REGION"
fi
fi
# The VPC and subnet are the user's own infrastructure and have no documented
# default to fall back on, so an absent flag genuinely means "not checked".
# Record that rather than omitting the row: a check that silently did not run
# is indistinguishable, in the output, from one that passed.
[[ -z "$VPC" ]] && record SKIP "vpc" "not checked -- pass --vpc to verify the gateway egresses into the network you expect"
[[ -z "$SUBNET" ]] && record SKIP "subnet" "not checked -- pass --subnet to verify the PSC IP is drawn from the right range"
if [[ -n "$ENVNAME" && -n "$PROXY" ]]; then
DEP="$(api "https://apigee.googleapis.com/v1/organizations/$ORG/environments/$ENVNAME/apis/$PROXY/deployments")"
REV="$(jqf 'd.get("deployments",[{}])[0].get("revision","")' <<<"$DEP")"
DT="$(jqf 'd.get("deployments",[{}])[0].get("proxyDeploymentType","")' <<<"$DEP")"
if [[ -z "$REV" ]]; then
record TODO "apigee/proxy/$PROXY" "not deployed yet -- deploy_proxy.sh builds and deploys it (~2 min)"
elif [[ "$DT" == "EXTENSIBLE" ]]; then
record PASS "apigee/proxy/$PROXY" "rev $REV, EXTENSIBLE"
else
record FAIL "apigee/proxy/$PROXY" "rev $REV, ${DT:-unknown} -- STANDARD deploys clean and governs nothing"
fi
# Which features are actually DEPLOYED, read off the revision's policy list
# rather than inferred from config. Drives the Enforcement rollup row: this
# skill meters without blocking, EXCEPT Model Armor, which is
# continueOnError=false and fails a turn closed.
if [[ -n "$REV" ]]; then
POLJ="$(api "https://apigee.googleapis.com/v1/organizations/$ORG/apis/$PROXY/revisions/$REV")"
[[ "$POLJ" == *modelarmor* ]] && HAS_ARMOR=1
[[ "$POLJ" == *LTQ-count* ]] && HAS_METER=1
[[ "$POLJ" == *semanticcache* ]] && HAS_CACHE=1
[[ "$POLJ" == *LTQ-enforce* ]] && HAS_ENFORCE=1
# Model Armor is the only policy that can refuse a request, so read its
# ACTUAL enforcement mode rather than trusting the config. continueOnError
# is not exposed on any JSON endpoint -- there is no per-policy resource --
# so pull the revision bundle. It is ~10 KB and about half a second.
if [[ "${HAS_ARMOR:-0}" == "1" ]]; then
BUNDLE="$(mktemp)"
if curl -fsS -H "Authorization: Bearer $TOKEN" -o "$BUNDLE" \
"https://apigee.googleapis.com/v1/organizations/$ORG/apis/$PROXY/revisions/$REV?format=bundle" 2>/dev/null; then
MA_COE="$(python3 - "$BUNDLE" <<'PY' 2>/dev/null || true
import sys,zipfile,re
try:
z=zipfile.ZipFile(sys.argv[1])
for n in z.namelist():
if "modelarmor" in n and n.endswith(".xml"):
m=re.search(r'continueOnError="(\w+)"', z.read(n).decode())
if m: print(m.group(1)); break
except Exception:
pass
PY
)"
fi
rm -f "$BUNDLE"
[[ "$MA_COE" == "true" ]] && MA_MODE="DRY_RUN" || MA_MODE="ENFORCE"
[[ -z "$MA_COE" ]] && MA_MODE="unknown"
fi
fi
fi
# ------------------------------------------------------------------ the PSC --
if [[ -n "$HOSTNAME_" ]]; then
# Matched on TARGET, not name: the one pointing at an Apigee instance
# service attachment is ours whatever it happens to be called. Falls back to
# the name hint for a half-built setup whose target is not resolvable yet.
FR="$(gcloud compute forwarding-rules list --project="$PROJECT" \
--filter="region:($REGION)" \
--format='value(name,IPAddress,pscConnectionStatus,target)' 2>/dev/null || true)"
PSCIP="$(awk '$4 ~ /serviceAttachments\/apigee-/ {print $2; exit}' <<<"$FR")"
PSCST="$(awk '$4 ~ /serviceAttachments\/apigee-/ {print $3; exit}' <<<"$FR")"
if [[ -z "$PSCIP" ]]; then
PSCIP="$(awk -v m="$OUR_PSC_MATCH" '$0 ~ m {print $2; exit}' <<<"$FR")"
PSCST="$(awk -v m="$OUR_PSC_MATCH" '$0 ~ m {print $3; exit}' <<<"$FR")"
fi
if [[ -z "$PSCIP" ]]; then
record TODO "psc/endpoint" "none yet in $REGION -- the build CREATEs one targeting the Apigee instance service attachment (never shared with another extension)"
elif [[ "$PSCST" == "ACCEPTED" ]]; then
record PASS "psc/endpoint" "$PSCIP ACCEPTED"
else
record FAIL "psc/endpoint" "$PSCIP ${PSCST:-PENDING} -- project is probably not on the instance consumerAcceptList"
fi
ZN="$(gcloud dns managed-zones list --project="$PROJECT" --format='value(name,dnsName)' 2>/dev/null || true)"
PARENT="${HOSTNAME_#*.}."
if grep -q "$PARENT" <<<"$ZN"; then
ZNAME="$(awk -v p="$PARENT" '$2==p {print $1; exit}' <<<"$ZN")"
record PASS "dns/zone" "${ZNAME:-found} covers $PARENT"
RS="$(gcloud dns record-sets list --zone="${ZNAME}" --project="$PROJECT" \
--filter="name=${HOSTNAME_}." --format='value(rrdatas[0])' 2>/dev/null || true)"
if [[ -z "$RS" ]]; then
record TODO "dns/record" "no A record for $HOSTNAME_ yet -- the build CREATEs it once the PSC IP exists"
elif [[ -n "$PSCIP" && "$RS" != "$PSCIP" ]]; then
record FAIL "dns/record" "$HOSTNAME_ -> $RS but the PSC endpoint is $PSCIP"
else
record PASS "dns/record" "$HOSTNAME_ -> $RS"
fi
else
record TODO "dns/zone" "no private zone covers $PARENT yet -- the build CREATEs one (an existing parent zone is reused instead)"
fi
fi
# --------------------------------------------------------- Vector Search ----
# Only reached when the deployed revision actually carries the cache policies,
# so this never probes Vertex AI for a setup that does not use it.
#
# The deployed index is the ONE resource in this skill that bills while idle.
# The provisioning script prints a COST block and modes.md requires explicit
# confirmation before creating it -- and then the health check said nothing
# about it at all, so an operator auditing an unfamiliar project got
# "SETUP OK, nothing outstanding" while a replica had been running for hours.
# Having taken the cost seriously at create time, reporting it afterwards is
# the other half of the same obligation.
CACHE_INDEX_ID=""; CACHE_EP_ID=""; CACHE_MACHINE=""; CACHE_REPLICAS=""
CACHE_DIMS=""; CACHE_METHOD=""; CACHE_SYNC=""; CACHE_DEPLOYED=""; CACHE_ELAPSED=""
if [[ "${HAS_CACHE:-0}" == "1" ]]; then
IDX_JSON="$(gcloud ai indexes list --project="$PROJECT" --region="$REGION" \
--format=json 2>/dev/null || echo '[]')"
CACHE_INDEX_ID="$(jqf 'next((i["name"].split("/")[-1] for i in d if "cache" in i.get("displayName","").lower()), "")' <<<"$IDX_JSON")"
if [[ -n "$CACHE_INDEX_ID" ]]; then
CACHE_DIMS="$(jqf 'next((str(i.get("metadata",{}).get("config",{}).get("dimensions","")) for i in d if i["name"].endswith("'"$CACHE_INDEX_ID"'")), "")' <<<"$IDX_JSON")"
CACHE_METHOD="$(jqf 'next((i.get("indexUpdateMethod","") for i in d if i["name"].endswith("'"$CACHE_INDEX_ID"'")), "")' <<<"$IDX_JSON")"
if [[ "$CACHE_METHOD" == "STREAM_UPDATE" ]]; then
record PASS "vectorsearch/index" "$CACHE_INDEX_ID dims=${CACHE_DIMS:-?} $CACHE_METHOD"
else
# Not cosmetic: SemanticCachePopulate writes via :upsertDatapoints, which
# a BATCH_UPDATE index does not expose. Populate fails silently forever.
record FAIL "vectorsearch/index" "$CACHE_INDEX_ID is ${CACHE_METHOD:-unknown}, not STREAM_UPDATE -- SemanticCachePopulate writes through :upsertDatapoints and can never succeed against it"
fi
else
record FAIL "vectorsearch/index" "cache policies are deployed but no index found in $REGION -- lookups cannot resolve; scripts/ensure_vector_search.sh builds it"
fi
EP_JSON="$(gcloud ai index-endpoints list --project="$PROJECT" --region="$REGION" \
--format=json 2>/dev/null || echo '[]')"
CACHE_EP_ID="$(jqf 'next((e["name"].split("/")[-1] for e in d if e.get("deployedIndexes")), "")' <<<"$EP_JSON")"
if [[ -n "$CACHE_EP_ID" ]]; then
CACHE_MACHINE="$(jqf 'next((di.get("dedicatedResources",{}).get("machineSpec",{}).get("machineType","") for e in d for di in e.get("deployedIndexes",[])), "")' <<<"$EP_JSON")"
CACHE_REPLICAS="$(jqf 'next((str(di.get("dedicatedResources",{}).get("minReplicaCount","")) for e in d for di in e.get("deployedIndexes",[])), "")' <<<"$EP_JSON")"
CACHE_SYNC="$(jqf 'next((di.get("indexSyncTime","") for e in d for di in e.get("deployedIndexes",[])), "")' <<<"$EP_JSON")"
CACHE_DEPLOYED="$(jqf 'next((di.get("createTime","") for e in d for di in e.get("deployedIndexes",[])), "")' <<<"$EP_JSON")"
# "Bills per node-hour" is a true statement nobody acts on. The number
# someone reviewing an idle demo environment actually wants is how long it
# has been running, and that is derivable from the deployedIndex
# createTime. No pricing table: the duration alone turns an abstract
# warning into something you can decide about, and a rate would go stale.
CACHE_ELAPSED=""
if [[ -n "$CACHE_DEPLOYED" ]]; then
_then="$(date -d "$CACHE_DEPLOYED" +%s 2>/dev/null || echo "")"
if [[ -n "$_then" ]]; then
_secs=$(( $(date +%s) - _then )); (( _secs < 0 )) && _secs=0
CACHE_ELAPSED=" deployed $(( _secs / 3600 ))h$(( (_secs % 3600) / 60 ))m ago -- ~$(awk -v s="$_secs" -v r="${CACHE_REPLICAS:-1}" 'BEGIN{printf "%.1f", (s/3600.0)*r}') node-hours accrued"
fi
fi
record WARN "vectorsearch/deployed" "${CACHE_MACHINE:-?} x${CACHE_REPLICAS:-?} -- BILLING per node-hour while deployed, with or without traffic${CACHE_ELAPSED}${CACHE_SYNC:+ (last sync $CACHE_SYNC)}; scripts/teardown_vector_search.sh stops it, in order"
else
record FAIL "vectorsearch/endpoint" "cache policies are deployed but no index endpoint carries a deployed index -- every lookup fails; scripts/ensure_vector_search.sh deploys one"
fi
fi
# ------------------------------------------------------------------ rollup --
# A category rollup above the per-check table. The table answers "which check
# failed"; this answers "what is this setup, and what does it do to traffic" --
# which is the question someone arriving cold actually has, and which 20 rows
# of PASS do not answer. Status carries a VALUE, not just a verdict, and each
# Details cell states the consequence rather than restating the value.
SUMROWS=()
sumrow() { SUMROWS+=("$1|$2|$3"); }
# Overall Health is computed LAST and PREPENDED -- see `rollup_overall_health`
# just before the output section. It is the first row the reader sees, but it
# summarises counters that rollup rows below are still incrementing, so
# building it here reads them too early and under-reports.
if [[ -z "${REV:-}" ]]; then
sumrow "Proxy" "NOT DEPLOYED" "nothing is governing traffic yet"
else
sumrow "Proxy" "${DT:-unknown} rev ${REV}" "${PROXY:-?} on ${ENVNAME:-?}$([[ "${ETYPE:-}" == "BASE" ]] && echo " -- env is BASE and cannot host this")"
fi
# Other governance products surface a row like this as Enforcement Mode. Ours
# is a different answer, and it should be stated rather than left to be
# inferred from a hardcoded CountOnly.
if [[ "${HAS_ARMOR:-0}" == "1" && "${MA_MODE:-}" == "DRY_RUN" ]]; then
sumrow "Enforcement" "METER + ARMOR:DRY_RUN" "nothing blocks -- Model Armor evaluates and logs, the fault is swallowed"
elif [[ "${HAS_ARMOR:-0}" == "1" && "${MA_MODE:-}" == "ENFORCE" ]]; then
sumrow "Enforcement" "METER + ARMOR:ENFORCE${HAS_ENFORCE:+ + QUOTA LIMIT}" "Model Armor DOES refuse a matching request (400)$([[ "${HAS_ENFORCE:-0}" == "1" ]] && echo "; token budget also enforced, one request late" || echo "; quotas count only")"
elif [[ "${HAS_ARMOR:-0}" == "1" ]]; then
sumrow "Enforcement" "METER + ARMOR:?" "Model Armor deployed; could not read continueOnError off rev ${REV:-?}"
elif [[ "${HAS_METER:-0}" == "1" && "${HAS_ENFORCE:-0}" == "1" ]]; then
sumrow "Enforcement" "METER + QUOTA LIMIT" "token budget IS enforced: an over-budget caller is refused on its NEXT request (enforcement is one request late)"
elif [[ "${HAS_METER:-0}" == "1" ]]; then
sumrow "Enforcement" "METER ONLY" "quotas are CountOnly -- no request is ever blocked by this proxy"
else
sumrow "Enforcement" "NONE DETECTED" "no metering policies on rev ${REV:-?}"
fi
# The only continuously-billing component gets its own row. Absent is a real
# answer here, not a gap -- "OFF" tells an auditor there is no standing spend.
if [[ "${HAS_CACHE:-0}" == "1" ]]; then
CACHECOST="${CACHE_MACHINE:-?} x${CACHE_REPLICAS:-?}"
sumrow "Caching" "ON ($CACHECOST)" "deployed index ${CACHE_INDEX_ID:-?} -- BILLING per node-hour while deployed, traffic or not"
else
sumrow "Caching" "OFF" "no semantic cache policies on rev ${REV:-?}; nothing here bills while idle"
fi
if [[ -n "${OUR_SUF:-}" ]]; then
NSUF="$(awk -F, '{print NF}' <<<"$OUR_SUF")"
CACHENOTE=""
if [[ "${HAS_CACHE:-0}" == "1" && "${NSUF:-1}" -gt 1 ]]; then
CACHENOTE=" -- KNOWN ISSUE: cache + >1 shape can serve the wrong model's answer"
# Also a row in its own right. modes.md requires this warning "at plan
# time and again in the summary", and assess is where someone inspecting
# a setup they did not build will look for it.
record WARN "semanticcache/shapes" "cache is ON with $NSUF governed shapes -- the cache key is the prompt embedding alone, carrying no model or wire-shape discriminator, so a cross-shape hit returns an EMPTY HTTP 200 that reads as the agent being broken. Treat hits as unverified while more than one model sits behind this proxy"
fi
sumrow "Governed Shapes" "$NSUF" "${OUR_SUF}${CACHENOTE}"
else
sumrow "Governed Shapes" "0" "no AuthzPolicy suffixes -- nothing reaches Apigee"
fi
if [[ "${PSCST:-}" == "ACCEPTED" && -n "${ZNAME:-}" ]]; then
sumrow "Callout Path" "Verified" "PSC ${PSCIP:-?} ACCEPTED, zone ${ZNAME} resolves ${HOSTNAME_:-?}"
else
sumrow "Callout Path" "Incomplete" "PSC=${PSCST:-missing}, dns zone=${ZNAME:-missing} -- the callout cannot land"
fi
if [[ -n "${OURS:-}" ]]; then
sumrow "AuthZ Wiring" "Verified" "${OURS}$( (( ${OTHER_CONTENT:-0} > 0 )) && echo " -- plus ${OTHER_CONTENT} other CONTENT_AUTHZ policy; precedence undefined")"
else
sumrow "AuthZ Wiring" "Missing" "no policy targets ${GATEWAY:-?}"
fi
# ------------------------------------------------- overall health (last) ----
# Deliberately the last thing computed and the first thing shown.
#
# Overall health reads TODO and FAIL as different kinds of news. A greenfield
# project is not a broken one: all TODO and no FAIL means there is nothing to
# repair, only things to build, and the headline has to say so or the whole
# run reads as breakage.
#
# It must read the SAME accumulators the footer tally prints. Computing it
# earlier -- where it used to live, above the rollup rows -- took a snapshot
# before `semanticcache/shapes` recorded its WARN, so a run with two warnings
# announced one. The dropped one was either the billing disclosure or the
# cache-correctness known issue, and modes.md tells the agent to lead with
# this row and treat it as the answer.
TALLY="$PASS PASS, $FAILN FAIL, $WARN WARN, $TODO TODO"
if (( FAILN > 0 && TODO > 0 )); then
OVERALL="NEEDS WORK"
DETAIL="$TALLY -- fix the $FAILN failure(s); the $TODO outstanding build steps are not faults"
elif (( FAILN > 0 )); then
OVERALL="NEEDS WORK"
DETAIL="$TALLY -- $FAILN genuine failure(s) to fix"
elif (( TODO > 0 && PASS <= 2 )); then
OVERALL="NOT BUILT"
DETAIL="$TALLY -- nothing built yet and nothing broken; a clean starting point"
elif (( TODO > 0 )); then
OVERALL="PARTIALLY BUILT"
DETAIL="$TALLY -- no failures; $TODO step(s) left to finish the build"
elif (( WARN > 0 )); then
OVERALL="OK, WITH NOTES"
DETAIL="$TALLY -- built and healthy; warnings are things to know, not to fix"
else
OVERALL="SETUP OK"
DETAIL="$TALLY -- built and healthy"
fi
SUMROWS=("Overall Health|$OVERALL|$DETAIL" "${SUMROWS[@]}")
# ------------------------------------------------------------------- output --
if (( JSON )); then
python3 -c '
import json,sys
blocks=sys.stdin.read().split("\x02")
summ=[l.split("|",2) for l in blocks[0].splitlines() if l]
rows=[l.split("|",2) for l in blocks[1].splitlines() if l]
print(json.dumps({
"summary":{"pass":int(sys.argv[1]),"fail":int(sys.argv[2]),"warn":int(sys.argv[3]),
"todo":int(sys.argv[4]),"overall":sys.argv[5],
"skip":int(sys.argv[6]),"assumed":[a for a in sys.argv[7].split() if a]},
"rollup":[{"category":c,"status":s,"detail":d} for c,s,d in summ],
"checks":[{"status":s,"resource":r,"detail":d} for s,r,d in rows]}, indent=2))
' "$PASS" "$FAILN" "$WARN" "$TODO" "$OVERALL" "$SKIPN" "${ASSUMED[*]:-}" <<<"$(printf '%s\n' "${SUMROWS[@]}")$(printf '\x02')$(printf '%s\n' "${ROWS[@]}")"
else
# Box-drawn so the two tables read as tables rather than as loose columns,
# and so the summary is visibly the headline rather than a preamble.
rule() { printf '%s%s%s\n' "$C_DIM" "$(printf '─%.0s' $(seq 1 "$1"))" "$C_RST"; }
case "$OVERALL" in
"SETUP OK"|"OK, WITH NOTES") OC="$C_GRN" ;;
"NEEDS WORK") OC="$C_RED" ;;
*) OC="$C_BLU" ;;
esac
hdr "Setup Status Summary"
printf '%s %-17s %-24s %s%s\n' "$C_BLD" "CATEGORY" "STATUS" "DETAILS" "$C_RST"
for r in "${SUMROWS[@]}"; do
cat_="${r%%|*}"; st="$(cut -d'|' -f2 <<<"$r")"; det="${r#*|*|}"
if [[ "$cat_" == "Overall Health" ]]; then
printf ' %-17s %s%-24s%s %s\n' "$cat_" "$OC$C_BLD" "$st" "$C_RST" "$det"
else
printf ' %-17s %-24s %s\n' "$cat_" "$st" "$det"
fi
done
rule 96
hdr "Checks"
printf '%s %-6s %-34s %s%s\n' "$C_BLD" "STATUS" "RESOURCE" "DETAIL" "$C_RST"
for r in "${ROWS[@]}"; do
printf ' %s %-34s %s\n' "$(paint "${r%%|*}")" "$(cut -d'|' -f2 <<<"$r")" "${r#*|*|}"
done
rule 96
printf '\n %s%d PASS%s %s%d FAIL%s %s%d WARN%s %s%d TODO%s %s%d SKIP%s\n' \
"$C_GRN" "$PASS" "$C_RST" "$C_RED" "$FAILN" "$C_RST" \
"$C_YEL" "$WARN" "$C_RST" "$C_BLU" "$TODO" "$C_RST" \
"$C_DIM" "$SKIPN" "$C_RST"
if (( ${#ASSUMED[@]} > 0 )); then
printf ' %sAssumed documented defaults for: %s%s\n' "$C_DIM" "${ASSUMED[*]}" "$C_RST"
printf ' %sPass the matching flags if this setup uses different names.%s\n' "$C_DIM" "$C_RST"
fi
# Every count above is useless on its own -- say what to do about it.
(( TODO > 0 )) && printf ' %sTODO%s is not a failure: the resource does not exist yet and this skill creates it.\n' "$C_BLU" "$C_RST"
(( FAILN > 0 )) && printf ' %sFAIL%s is something a build step will NOT resolve. Fix top-down: a gateway with no\n route into the VPC makes every later check meaningless.\n' "$C_RED" "$C_RST"
(( FAILN == 0 && WARN > 0 )) && printf ' %sWARN%s is a thing to know, not a thing to fix.\n' "$C_YEL" "$C_RST"
# Standing spend gets its own line. Folding it into "warnings are things to
# know, not to fix" is wrong: this one IS actionable, and it is the only
# thing in the skill that costs money while nothing is happening.
[[ "${HAS_CACHE:-0}" == "1" && -n "${CACHE_MACHINE:-}" ]] && printf \
' %sCOST%s the deployed index (%s x%s) bills per node-hour whether or not traffic flows.\n Undeploy it to stop the charge -- editing the YAML does not.\n' \
"$C_YEL" "$C_RST" "${CACHE_MACHINE}" "${CACHE_REPLICAS:-?}"
(( FAILN == 0 && TODO == 0 && WARN == 0 )) && printf ' Nothing outstanding.\n'
fi
# TODO alone is a clean exit: a greenfield project is a valid state, and
# callers gate "is anything broken" on this. Only real failures exit non-zero.
(( FAILN > 0 )) && exit 1
exit 0
compile_check.py 9.9 KB
#!/usr/bin/env python3
"""Compile an AFT template offline and assert the ext-proc invariants.
No Apigee org, no network, no deploy. Replicates exactly what
`gcloud apigee apis import --from-template` does locally: load the template,
load every feature it names from the same directory, compile with an EMPTY
caller-parameter map, and convert to a bundle.
python3 compile_check.py ../assets/apigee-proxy-template.yaml
Exits non-zero if an invariant fails. Checks:
1. the proxy is no-route -- a RouteRule with no TargetEndpoint
2. no targets are declared
3. at most one <PreFlow> and one <PostFlow> per endpoint
(AFT emits one element per Flow entry; two Flows both named PreFlow
produce two sibling <PreFlow> elements, which is not valid ProxyEndpoint
XML -- put response-phase steps in PostFlow/Response instead)
4. no unsubstituted {MACRO} survives into the bundle
"""
import io
import os
import re
import sys
import xml.etree.ElementTree as ET
import zipfile
try:
import yaml
except ModuleNotFoundError:
# The usual cause is running this with an interpreter that happens not to
# carry PyYAML, which is common and says nothing about the install being
# wrong. Name the interpreter in the message so the fix is unambiguous --
# a bare traceback sends people looking for a problem with the script.
sys.exit(
"error: PyYAML is not available to this interpreter.\n"
f" interpreter: {sys.executable}\n"
" Install it (pip install pyyaml) or re-run with a Python 3\n"
" that already has it. The gcloud SDK's bundled interpreter does\n"
" not, and the SDK's vendored 'yaml' is Python 2 -- do not use it."
)
# The AFT compiler ships inside the gcloud SDK rather than on PyPI, so import it
# from the SDK install. Set CLOUDSDK_ROOT_DIR to override the search.
_CANDIDATES = [
os.path.join(os.environ["CLOUDSDK_ROOT_DIR"], "lib")
if os.environ.get("CLOUDSDK_ROOT_DIR")
else "",
"/usr/lib/google-cloud-sdk/lib",
os.path.expanduser("~/google-cloud-sdk/lib"),
]
for _p in _CANDIDATES:
if _p and os.path.isdir(_p):
# third_party first: the SDK vendors its own deps (dateutil and friends)
# and importing googlecloudsdk without them fails.
sys.path.insert(0, os.path.join(_p, "third_party"))
sys.path.insert(0, _p)
break
else:
sys.exit(
"error: could not find the gcloud SDK's python libraries.\n Install"
" the Google Cloud SDK (>= 588.0.0), or set CLOUDSDK_ROOT_DIR\n to"
" its install directory."
)
from googlecloudsdk.command_lib.apigee.aft import compiler # noqa: E402
from googlecloudsdk.command_lib.apigee.aft import converter # noqa: E402
from googlecloudsdk.command_lib.apigee.aft import models # noqa: E402
# Apigee message templates also use {}, so only flag names that look like AFT
# parameters: SCREAMING_SNAKE_CASE with no dots.
_MACRO = re.compile(r"\{([A-Z][A-Z0-9_]*)\}")
# A value safe to drop into a sed pattern unescaped. Deliberately narrow:
# anything with a quote, space, paren or regex metacharacter gets prose.
_SIMPLE_SCALAR = re.compile(r"[A-Za-z0-9._-]+")
def compile_template(path):
root = os.path.dirname(os.path.abspath(path))
with open(path) as fh:
template = models.from_dict(models.Template, yaml.safe_load(fh))
features = []
for name in template.features:
with open(os.path.join(root, name)) as fh:
features.append(models.from_dict(models.Feature, yaml.safe_load(fh)))
return template, compiler.ApigeeCompiler().compile(template, features, {})
def parameter_drift(path, template):
"""Template-declared parameters are INERT for features. Report the drift.
`gcloud apigee apis import --from-template` invokes the compiler with an
EMPTY caller-parameter map, so every feature resolves its own declared
default and the template's declaration of the same name is never consulted.
Editing a default in the template therefore changes nothing, silently, and
the compile still succeeds -- the macro resolves, just to the other value.
This was hit for real: MA_CONTINUE_ON_ERROR was set to "true" (DRY_RUN) in
the template, the feature kept "false", and the bundle came out ENFORCE on
a fail-closed Model Armor policy. Nothing in the output said so.
Two findings, different severities:
MISMATCH -- a feature declares the same name with a DIFFERENT default.
The feature wins. This is the dangerous one: someone edited
the template expecting an effect and got none.
INERT -- no feature declares it at all, so the parameter does nothing
anywhere. Usually a leftover, occasionally a typo in a name.
"""
root = os.path.dirname(os.path.abspath(path))
tmpl_defaults = {
p.name: getattr(p, "default", None) for p in template.parameters
}
feature_defaults = {} # name -> {feature_file: default}
for fname in template.features:
with open(os.path.join(root, fname)) as fh:
feat = models.from_dict(models.Feature, yaml.safe_load(fh))
for fp in feat.parameters or []:
feature_defaults.setdefault(fp.name, {})[fname] = getattr(
fp, "default", None
)
mismatches, inert = [], []
for name, tdefault in tmpl_defaults.items():
holders = feature_defaults.get(name)
if not holders:
inert.append(name)
continue
differing = {f: d for f, d in holders.items() if d != tdefault}
if differing:
mismatches.append((name, tdefault, differing))
return mismatches, inert
def check(path):
template, proxy = compile_template(path)
failures = []
mismatches, inert = parameter_drift(path, template)
root = os.path.dirname(os.path.abspath(path))
for name, tdefault, differing in mismatches:
where = "; ".join(f"{f} has {d!r}" for f, d in sorted(differing.items()))
# Print the exact remedy, not just the diagnosis. Reconciling one
# number across a template and two features is the most common edit
# this check blocks, and leaving the operator to work out which file
# and which direction is where the drift gets re-introduced -- the
# feature value is the one that compiles, so the template is almost
# always the side that moves.
#
# The pattern tolerates optional quotes because YAML scalars are
# written `default: "10000"` here while the parsed value is bare, and
# a sed that matches neither silently succeeds -- worse than printing
# nothing. Values carrying regex or quote characters (LLM_URI_MATCH)
# get prose instead of a command that might corrupt the file.
def _remedy(fname, cur):
target = os.path.join(root, fname)
if _SIMPLE_SCALAR.fullmatch(str(cur)) and _SIMPLE_SCALAR.fullmatch(
str(tdefault)
):
return (
f' sed -i -E "s|(^[[:space:]]*default: )[\\"\']?{cur}[\\"\']?'
f'[[:space:]]*$|\\1\\"{tdefault}\\"|" {target}'
)
return (
f" edit {target}: set {name} default to {tdefault!r} (value"
" needs quoting care)"
)
fixes = "\n".join(_remedy(f, d) for f, d in sorted(differing.items()))
failures.append(
f"parameter {name}: the template declares {tdefault!r} but {where}. "
"The FEATURE value is what compiles -- the template's is inert, "
"because gcloud passes an empty caller-parameter map.\n"
f" To make the features match the template:\n{fixes}\n"
" To keep the feature value instead, change the template's "
f"declaration of {name} to {sorted(differing.values())[0]!r}."
)
if proxy.targets:
failures.append(
f"expected no targets, got {[t.name for t in proxy.targets]}"
)
for ep in proxy.endpoints:
routed = [r.name for r in ep.routes if r.target is not None]
if routed:
failures.append(f"endpoint {ep.name}: routes with a target: {routed}")
if not ep.routes:
failures.append(f"endpoint {ep.name}: no RouteRule at all")
for tag in ("PreFlow", "PostFlow"):
n = sum(1 for f in ep.flows if f.name == tag)
if n > 1:
failures.append(
f"endpoint {ep.name}: {n} flows named {tag}; the converter "
f"emits one <{tag}> element each, which is invalid. Move "
"response-phase steps to PostFlow/Response."
)
bundle = converter.proxy_to_bundle(proxy)
zf = zipfile.ZipFile(io.BytesIO(bundle))
declared = {p.name for p in template.parameters}
for entry in zf.namelist():
if not entry.endswith((".xml", ".js", ".properties")):
continue
for macro in set(_MACRO.findall(zf.read(entry).decode("utf-8", "replace"))):
if macro in declared:
failures.append(
f"{entry}: {{{macro}}} was not substituted. Template "
"parameters are replaced in FEATURE content only -- the "
"template's own fields are copied verbatim."
)
# Structural parse of the emitted ProxyEndpoint.
for entry in zf.namelist():
if "/proxies/" in entry:
el = ET.fromstring(zf.read(entry))
for tag in ("PreFlow", "PostFlow"):
if len(el.findall(tag)) > 1:
failures.append(f"{entry}: multiple <{tag}> elements")
for rule in el.findall("RouteRule"):
if rule.find("TargetEndpoint") is not None:
failures.append(f"{entry}: RouteRule has a TargetEndpoint")
print(f"template : {template.name}")
print(f"policies : {len(proxy.policies)} resources: {len(proxy.resources)}")
print(f"bundle : {len(zf.namelist())} entries")
if inert:
print(
"WARNING : template parameters no feature reads, so they do nothing: "
+ ", ".join(sorted(inert))
)
for ep in proxy.endpoints:
for f in ep.flows:
print(f" {f.name}/{f.mode}: {[s.name for s in f.steps]}")
if failures:
print("\nFAIL")
for f in failures:
print(f" - {f}")
return 1
print(
"\nOK: no-route, no targets, single PreFlow/PostFlow, all macros resolved"
)
return 0
if __name__ == "__main__":
if len(sys.argv) != 2:
print(__doc__)
sys.exit(2)
sys.exit(check(sys.argv[1]))
deploy_proxy.sh 23.7 KB
#!/bin/bash
# Enable a service-extension environment, build the ext-proc proxy from the AFT
# template, deploy it, and confirm it came up EXTENSIBLE.
#
# This sequence is deterministic and order-dependent, and three of its steps
# fail in ways that look like something else:
# - the environment PATCH replaces the whole properties map
# - the PATCH is asynchronous, so an immediate readback looks like a failure
# - the environment is locked while an instance attachment is running
# Encapsulated here so those are handled once rather than re-learned.
#
# Data goes to stdout as JSON. Diagnostics go to stderr.
set -euo pipefail
usage() {
cat <<'EOF'
Deploy the Apigee Agent Gateway ext-proc proxy.
Usage:
deploy_proxy.sh --org ORG --env ENV --proxy PROXY --template PATH [options]
Required:
--org ORG Apigee organization
--env ENV environment that will host the proxy
--proxy PROXY proxy name to create or revise
--template PATH AFT template; feature files must sit beside it
Options:
--service-account SA deployment SA; required if any policy calls a Google
API (Model Armor, embeddings, Vector Search), else the
deploy is rejected with MISSING_SERVICE_ACCOUNT
--skip-property environment property is already set; skip that step
--yes apply. Without it, prints the plan and exits 0.
--dry-run explicit form of the default; prints and changes nothing
--help this text
Semantic cache (only if the semanticCache feature is enabled):
--index-endpoint-id ID Vector Search index endpoint. Its public domain is
read back and substituted into the findNeighbors URL;
the domain cannot be derived from any id you hold, and
the input file has no field for it.
--index-id ID Vector Search index, for the upsertDatapoints URL
--embeddings-model M with --index-id, refuses to deploy when the index
width does not match the model's native output width.
A mismatch is only fixable by rebuilding the index.
--sc-project P project holding the index endpoint
--sc-region R region holding the index endpoint
scripts/ensure_vector_search.sh creates all of these
and prints the ids as JSON.
Environment:
CLOUDSDK_AUTH_ACCESS_TOKEN set automatically from ADC if unset. Needed
because under context-aware access the default
gcloud credential is rejected with a message
that names the resource, not the credential.
Exit codes: 0 ok, 1 usage, 2 precondition failed, 3 deploy not EXTENSIBLE
EOF
}
log() { echo "[$(date +%H:%M:%S)] $*" >&2; }
# ---------------------------------------------------------------- display ----
# Same palette as assess_integration.sh so the whole skill looks like one tool.
# The tty test is on fd 2, NOT fd 1: every log line here goes to stderr, so
# testing stdout would colour a piped run and leave an interactive one plain --
# exactly backwards. Honours NO_COLOR (no-color.org) and a dumb terminal.
if [[ -t 2 && -z "${NO_COLOR:-}" && "${TERM:-dumb}" != "dumb" ]]; then
C_RST=$'\033[0m'; C_DIM=$'\033[2m'; C_BLD=$'\033[1m'
C_GRN=$'\033[32m'; C_RED=$'\033[31m'; C_YEL=$'\033[33m'; C_BLU=$'\033[36m'
else
C_RST=; C_DIM=; C_BLD=; C_GRN=; C_RED=; C_YEL=; C_BLU=
fi
# hdr <title> section banner
# row <verb> <text> a planned change; CREATE/RESERVE cyan, MODIFY yellow
# cost <line>... standing-spend callout, always yellow
hdr() { printf '%s\n%s┌─ %s %s%s\n' "" "$C_DIM" "$1" "$(printf '─%.0s' $(seq 1 $(( 92 > ${#1} ? 92 - ${#1} : 3 ))))" "$C_RST" >&2; }
row() { local c="$C_BLU"; case "$1" in MODIFY|PATCH|APPEND) c="$C_YEL";; REUSE) c="$C_GRN";; esac
printf ' %s%-8s%s %s\n' "$c" "$1" "$C_RST" "$2" >&2; }
cost() { printf ' %s%s%s\n' "$C_YEL" "$*" "$C_RST" >&2; }
die() { echo "error: $1" >&2; exit "${2:-1}"; }
# Applies nothing without --yes, matching ensure_*/teardown_*. This script
# patches the environment, imports the proxy and deploys a revision, any of
# which can affect live traffic, so the default is plan-only.
ORG=""; ENV=""; PROXY=""; TEMPLATE=""; SA=""; SKIP_PROPERTY=0; DRY_RUN=1; BASE_PATH="/"
INDEX_ENDPOINT_ID=""; INDEX_ID=""; SC_PROJECT=""; SC_REGION=""; EMBEDDINGS_MODEL=""
while [[ $# -gt 0 ]]; do
case "$1" in
--org) ORG="$2"; shift 2 ;;
--env) ENV="$2"; shift 2 ;;
--proxy) PROXY="$2"; shift 2 ;;
--template) TEMPLATE="$2"; shift 2 ;;
--service-account) SA="$2"; shift 2 ;;
--index-endpoint-id) INDEX_ENDPOINT_ID="$2"; shift 2 ;;
--index-id) INDEX_ID="$2"; shift 2 ;;
--embeddings-model) EMBEDDINGS_MODEL="$2"; shift 2 ;;
--sc-project) SC_PROJECT="$2"; shift 2 ;;
--sc-region) SC_REGION="$2"; shift 2 ;;
--skip-property) SKIP_PROPERTY=1; shift ;;
--yes) DRY_RUN=0; shift ;;
--dry-run) DRY_RUN=1; shift ;;
--help|-h) usage; exit 0 ;;
*) usage >&2; die "unknown argument: $1" ;;
esac
done
[[ -n "$ORG" && -n "$ENV" && -n "$PROXY" && -n "$TEMPLATE" ]] \
|| { usage >&2; die "missing required argument"; }
[[ -f "$TEMPLATE" ]] || die "template not found: $TEMPLATE"
if [[ -n "$INDEX_ENDPOINT_ID" ]]; then
[[ -n "$SC_PROJECT" && -n "$SC_REGION" ]] \
|| { usage >&2; die "--index-endpoint-id also needs --sc-project and --sc-region (the Vector Search endpoint's own project/region)" 1; }
fi
# Echoes the command in dry-run. Redacts the bearer token: printing it would
# put a live credential into whatever captures stderr.
run() {
if [[ $DRY_RUN -eq 1 ]]; then
local shown=()
for a in "$@"; do
case "$a" in
"Authorization: Bearer "*) shown+=("Authorization: Bearer [REDACTED]") ;;
*) shown+=("$a") ;;
esac
done
printf ' %sDRY-RUN%s %s\n' "$C_BLU" "$C_RST" "${shown[*]}" >&2
return 0
fi
"$@"
}
: "${CLOUDSDK_AUTH_ACCESS_TOKEN:=$(gcloud auth application-default print-access-token 2>/dev/null)}"
export CLOUDSDK_AUTH_ACCESS_TOKEN
[[ -n "$CLOUDSDK_AUTH_ACCESS_TOKEN" ]] || die "could not obtain an ADC token; run 'gcloud auth application-default login'" 2
API="https://apigee.googleapis.com/v1/organizations/$ORG"
auth=(-H "Authorization: Bearer $CLOUDSDK_AUTH_ACCESS_TOKEN")
# 0. Envgroup-count precondition. A service-extension environment must be
# attached to exactly ONE envgroup. In two or more, the gateway 404s every agent
# request with the extension never invoked -- no Apigee error, no debug session,
# no Cloud Monitoring entry. Every other check in this script passes and the
# proxy deploys clean as EXTENSIBLE, so nothing downstream catches it.
#
# This is independent of the base-path check below: an environment can be in two
# envgroups and still have "/" free. Checked first because it is cheap,
# deterministic, and the alternative is bisecting against a known-good setup.
log "counting envgroups attached to $ENV"
envgroup_report=$(
curl -sf "${auth[@]}" "$API/envgroups" 2>/dev/null \
| python3 -c '
import json, sys
try:
groups = [g["name"] for g in json.load(sys.stdin).get("environmentGroups", [])]
except Exception:
groups = []
print("\n".join(groups))
' 2>/dev/null \
| while read -r g; do
[[ -z "$g" ]] && continue
if curl -sf "${auth[@]}" "$API/envgroups/${g}/attachments" 2>/dev/null \
| python3 -c "
import json, sys
try:
atts = json.load(sys.stdin).get('environmentGroupAttachments', [])
except Exception:
sys.exit(1)
sys.exit(0 if any(a.get('environment') == '$ENV' for a in atts) else 1)
"; then printf '%s ' "$g"; fi
done
) || true
envgroup_report="${envgroup_report% }"
envgroup_count=$(wc -w <<<"$envgroup_report")
if [[ "$envgroup_count" -eq 1 ]]; then
log " $ENV is in exactly one envgroup ($envgroup_report)"
elif [[ "$envgroup_count" -eq 0 ]]; then
log " $ENV is in no envgroup yet -- it must end up in exactly one"
else
die "environment '$ENV' is attached to $envgroup_count envgroups ($envgroup_report). A service-extension environment must be in exactly one, or the gateway returns 404 for every agent request with the extension never invoked and no error reported anywhere. Use a dedicated environment. See references/gotchas.md." 2
fi
# 1. Environment property, preserving every property already set.
if [[ $SKIP_PROPERTY -eq 0 ]]; then
log "reading existing properties on $ENV"
existing=$(curl -sf "${auth[@]}" "$API/environments/$ENV") \
|| die "cannot read environment $ENV; check the org and your access" 2
merged=$(echo "$existing" | python3 -c '
import json, sys
env = json.load(sys.stdin)
props = env.get("properties", {}).get("property", [])
props = [p for p in props if p.get("name") != "apigee-service-extension-enabled"]
props.append({"name": "apigee-service-extension-enabled", "value": "true"})
print(json.dumps({"properties": {"property": props}}))')
log "setting apigee-service-extension-enabled=true (async; will poll)"
if [[ $DRY_RUN -eq 0 ]]; then
resp=$(curl -sf -X PATCH "${auth[@]}" -H 'Content-Type: application/json' \
"$API/environments/$ENV?updateMask=properties" -d "$merged") \
|| die "property PATCH failed. If it reported FAILED_PRECONDITION with a lock, an instance attachment is still running -- wait for it and retry" 2
op=$(echo "$resp" | python3 -c 'import json,sys; print(json.load(sys.stdin).get("name",""))')
if [[ -n "$op" ]]; then
# Both failure modes here surface LATER as "proxy is not EXTENSIBLE"
# (exit 3), which sends you to the proxy and the template -- neither of
# which is the cause. Report them where they happen instead:
# 1. the operation never finished inside the window
# 2. the operation finished and FAILED
op_done=0; op_err=""
for _ in $(seq 1 60); do
opjson=$(curl -sf "${auth[@]}" "https://apigee.googleapis.com/v1/$op" || true)
read -r done_ op_err <<<"$(printf '%s' "$opjson" | python3 -c '
import json, sys
try:
d = json.load(sys.stdin)
except Exception:
print("False", ""); raise SystemExit
err = d.get("error") or {}
print(d.get("done", False), (err.get("message") or "").replace("\n", " "))')"
if [[ "$done_" == "True" ]]; then op_done=1; break; fi
sleep 5
done
[[ -n "$op_err" ]] && die "setting apigee-service-extension-enabled failed: $op_err" 2
(( op_done )) || die "the property operation did not finish within 5 minutes ($op). The environment property is what makes an extensible proxy deployable, so do not continue -- re-run once it completes." 2
log "property operation complete"
fi
else
printf ' %sDRY-RUN%s PATCH %s/environments/%s?updateMask=properties\n' \
"$C_BLU" "$C_RST" "$API" "$ENV" >&2
fi
fi
# 1a. Semantic cache: index width must match the embeddings model.
#
# The SemanticCacheLookup policy takes only a URL, so the model's native output
# width is what lands in the index, and index width is fixed at creation. A
# mismatch is not a config error you can correct -- the remedy is a full index
# rebuild, and the deploy step alone runs about 34 minutes. Checked here so it
# fails in seconds rather than at runtime against a live agent.
if [[ -n "$INDEX_ID" && -n "$EMBEDDINGS_MODEL" ]]; then
case "$EMBEDDINGS_MODEL" in
gemini-embedding-001) want_dims=3072 ;;
text-embedding-005) want_dims=768 ;;
text-multilingual-embedding-002) want_dims=768 ;;
text-embedding-004) want_dims=768 ;;
*) die "unknown --embeddings-model '$EMBEDDINGS_MODEL'; extend the width table in this script and in scripts/ensure_vector_search.sh after measuring the model's output width" 2 ;;
esac
log "checking index $INDEX_ID is ${want_dims}-dimensional for $EMBEDDINGS_MODEL"
have_dims="$(gcloud ai indexes describe "$INDEX_ID" \
--region="$SC_REGION" --project="$SC_PROJECT" \
--format='value(metadata.config.dimensions)' 2>/dev/null || true)"
[[ -n "$have_dims" ]] \
|| die "cannot read dimensions for index $INDEX_ID in $SC_PROJECT/$SC_REGION; check --index-id, --sc-project and --sc-region" 2
[[ "$have_dims" == "$want_dims" ]] \
|| die "index $INDEX_ID is ${have_dims}-dimensional but --embeddings-model $EMBEDDINGS_MODEL emits $want_dims. Dimensions are fixed at index creation and the policy cannot truncate, so this cannot be reconciled in config -- pick a ${have_dims}-dimensional model, or build a new index (scripts/ensure_vector_search.sh)." 2
log " dimensions match ($have_dims)"
fi
# 1a-bis. The REVERSE of the leftover-placeholder check further down.
#
# That one catches a placeholder that survived substitution. This one catches
# a placeholder that was never there -- i.e. someone pasted concrete ids into
# the shipped feature file instead of passing the flags. That deploys
# correctly, so nothing else notices, but it bakes one deployment's ids into a
# file meant to be reusable and skips the substitution check rather than
# exercising it. A warning, not a refusal: a deliberate fork is legitimate,
# and failing a working deploy over file hygiene would be worse than the
# problem.
SRC_CACHE="$(dirname "$TEMPLATE")/feature-semantic-cache.yaml"
if [[ -e "$SRC_CACHE" ]]; then
SUBSTITUTED=""
for tok in INDEX_ENDPOINT_DOMAIN INDEX_ENDPOINT_ID INDEX_ID; do
grep -q "\b$tok\b" "$SRC_CACHE" || SUBSTITUTED="$SUBSTITUTED $tok"
done
if [[ -n "$SUBSTITUTED" ]]; then
log "!! WARNING: feature-semantic-cache.yaml has no$SUBSTITUTED placeholder."
log "!! It looks hand-substituted. Concrete ids in a shipped asset"
log "!! are not reusable across deployments, and the"
log "!! leftover-placeholder check below cannot verify what it"
log "!! cannot see. Prefer: git checkout the feature file and pass"
log "!! --index-endpoint-id / --index-id / --sc-project / --sc-region."
fi
fi
# 1b. Semantic cache: resolve the index endpoint domain and substitute it.
#
# The findNeighbors host is the index endpoint's OWN domain, and its leading
# label is assigned at endpoint-creation time -- it matches neither the index
# id, the endpoint id, nor the project number, so it cannot be derived and the
# input file has no field for it. It has to be read back. Without this, a user
# who filled in every documented field still cannot compile a working cache.
if [[ -n "$INDEX_ENDPOINT_ID" ]]; then
log "resolving index endpoint domain for $INDEX_ENDPOINT_ID"
ENDPOINT_DOMAIN="$(gcloud ai index-endpoints describe "$INDEX_ENDPOINT_ID" \
--region="$SC_REGION" --project="$SC_PROJECT" \
--format='value(publicEndpointDomainName)' 2>/dev/null || true)"
[[ -n "$ENDPOINT_DOMAIN" ]] \
|| die "index endpoint $INDEX_ENDPOINT_ID reports no publicEndpointDomainName. It must be created with --public-endpoint-enabled and have an index deployed; scripts/ensure_vector_search.sh does both." 2
log " $ENDPOINT_DOMAIN"
# Work on a copy: substituting in place would edit the shipped assets.
SUBST_DIR="$(mktemp -d)"; trap 'rm -rf "$SUBST_DIR"' EXIT
cp "$(dirname "$TEMPLATE")"/*.yaml "$SUBST_DIR"/ 2>/dev/null || true
TEMPLATE="$SUBST_DIR/$(basename "$TEMPLATE")"
# WORD BOUNDARIES ARE LOAD-BEARING. DEPLOYED_INDEX_ID *contains* INDEX_ID, so
# a plain s/INDEX_ID/.../g rewrites the parameter's own name:
# - name: DEPLOYED_INDEX_ID -> - name: DEPLOYED_3873425533026959360
# and rewrites its reference to match, so the bundle still compiles and still
# works -- the breakage only surfaces later, when the template tries to
# supply a DEPLOYED_INDEX_ID that no longer exists. Same shape for
# INDEX_ENDPOINT_ID against INDEX_ENDPOINT_DOMAIN.
for f in "$SUBST_DIR"/*.yaml; do
[[ -e "$f" ]] || continue
# Longest first as a second line of defence; \b is what actually does it.
sed -i \
-e "s|\bINDEX_ENDPOINT_DOMAIN\b|$ENDPOINT_DOMAIN|g" \
-e "s|\bINDEX_ENDPOINT_ID\b|$INDEX_ENDPOINT_ID|g" \
${INDEX_ID:+-e "s|\bINDEX_ID\b|$INDEX_ID|g"} \
-e "s|\bPROJECT\b|$SC_PROJECT|g" \
-e "s|\bREGION\b|$SC_REGION|g" \
"$f"
done
# Assert nothing survived. A leftover placeholder compiles fine and fails at
# runtime against a hostname that does not resolve.
if leftovers=$(grep -l -E '\b(INDEX_ENDPOINT_DOMAIN|INDEX_ENDPOINT_ID|INDEX_ID)\b' "$SUBST_DIR"/*.yaml 2>/dev/null); then
log "placeholders survived substitution in:"; printf '%s\n' "$leftovers" >&2
die "substitution incomplete -- refusing to import a half-substituted bundle" 2
fi
# And that the trap did not fire: the parameter must still be named.
if grep -q 'DEPLOYED_INDEX_ID' "$SUBST_DIR"/feature-semantic-cache.yaml 2>/dev/null; then
log " DEPLOYED_INDEX_ID intact; substitution did not corrupt it"
elif [[ -e "$SUBST_DIR/feature-semantic-cache.yaml" ]]; then
die "substitution corrupted the DEPLOYED_INDEX_ID parameter name -- this is the INDEX_ID substring trap. Do not import this bundle." 2
fi
fi
# 1c. Model Armor's template name has its own placeholders, and they are NOT
# covered by the semantic-cache substitution above -- that whole block only
# runs when --index-endpoint-id is passed. Model Armor needs no flag on this
# script, so an unsubstituted MA_TEMPLATE_NAME would otherwise import and
# deploy clean and then fail every matching request at runtime, which is the
# worst failure shape this skill has: fail-closed, on live traffic, with
# nothing wrong at deploy time.
#
# Checked against the bundle actually being imported, whatever produced it.
# The anchored pattern matters: the shipped template lists the optional
# features as COMMENTED examples, so a plain substring match fires on the
# default bundle and blocks a deploy that has no Model Armor in it at all.
# Match an actual list entry only.
MA_FILE="$(dirname "$TEMPLATE")/feature-model-armor.yaml"
if [[ -e "$MA_FILE" ]] && grep -qE '^[[:space:]]*-[[:space:]]*feature-model-armor\.yaml' "$TEMPLATE"; then
if ma_left=$(grep -nE '\b(MA_TEMPLATE|PROJECT|REGION)\b' "$MA_FILE"); then
log "Model Armor is enabled but its template name still carries placeholders:"
printf '%s\n' "$ma_left" >&2
log " substitute projects/PROJECT/locations/REGION/templates/MA_TEMPLATE"
log " with your real Model Armor template, or drop feature-model-armor.yaml"
log " from the template's features list."
die "refusing to deploy Model Armor with an unresolved template name" 2
fi
log " Model Armor template name substituted"
fi
# 2. Build from the template. GA carries --from-template as of gcloud 588.0.0.
log "importing $PROXY from $TEMPLATE"
if [[ $DRY_RUN -eq 1 ]]; then
printf ' %sDRY-RUN%s gcloud apigee apis import organizations/%s/apis/%s --from-template=%s\n' \
"$C_BLU" "$C_RST" "$ORG" "$PROXY" "$TEMPLATE" >&2
REV="DRY-RUN"
else
out=$(gcloud apigee apis import "organizations/$ORG/apis/$PROXY" \
--from-template="$TEMPLATE" 2>&1) \
|| die "import failed. Needs gcloud >= 588.0.0 for --from-template on GA. Output: $out" 2
REV=$(echo "$out" | sed -n "s/^revision: '\{0,1\}\([0-9]*\)'\{0,1\}/\1/p" | tail -1)
[[ -n "$REV" ]] || die "import succeeded but no revision was returned: $out" 2
log "imported revision $REV"
fi
# 2b. Base-path conflict pre-check. Apigee allows one proxy per base path per
# environment, and the failure arrives only at deploy time -- after the import
# has already left an undeployed revision behind. Enumerate first and name the
# offender.
if [[ $DRY_RUN -eq 0 ]]; then
log "checking base paths already taken in $ENV"
conflict="$(curl -s "${auth[@]}" "$API/environments/$ENV/deployments" 2>/dev/null | python3 -c "
import json, sys, urllib.request, os
want = '$BASE_PATH'
proxy = '$PROXY'
try:
deps = json.load(sys.stdin).get('deployments', [])
except Exception:
sys.exit(0)
tok = os.environ['CLOUDSDK_AUTH_ACCESS_TOKEN']
api = '$API'
for d in deps:
name, rev = d.get('apiProxy'), d.get('revision')
if name == proxy:
continue
req = urllib.request.Request(f'{api}/apis/{name}/revisions/{rev}',
headers={'Authorization': f'Bearer {tok}'})
try:
body = json.load(urllib.request.urlopen(req, timeout=15))
except Exception:
continue
for bp in body.get('basepaths', []):
if bp == want:
print(f'{name} revision {rev}')
sys.exit(0)
" 2>/dev/null || true)"
if [[ -n "$conflict" ]]; then
die "base path '$BASE_PATH' in environment '$ENV' is already taken by $conflict. '$ENV' is carrying other traffic, so it is not the dedicated environment this proxy needs -- a shared environment also causes the 404-with-no-error failure described in references/gotchas.md. Move this proxy to a dedicated environment rather than freeing the path." 2
fi
log " base path $BASE_PATH is free"
fi
# 3. Deploy.
deploy_url="$API/environments/$ENV/apis/$PROXY/revisions/$REV/deployments?override=true"
[[ -n "$SA" ]] && deploy_url="$deploy_url&serviceAccount=$SA"
log "deploying revision $REV"
if [[ $DRY_RUN -eq 0 ]]; then
# No -f: -f discards the body, and the body is where the real cause lives.
# A CONFLICTING_DEPLOYMENT was once reported as a service-account problem
# purely because the response was thrown away.
deploy_body="$(curl -s -w '\n%{http_code}' -X POST "${auth[@]}" "$deploy_url")"
deploy_code="${deploy_body##*$'\n'}"; deploy_body="${deploy_body%$'\n'*}"
if [[ "$deploy_code" != 2* ]]; then
log "deploy failed (HTTP $deploy_code). Apigee said:"
printf '%s\n' "$deploy_body" >&2
case "$deploy_body" in
*CONFLICTING_DEPLOYMENT*)
die "another proxy already occupies this base path in $ENV, so $ENV is not a dedicated environment; move this proxy to one of its own" 2 ;;
*MISSING_SERVICE_ACCOUNT*)
die "pass --service-account: a policy in this proxy calls a Google API" 2 ;;
*) die "deploy failed" 2 ;;
esac
fi
else
run curl -s -X POST "${auth[@]}" "$deploy_url" >/dev/null
fi
# 4. Confirm EXTENSIBLE. STANDARD means it will not see off-Apigee egress.
if [[ $DRY_RUN -eq 1 ]]; then
printf ' %sNot applying.%s Re-run with %s--yes%s to make these changes.\n' \
"$C_BLD" "$C_RST" "$C_BLD" "$C_RST" >&2
echo '{"dryRun": true, "changed": false, "reason": "dry run, --yes not given"}'
exit 0
fi
log "waiting for the deployment to report its type"
for _ in $(seq 1 20); do
state=$(curl -sf "${auth[@]}" "$API/environments/$ENV/deployments" \
| python3 -c "
import json, sys
for d in json.load(sys.stdin).get('deployments', []):
if d.get('apiProxy') == '$PROXY' and d.get('revision') == '$REV':
print(d.get('proxyDeploymentType', '')); break
" 2>/dev/null || true)
[[ -n "$state" ]] && break
sleep 5
done
# The deployment type is the whole verdict: STANDARD deploys clean and governs
# nothing, so it must not be just another field in a JSON blob.
hdr "Deployment result"
if [[ "$state" == "EXTENSIBLE" ]]; then
printf ' %s%-12s%s %s rev %s on %s\n' "$C_GRN" "EXTENSIBLE" "$C_RST" "$PROXY" "$REV" "$ENV" >&2
printf ' %sThe gateway can call this proxy.%s\n' "$C_DIM" "$C_RST" >&2
else
printf ' %s%-12s%s %s rev %s on %s\n' "$C_RED" "${state:-UNKNOWN}" "$C_RST" "$PROXY" "$REV" "$ENV" >&2
printf ' %sNOT EXTENSIBLE -- the callout will never be invoked. The proxy is\n deployed and healthy and governs nothing. Check that the environment\n carries apigee-service-extension-enabled=true and is COMPREHENSIVE.%s\n' \
"$C_RED" "$C_RST" >&2
fi
python3 -c "
import json
print(json.dumps({'org': '$ORG', 'environment': '$ENV', 'proxy': '$PROXY',
'revision': '$REV', 'proxyDeploymentType': '$state'}, indent=2))"
if [[ "$state" != "EXTENSIBLE" ]]; then
echo "error: deployed as '${state:-unknown}', not EXTENSIBLE. The proxy will not" >&2
echo " see the agent's off-Apigee tool egress. Check that the environment" >&2
echo " property is set and that the proxy is genuinely no-route." >&2
exit 3
fi
log "EXTENSIBLE confirmed"
ensure_apigee_environment.sh 17.8 KB
#!/bin/bash
# Create the dedicated Apigee environment this proxy needs, attach it to the
# runtime instance in the region, and put it in exactly one envgroup bearing the
# callout hostname.
#
# The environment must be attached to EXACTLY ONE envgroup. In two or more the
# gateway returns 404 for every agent request with the extension never invoked,
# and nothing reports it -- no Apigee error, no debug session, no Cloud
# Monitoring entry. Every later step still succeeds, so nothing downstream
# catches it. That failure is the reason this script exists rather than four
# curl commands in a runbook.
#
# Four things make it worth a script:
#
# 1. Environment creation must NOT send `type`. On a SUBSCRIPTION_2021 org it
# is rejected outright, and the message blames the pricing plan rather than
# the request.
# 2. Attaching the environment to the instance takes minutes and LOCKS the
# environment while it runs. A property PATCH issued in that window fails
# in a way that looks like a permissions problem.
# 3. An existing envgroup whose hostname differs is NOT reused. Silently
# repurposing someone else's envgroup would break their routing, and a
# hostname that does not match the AuthzExtension means the callout never
# lands and nothing errors.
# 4. The one-envgroup invariant is checked before and after, because an
# environment that already exists may already be in others.
#
# It creates billable resources, so it applies nothing without --yes.
#
# Data goes to stdout as JSON. Diagnostics go to stderr.
set -euo pipefail
usage() {
cat <<'EOF'
Ensure a dedicated Apigee environment for the ext-proc proxy.
Usage:
ensure_apigee_environment.sh --org ORG --env ENV --region R \
--envgroup GROUP --hostname HOST [options]
Required:
--org ORG Apigee organization
--env ENV environment to create or verify; must end up dedicated
--region R must match the Agent Gateway and the callout endpoint
--envgroup GROUP envgroup to create or reuse
--hostname HOST callout hostname for the envgroup. Must be byte-identical
to the DNS A record and the AuthzExtension authority.
Options:
--instance NAME runtime instance to attach to. Default: the single ACTIVE
instance in --region; ambiguity is an error, not a guess.
--timeout SECONDS how long to wait for the instance attachment.
Default 600; it normally takes about four minutes.
--yes apply. Without it, prints the plan and exits 0.
--help this text
Environment:
CLOUDSDK_AUTH_ACCESS_TOKEN set from ADC if unset.
Exit codes:
0 already correct, or plan shown, or applied successfully
1 usage error
2 precondition failed (no instance in region, environment already shared,
envgroup exists with a different hostname)
3 apply failed, or the invariant is still violated afterwards
EOF
}
log() { printf '%s\n' "$*" >&2; }
# ---------------------------------------------------------------- display ----
# Same palette as assess_integration.sh so the whole skill looks like one tool.
# The tty test is on fd 2, NOT fd 1: every log line here goes to stderr, so
# testing stdout would colour a piped run and leave an interactive one plain --
# exactly backwards. Honours NO_COLOR (no-color.org) and a dumb terminal.
if [[ -t 2 && -z "${NO_COLOR:-}" && "${TERM:-dumb}" != "dumb" ]]; then
C_RST=$'\033[0m'; C_DIM=$'\033[2m'; C_BLD=$'\033[1m'
C_GRN=$'\033[32m'; C_RED=$'\033[31m'; C_YEL=$'\033[33m'; C_BLU=$'\033[36m'
else
C_RST=; C_DIM=; C_BLD=; C_GRN=; C_RED=; C_YEL=; C_BLU=
fi
# hdr <title> section banner
# row <verb> <text> a planned change; CREATE/RESERVE cyan, MODIFY yellow
# cost <line>... standing-spend callout, always yellow
hdr() { printf '%s\n%s┌─ %s %s%s\n' "" "$C_DIM" "$1" "$(printf '─%.0s' $(seq 1 $(( 92 > ${#1} ? 92 - ${#1} : 3 ))))" "$C_RST" >&2; }
row() { local c="$C_BLU"; case "$1" in MODIFY|PATCH|APPEND) c="$C_YEL";; REUSE) c="$C_GRN";; esac
printf ' %s%-8s%s %s\n' "$c" "$1" "$C_RST" "$2" >&2; }
cost() { printf ' %s%s%s\n' "$C_YEL" "$*" "$C_RST" >&2; }
die() { log "ERROR: $1"; exit "${2:-1}"; }
ORG=""; ENV=""; REGION=""; ENVGROUP=""; HOSTNAME_=""; INSTANCE=""; TIMEOUT=600; APPLY=0
while [[ $# -gt 0 ]]; do
case "$1" in
--org) ORG="$2"; shift 2 ;;
--env) ENV="$2"; shift 2 ;;
--region) REGION="$2"; shift 2 ;;
--envgroup) ENVGROUP="$2"; shift 2 ;;
--hostname) HOSTNAME_="$2"; shift 2 ;;
--instance) INSTANCE="$2"; shift 2 ;;
--timeout) TIMEOUT="$2"; shift 2 ;;
--yes) APPLY=1; shift ;;
--help) usage; exit 0 ;;
*) usage >&2; die "unknown argument: $1" 1 ;;
esac
done
for v in ORG ENV REGION ENVGROUP HOSTNAME_; do
[[ -n "${!v}" ]] || { usage >&2; die "missing --${v,,}" 1; }
done
[[ "$TIMEOUT" =~ ^[0-9]+$ ]] || die "--timeout must be a whole number of seconds" 1
: "${CLOUDSDK_AUTH_ACCESS_TOKEN:=$(gcloud auth application-default print-access-token 2>/dev/null)}"
export CLOUDSDK_AUTH_ACCESS_TOKEN
[[ -n "$CLOUDSDK_AUTH_ACCESS_TOKEN" ]] \
|| die "could not obtain an ADC token; run 'gcloud auth application-default login'" 2
API="https://apigee.googleapis.com/v1/organizations/$ORG"
auth=(-H "Authorization: Bearer $CLOUDSDK_AUTH_ACCESS_TOKEN")
json=(-H "Content-Type: application/json")
# jq is not assumed; python3 needs only the json stdlib here (no PyYAML).
pyjson() { python3 -c "$1" 2>/dev/null; }
# ---------------------------------------------------------------- inspect ----
log "==> inspecting org $ORG"
# Runtime instance. Guessing the wrong one puts the environment in another
# region, where the callout endpoint cannot reach it.
if [[ -z "$INSTANCE" ]]; then
mapfile -t candidates < <(curl -sf "${auth[@]}" "$API/instances" 2>/dev/null | pyjson "
import json, sys
for i in json.load(sys.stdin).get('instances', []):
if i.get('location') == '$REGION' and i.get('state') == 'ACTIVE':
print(i['name'])
")
case "${#candidates[@]}" in
0) die "no ACTIVE runtime instance in $REGION. The environment must attach to an instance in the same region as the gateway." 2 ;;
1) INSTANCE="${candidates[0]}"; log " instance: $INSTANCE (only ACTIVE one in $REGION)" ;;
*) die "$REGION has ${#candidates[@]} ACTIVE instances (${candidates[*]}). Pass --instance to choose." 2 ;;
esac
else
log " instance: $INSTANCE (given)"
fi
env_exists=0
curl -sf "${auth[@]}" "$API/environments/$ENV" >/dev/null 2>&1 && env_exists=1
log " environment $ENV: $([[ $env_exists -eq 1 ]] && echo present || echo ABSENT)"
instance_attached=0
if [[ $env_exists -eq 1 ]]; then
if curl -sf "${auth[@]}" "$API/instances/$INSTANCE/attachments" 2>/dev/null | pyjson "
import json, sys
atts = json.load(sys.stdin).get('attachments', [])
sys.exit(0 if any(a.get('environment') == '$ENV' for a in atts) else 1)
"; then instance_attached=1; fi
log " attached to $INSTANCE: $([[ $instance_attached -eq 1 ]] && echo yes || echo NO)"
fi
# Envgroup. A hostname mismatch is fatal rather than repaired: the envgroup may
# belong to someone else, and rewriting its hostnames would break their routing.
group_exists=0; group_hostnames=""
if group_json=$(curl -sf "${auth[@]}" "$API/envgroups/$ENVGROUP" 2>/dev/null); then
group_exists=1
group_hostnames=$(printf '%s' "$group_json" | pyjson "
import json, sys
print(' '.join(json.load(sys.stdin).get('hostnames', [])))
")
log " envgroup $ENVGROUP: present, hostnames: ${group_hostnames:-<none>}"
if [[ " $group_hostnames " != *" $HOSTNAME_ "* ]]; then
die "envgroup '$ENVGROUP' already exists with hostnames '$group_hostnames', which does not include '$HOSTNAME_'. Refusing to rewrite an existing envgroup: it may carry other routing, and a hostname that differs from the AuthzExtension authority means the callout never lands and nothing errors. Pick a different --envgroup, or fix the hostname." 2
fi
else
log " envgroup $ENVGROUP: ABSENT"
fi
group_attached=0
if [[ $group_exists -eq 1 ]]; then
if curl -sf "${auth[@]}" "$API/envgroups/$ENVGROUP/attachments" 2>/dev/null | pyjson "
import json, sys
atts = json.load(sys.stdin).get('environmentGroupAttachments', [])
sys.exit(0 if any(a.get('environment') == '$ENV' for a in atts) else 1)
"; then group_attached=1; fi
fi
# The invariant, checked on what exists today. An environment already sitting in
# other envgroups cannot be made dedicated by adding one more.
count_envgroups() {
curl -sf "${auth[@]}" "$API/envgroups" 2>/dev/null | pyjson "
import json, sys
print('\n'.join(g['name'] for g in json.load(sys.stdin).get('environmentGroups', [])))
" | while read -r g; do
[[ -z "$g" ]] && continue
if curl -sf "${auth[@]}" "$API/envgroups/${g}/attachments" 2>/dev/null | pyjson "
import json, sys
atts = json.load(sys.stdin).get('environmentGroupAttachments', [])
sys.exit(0 if any(a.get('environment') == '$ENV' for a in atts) else 1)
"; then printf '%s ' "$g"; fi
done
}
existing_groups=""
if [[ $env_exists -eq 1 ]]; then
existing_groups="$(count_envgroups)"; existing_groups="${existing_groups% }"
others=""
for g in $existing_groups; do [[ "$g" != "$ENVGROUP" ]] && others+="$g "; done
others="${others% }"
if [[ -n "$others" ]]; then
die "environment '$ENV' is already attached to envgroup(s) '$others' besides '$ENVGROUP'. A service-extension environment must be in exactly one, or the gateway 404s every agent request with the extension never invoked and no error anywhere. Use a dedicated environment. See references/gotchas.md." 2
fi
fi
# ------------------------------------------------------------------- plan ----
plan=()
[[ $env_exists -eq 0 ]] && plan+=("create environment $ENV (without 'type')")
[[ $instance_attached -eq 0 ]] && plan+=("attach $ENV to instance $INSTANCE (minutes; environment is locked meanwhile)")
[[ $group_exists -eq 0 ]] && plan+=("create envgroup $ENVGROUP with hostname $HOSTNAME_")
[[ $group_attached -eq 0 ]] && plan+=("attach envgroup $ENVGROUP to $ENV")
if [[ ${#plan[@]} -eq 0 ]]; then
log "==> nothing to do: $ENV exists, is attached to $INSTANCE, and is in exactly one envgroup ($ENVGROUP)"
printf '{"changed":false,"environment":"%s","instance":"%s","envgroup":"%s","hostname":"%s"}\n' \
"$ENV" "$INSTANCE" "$ENVGROUP" "$HOSTNAME_"
exit 0
fi
hdr "Proposed changes in org $ORG"
for p in "${plan[@]}"; do
# PATCHing the environment type edits a resource that already exists;
# everything else here brings something new into being. Colour them apart,
# because "what are you changing that I already have" is the question.
case "$p" in
patch*|*type*COMPREHENSIVE*) row MODIFY "$p" ;;
*) row CREATE "$p" ;;
esac
done
log ""
cost "These create billable resources. The instance attachment takes about"
cost "four minutes and LOCKS the environment while it runs."
log ""
if [[ $APPLY -eq 0 ]]; then
printf ' %sNot applying.%s Re-run with %s--yes%s to make these changes.\n' \
"$C_BLD" "$C_RST" "$C_BLD" "$C_RST" >&2
printf '{"changed":false,"planned":%d,"environment":"%s","instance":"%s","envgroup":"%s"}\n' \
"${#plan[@]}" "$ENV" "$INSTANCE" "$ENVGROUP"
exit 0
fi
# ------------------------------------------------------------------ apply ----
post() { # post URL JSON_BODY ERRLABEL -> response body
local body code
body="$(curl -s -w '\n%{http_code}' -X POST "${auth[@]}" "${json[@]}" -d "$2" "$1")"
code="${body##*$'\n'}"; body="${body%$'\n'*}"
if [[ "$code" != 2* ]]; then
log "$3 failed (HTTP $code). Apigee said:"; printf '%s\n' "$body" >&2
die "$3 failed" 3
fi
printf '%s' "$body"
}
# These POSTs return a long-running operation, and the resource is LOCKED until
# it finishes. Critically, the environment is READABLE long before it is ready:
# a GET returns 200 while the create operation is at 1%, so "can I fetch it" is
# not a readiness test. Attaching in that window fails with FAILED_PRECONDITION
# naming the operation that holds the lock. Poll the operation itself.
wait_op() { # wait_op OPERATION_NAME LABEL TIMEOUT_SECONDS
local op="$1" label="$2" deadline state
deadline=$(( $(date +%s) + $3 ))
[[ -n "$op" ]] || die "$label returned no operation to wait on" 3
while :; do
state="$(curl -sf "${auth[@]}" "https://apigee.googleapis.com/v1/$op" 2>/dev/null | pyjson "
import json, sys
o = json.load(sys.stdin)
if o.get('error'):
print('FAILED ' + json.dumps(o['error'].get('message', 'unknown')))
elif o.get('done'):
print('DONE')
else:
m = o.get('metadata', {}).get('progress', {})
print('RUNNING %s' % m.get('percentDone', '?'))
")"
case "$state" in
DONE) return 0 ;;
FAILED*) die "$label failed: ${state#FAILED }" 3 ;;
*) : ;;
esac
[[ $(date +%s) -ge $deadline ]] \
&& die "$label did not finish within $3s. It may still be running; re-run this script to pick up where it left off." 3
sleep 10
log " ${state:-waiting}..."
done
}
if [[ $env_exists -eq 0 ]]; then
log "==> creating environment $ENV"
# No "type" on CREATE: it is rejected on SUBSCRIPTION_2021 orgs with a
# message about pricing plans. The org default applies instead -- and that
# default is BASE, which REJECTS extensible proxies. Left alone, the create,
# the attach and the property PATCH all succeed and only the deploy fails:
# "Extensible proxy can not be deployed to a base environment."
# and it fails AFTER the ~4 minute attachment. Patched below instead, which
# avoids the create-time rejection and still reaches a usable end state.
op="$(post "$API/environments" "{\"name\":\"$ENV\"}" "environment create" \
| pyjson "import json,sys; print(json.load(sys.stdin).get('name',''))")"
wait_op "$op" "environment create" "$TIMEOUT"
log " created"
fi
# --------------------------------------------------------- environment type --
# Unconditional and idempotent: patching an already-COMPREHENSIVE environment
# is a no-op. Done BEFORE the instance attachment so a failure here costs
# seconds instead of arriving four minutes later.
#
# These two calls used a bare $TOKEN, which this script never defines -- every
# other call uses "${auth[@]}". Both sat inside command substitutions ending
# `|| echo ""`, so `set -u` aborted the subshell and the failure was swallowed
# into an empty string; the only tell was `environment type: unknown`, which
# reads as cosmetic. The success log below was also unconditional, so the
# script reported "now COMPREHENSIVE" and exited 0 with applied=4 while the
# environment was still BASE -- surfacing four steps later as a deployment
# that would not come up EXTENSIBLE. Found by a live run.
env_type="$(curl -fsS "${auth[@]}" "$API/environments/$ENV" 2>/dev/null \
| pyjson "import json,sys; print(json.load(sys.stdin).get('type',''))" || echo "")"
# An empty read is NOT "absent type". A healthy org legitimately omits `type`,
# but so does a failed call, and the two must not be conflated: one is fine to
# patch past, the other means we are flying blind. Probe once more without the
# json filter to tell them apart, and refuse rather than guess.
if [[ -z "$env_type" ]]; then
if ! curl -fsS "${auth[@]}" "$API/environments/$ENV" >/dev/null 2>&1; then
die "cannot read environment $ENV to determine its type -- refusing to continue, because a BASE environment that looks unknown will fail at proxy deploy four steps from now"
fi
log "==> environment type: not reported (absent is not BASE; patching anyway is a no-op)"
else
log "==> environment type: $env_type"
fi
if [[ "$env_type" != "COMPREHENSIVE" ]]; then
log " BASE cannot host an extensible proxy -- patching to COMPREHENSIVE"
op="$(curl -fsS -X PATCH "${auth[@]}" \
-H 'Content-Type: application/json' \
"$API/environments/$ENV?updateMask=type" \
-d '{"type":"COMPREHENSIVE"}' \
| pyjson "import json,sys; print(json.load(sys.stdin).get('name',''))" || echo "")"
if [[ -n "$op" ]]; then
wait_op "$op" "environment type patch" "$TIMEOUT"
log " now COMPREHENSIVE (apigee-service-extension-enabled survives this)"
else
# Never claim success for a call that returned nothing. This is the exact
# shape of the original defect.
die "environment type PATCH returned no operation -- $ENV may still be BASE; re-run, or PATCH ?updateMask=type to COMPREHENSIVE by hand before deploying"
fi
fi
if [[ $instance_attached -eq 0 ]]; then
log "==> attaching $ENV to instance $INSTANCE (this takes minutes)"
op="$(post "$API/instances/$INSTANCE/attachments" "{\"environment\":\"$ENV\"}" "instance attach" \
| pyjson "import json,sys; print(json.load(sys.stdin).get('name',''))")"
wait_op "$op" "instance attach" "$TIMEOUT"
log " attached"
fi
if [[ $group_exists -eq 0 ]]; then
log "==> creating envgroup $ENVGROUP on $HOSTNAME_"
post "$API/envgroups" "{\"name\":\"$ENVGROUP\",\"hostnames\":[\"$HOSTNAME_\"]}" "envgroup create" >/dev/null
log " created"
fi
if [[ $group_attached -eq 0 ]]; then
log "==> attaching envgroup $ENVGROUP to $ENV"
post "$API/envgroups/$ENVGROUP/attachments" "{\"environment\":\"$ENV\"}" "envgroup attach" >/dev/null
log " attached"
fi
# ------------------------------------------------------------------ verify ---
log "==> verifying"
final_groups="$(count_envgroups)"; final_groups="${final_groups% }"
final_count=$(wc -w <<<"$final_groups")
[[ "$final_count" -eq 1 && "$final_groups" == "$ENVGROUP" ]] \
|| die "after applying, $ENV is in $final_count envgroup(s) ($final_groups); expected exactly 1 ($ENVGROUP)" 3
curl -sf "${auth[@]}" "$API/instances/$INSTANCE/attachments" 2>/dev/null | pyjson "
import json, sys
atts = json.load(sys.stdin).get('attachments', [])
sys.exit(0 if any(a.get('environment') == '$ENV' for a in atts) else 1)
" || die "after applying, $ENV is not attached to instance $INSTANCE" 3
log " $ENV is attached to $INSTANCE and is in exactly one envgroup ($ENVGROUP)"
printf '{"changed":true,"environment":"%s","instance":"%s","envgroup":"%s","hostname":"%s","applied":%d}\n' \
"$ENV" "$INSTANCE" "$ENVGROUP" "$HOSTNAME_" "${#plan[@]}"
ensure_gateway_connectivity.sh 21.2 KB
#!/bin/bash
# Give an Agent Gateway a route into your VPC: a PSC-interface network
# attachment plus DNS peering for the callout domain.
#
# Without both, the gateway cannot reach a private Apigee endpoint and cannot
# resolve the callout hostname. Nothing reports this. The gateway keeps serving
# ordinary agent traffic to public Google endpoints -- that path never enters
# your VPC -- so every other check passes and only the Apigee callout fails.
#
# Three things make this worth a script rather than three commands:
#
# 1. `agent-gateways import` is a WHOLE-RESOURCE upsert. Importing a YAML
# that carries only name + networkConfig silently drops `registries` and
# `protocols`. This does read-modify-write off the live export so nothing
# is lost.
# 2. `dnsPeeringConfig.targetNetwork` must be the full
# projects/{p}/global/networks/{n}. A bare network name is rejected.
# 3. A gateway created before `protocols` was enforced exports YAML that its
# own import rejects -- the API marks the field "Optional. Deprecated."
# while gcloud requires it client-side. PROTOCOL_UNSPECIFIED is injected
# when the export lacks it.
#
# It modifies a resource you own, so it applies nothing without --yes.
#
# Data goes to stdout as JSON. Diagnostics go to stderr.
set -euo pipefail
usage() {
cat <<'EOF'
Ensure an Agent Gateway can reach your VPC.
Usage:
ensure_gateway_connectivity.sh --gateway GW --project P --region R \
--vpc VPC --subnet SUBNET --attachment NAME --domain DOMAIN [options]
Required:
--gateway GW Agent Gateway short name
--project P project holding the gateway, VPC and attachment
--region R must match the gateway and the Apigee instance
--vpc VPC VPC the gateway will egress into
--subnet SUBNET subnet in --region for the network attachment
--attachment NAME network attachment; created if absent, reused if present
--domain DOMAIN private DNS domain to peer, trailing dot
(e.g. internal.example.local.)
Options:
--zone NAME private DNS zone to create for --domain when none exists.
The import is rejected outright if the domain has no
private zone in --vpc. Default: agent-gw-zone
--yes apply. Without it, prints the diff and exits 0.
--help this text
Environment:
CLOUDSDK_AUTH_ACCESS_TOKEN set from ADC if unset.
Exit codes:
0 already correct, or diff shown, or applied
1 usage error
2 precondition failed (missing subnet, gateway not found)
3 import failed or gateway still lacks networkConfig afterwards
EOF
}
log() { printf '%s\n' "$*" >&2; }
# ---------------------------------------------------------------- display ----
# Same palette as assess_integration.sh so the whole skill looks like one tool.
# The tty test is on fd 2, NOT fd 1: every log line here goes to stderr, so
# testing stdout would colour a piped run and leave an interactive one plain --
# exactly backwards. Honours NO_COLOR (no-color.org) and a dumb terminal.
if [[ -t 2 && -z "${NO_COLOR:-}" && "${TERM:-dumb}" != "dumb" ]]; then
C_RST=$'\033[0m'; C_DIM=$'\033[2m'; C_BLD=$'\033[1m'
C_GRN=$'\033[32m'; C_RED=$'\033[31m'; C_YEL=$'\033[33m'; C_BLU=$'\033[36m'
else
C_RST=; C_DIM=; C_BLD=; C_GRN=; C_RED=; C_YEL=; C_BLU=
fi
# hdr <title> section banner
# row <verb> <text> a planned change; CREATE/RESERVE cyan, MODIFY yellow
# cost <line>... standing-spend callout, always yellow
hdr() { printf '%s\n%s┌─ %s %s%s\n' "" "$C_DIM" "$1" "$(printf '─%.0s' $(seq 1 $(( 92 > ${#1} ? 92 - ${#1} : 3 ))))" "$C_RST" >&2; }
row() { local c="$C_BLU"; case "$1" in MODIFY|PATCH|APPEND) c="$C_YEL";; REUSE) c="$C_GRN";; esac
printf ' %s%-8s%s %s\n' "$c" "$1" "$C_RST" "$2" >&2; }
cost() { printf ' %s%s%s\n' "$C_YEL" "$*" "$C_RST" >&2; }
die() { log "ERROR: $1"; exit "${2:-1}"; }
GATEWAY=""; PROJECT=""; REGION=""; VPC=""; SUBNET=""; ATTACHMENT=""; DOMAIN=""; APPLY=0; ZONE="agent-gateway-callout-zone"
while [[ $# -gt 0 ]]; do
case "$1" in
--gateway) GATEWAY="$2"; shift 2 ;;
--project) PROJECT="$2"; shift 2 ;;
--region) REGION="$2"; shift 2 ;;
--vpc) VPC="$2"; shift 2 ;;
--subnet) SUBNET="$2"; shift 2 ;;
--attachment) ATTACHMENT="$2"; shift 2 ;;
--domain) DOMAIN="$2"; shift 2 ;;
--zone) ZONE="$2"; shift 2 ;;
--yes) APPLY=1; shift ;;
--help) usage; exit 0 ;;
*) usage >&2; die "unknown argument: $1" 1 ;;
esac
done
for v in GATEWAY PROJECT REGION VPC SUBNET ATTACHMENT DOMAIN; do
[[ -n "${!v}" ]] || { usage >&2; die "missing --${v,,}" 1; }
done
[[ "$DOMAIN" == *. ]] || die "--domain must end with a dot: $DOMAIN" 1
export CLOUDSDK_AUTH_ACCESS_TOKEN="${CLOUDSDK_AUTH_ACCESS_TOKEN:-$(gcloud auth application-default print-access-token)}"
WORK="$(mktemp -d)"; trap 'rm -rf "$WORK"' EXIT
# ---------------------------------------------------------------- inspect ----
log "==> reading gateway $GATEWAY"
gcloud network-services agent-gateways export "$GATEWAY" \
--location="$REGION" --project="$PROJECT" --destination="$WORK/before.yaml" \
>/dev/null 2>"$WORK/export.err" \
|| { cat "$WORK/export.err" >&2; die "cannot export gateway $GATEWAY" 2; }
# Surfacing an existing CUSTOM AuthzPolicy is informational. What is established:
# it cannot be merged with a new one -- `resources` is "Limited to 1 custom
# provider" and `policyProfile` is immutable -- so a second policy has to sit
# alongside it, or replace it.
#
# Deleting it is NOT known to break the gateway. On a live gateway the IAP
# CUSTOM policy was deleted during root-cause isolation, was not auto-recreated,
# and the gateway kept serving agent traffic with only the ext-proc policy
# attached. Whether it is safe in a given project depends on what relies on that
# policy, which this script cannot know -- so it reports and does not advise.
#
# Two CUSTOM policies coexisting is also NOT the cause of the 404-with-no-error
# failure; that is the environment's envgroup count. See references/gotchas.md,
# which lists a second CUSTOM policy as an individually disproved non-cause.
EXISTING_AUTHZ="$(gcloud network-security authz-policies list \
--location="$REGION" --project="$PROJECT" --format='value(name)' 2>/dev/null \
| while read -r pol; do
[[ -z "$pol" ]] && continue
if gcloud network-security authz-policies describe "${pol##*/}" \
--location="$REGION" --project="$PROJECT" --format='value(action,target.resources)' 2>/dev/null \
| grep -q "CUSTOM.*$GATEWAY"; then printf '%s ' "${pol##*/}"; fi
done)"
if [[ -n "$EXISTING_AUTHZ" ]]; then
log "NOTE: gateway $GATEWAY already has a CUSTOM AuthzPolicy: $EXISTING_AUTHZ"
log " It cannot be merged with a new one (one custom provider per policy,"
log " immutable policyProfile), so the ext-proc policy will sit alongside it."
log " Removing it may be safe -- check what depends on it first."
fi
# The two legs are INDEPENDENT and are detected separately. Testing for the
# `networkConfig:` block instead is the bug this comment exists to prevent: a
# gateway with egress attached but no DNS peering -- the exact state
# assess_integration.sh flags as
# dnsPeeringConfig absent -- ensure_gateway_connectivity.sh appends the domain
# -- took the early exit and reported "nothing to do". assess named this
# script as the remedy, this script declined to act, both exited 0, and the
# callout could not resolve its hostname while every later step passed.
HAS_EGRESS=0
grep -q 'networkAttachment:' "$WORK/before.yaml" && HAS_EGRESS=1
HAS_PEERING=0
grep -q 'dnsPeeringConfig:' "$WORK/before.yaml" && HAS_PEERING=1
# Whether the block exists is NOT the same question as whether OUR domain is in
# it. A gateway can already peer a different extension's domain -- the block is
# present, `domains` does not contain $DOMAIN, and the correct action is to
# APPEND to the list rather than to do nothing. Treating "block present" as
# "done" is the same class of bug as the one the comment above describes: the
# callout cannot resolve its hostname while every later step still passes.
DOMAIN_LISTED=0
if [[ $HAS_PEERING -eq 1 ]]; then
PRE_DOMAINS="$(gcloud network-services agent-gateways describe "$GATEWAY" \
--location="$REGION" --project="$PROJECT" \
--format='value(networkConfig.dnsPeeringConfig.domains)' 2>/dev/null || true)"
# gcloud joins a repeated field with ';'. Wrap both sides so the match is
# exact and a domain cannot match a longer one that merely contains it.
case ";$(printf '%s' "$PRE_DOMAINS" | tr -d '[:space:]');" in
*";$DOMAIN;"*) DOMAIN_LISTED=1 ;;
esac
fi
if [[ $HAS_EGRESS -eq 1 && $DOMAIN_LISTED -eq 1 ]]; then
log " egress attachment and DNS peering for $DOMAIN both present -- nothing to do"
printf '{"changed":false,"reason":"egress and dnsPeeringConfig both present","gateway":"%s"}\n' "$GATEWAY"
exit 0
fi
if [[ $HAS_EGRESS -eq 1 && $HAS_PEERING -eq 1 ]]; then
log " egress present, dnsPeeringConfig present but WITHOUT $DOMAIN -- appending"
elif [[ $HAS_EGRESS -eq 1 ]]; then
log " egress present, dnsPeeringConfig ABSENT -- gateway cannot resolve $DOMAIN"
elif [[ $HAS_PEERING -eq 1 ]]; then
log " dnsPeeringConfig present, egress ABSENT -- gateway has no route into $VPC"
else
log " networkConfig ABSENT -- gateway has no route into $VPC"
fi
gcloud compute networks subnets describe "$SUBNET" \
--region="$REGION" --project="$PROJECT" >/dev/null 2>&1 \
|| die "subnet $SUBNET not found in $REGION" 2
# The import validates dnsPeeringConfig.domains against EXISTING private zones in
# the target VPC and rejects the whole request if the domain has no zone:
# domain "x." does not exist as a private zone in network ".../networks/<vpc>"
# The zone may be empty -- only its existence is checked. The A record cannot be
# written yet anyway, since the PSC endpoint it points at comes later.
ZONE_EXISTS=0
EXISTING_ZONE="$(gcloud dns managed-zones list --project="$PROJECT" \
--filter="dnsName=$DOMAIN AND visibility=private" --format='value(name)' 2>/dev/null | head -1)"
if [[ -n "$EXISTING_ZONE" ]]; then
ZONE_EXISTS=1
ZONE="$EXISTING_ZONE"
fi
ATTACH_URI="projects/$PROJECT/regions/$REGION/networkAttachments/$ATTACHMENT"
ATTACH_EXISTS=0
gcloud compute network-attachments describe "$ATTACHMENT" \
--region="$REGION" --project="$PROJECT" >/dev/null 2>&1 && ATTACH_EXISTS=1
# ------------------------------------------------------------ build after ----
# Read-modify-write: start from the live export so registries, protocols and
# googleManaged survive. Append rather than regenerate.
cp "$WORK/before.yaml" "$WORK/after.yaml"
# Trap 3: a gateway predating client-side enforcement exports without
# `protocols`, and its own import then rejects it.
if ! grep -q '^protocols:' "$WORK/after.yaml"; then
log " export lacks 'protocols' -- injecting PROTOCOL_UNSPECIFIED so import is accepted"
printf 'protocols:\n- PROTOCOL_UNSPECIFIED\n' >>"$WORK/after.yaml"
fi
# Greenfield appends the whole block. When one leg already exists the block is
# there too, so the missing leg is INSERTED UNDER IT -- appending a second
# top-level `networkConfig:` would either be rejected or silently clobber the
# leg already in place, which for egress is the irreversible one.
#
# awk, not sed: the inserted text is multi-line and contains slashes, and the
# insert must happen exactly once even though `networkConfig:` appears in the
# comment-free export only at column 0.
_insert_under_networkconfig() {
awk -v block="$1" '
!done && /^networkConfig:[[:space:]]*$/ { print; printf "%s", block; done=1; next }
{ print }
END { if (!done) exit 9 }
' "$WORK/after.yaml" >"$WORK/after.yaml.tmp" \
|| die "export has no top-level 'networkConfig:' to insert under -- refusing to guess" 3
mv "$WORK/after.yaml.tmp" "$WORK/after.yaml"
}
# Adds one entry to an EXISTING dnsPeeringConfig.domains list, at the same
# indentation as the `domains:` key -- the shape PEERING_BLOCK below writes and
# the shape gcloud exports. Additive only: the entries already there are left
# untouched, because another extension depends on them.
_append_domain_to_peering() {
awk -v dom="$DOMAIN" '
/^[[:space:]]*domains:[[:space:]]*$/ && !done {
print
match($0, /^[[:space:]]*/)
print substr($0, 1, RLENGTH) "- " dom
done = 1
next
}
{ print }
END { if (!done) exit 9 }
' "$WORK/after.yaml" >"$WORK/after.yaml.tmp" \
|| die "dnsPeeringConfig present but has no 'domains:' list to append to -- refusing to guess" 3
mv "$WORK/after.yaml.tmp" "$WORK/after.yaml"
}
PEERING_BLOCK=" dnsPeeringConfig:
domains:
- $DOMAIN
targetNetwork: projects/$PROJECT/global/networks/$VPC
targetProject: $PROJECT
"
EGRESS_BLOCK=" egress:
networkAttachment: $ATTACH_URI
"
if [[ $HAS_EGRESS -eq 0 && $HAS_PEERING -eq 0 ]]; then
# printf, not a heredoc: both blocks already carry their trailing newline,
# and a heredoc terminator has to sit alone at the start of a source line.
printf 'networkConfig:\n%s%s' "$EGRESS_BLOCK" "$PEERING_BLOCK" >>"$WORK/after.yaml"
elif [[ $HAS_PEERING -eq 0 ]]; then
log " inserting dnsPeeringConfig into the existing networkConfig"
_insert_under_networkconfig "$PEERING_BLOCK"
else
# Peering block exists. Append our domain if it is missing -- never replace
# the list, which would unpeer whoever is already using this gateway.
if [[ $DOMAIN_LISTED -eq 0 ]]; then
log " appending $DOMAIN to the existing dnsPeeringConfig.domains"
_append_domain_to_peering
fi
if [[ $HAS_EGRESS -eq 0 ]]; then
log " inserting egress attachment into the existing networkConfig"
_insert_under_networkconfig "$EGRESS_BLOCK"
fi
fi
# --------------------------------------------------- egress reachability ----
# Attaching egress PINS ALL the gateway's egress into this VPC -- not just the
# Apigee callout. The agents' own control-plane calls (create_session, and the
# model call itself) start leaving through here too. If this VPC cannot reach
# Google APIs, every agent behind the gateway stops working.
#
# Checked BEFORE the diff, because the diff cannot show it: the change is
# purely additive on paper -- a networkConfig block appears, nothing is
# removed -- so it reads as safe while being a routing change. And it is NOT
# reversible (see the warning below), so a wrong answer here is expensive.
#
# ONLY when egress is actually being attached. If the gateway is already
# pinned and all we are adding is DNS peering, the pinning decision was taken
# long ago and this check can no longer protect anything -- it would just
# refuse the peering fix on a gateway whose callout is already broken, which
# is the worst moment to withhold the remedy.
SUBNET_PGA="n/a"
NAT_COUNT=0
if [[ $HAS_EGRESS -eq 0 ]]; then
SUBNET_PGA="$(gcloud compute networks subnets describe "$SUBNET" \
--region="$REGION" --project="$PROJECT" \
--format='value(privateIpGoogleAccess)' 2>/dev/null || echo "")"
NAT_COUNT="$(gcloud compute routers list --project="$PROJECT" \
--filter="region:($REGION) AND network:($VPC)" \
--format='value(name)' 2>/dev/null | grep -c . || true)"
if [[ "$SUBNET_PGA" != "True" && "${NAT_COUNT:-0}" -eq 0 ]]; then
log ""
log "!! REFUSING: subnet '$SUBNET' has privateIpGoogleAccess=${SUBNET_PGA:-unset} and"
log "!! there is no Cloud NAT on network '$VPC' in $REGION."
log "!!"
log "!! Pinning gateway egress into a VPC that cannot reach *.googleapis.com"
log "!! takes EVERY agent behind this gateway offline, not just the Apigee"
log "!! callout -- the agents' own create_session calls egress here too. The"
log "!! symptom is an agent-side connection reset to"
log "!! <region>-aiplatform.mtls.googleapis.com, which reads as an agent bug."
log "!!"
log "!! Fix one of these first, then re-run:"
log "!! gcloud compute networks subnets update $SUBNET --region=$REGION \\"
log "!! --project=$PROJECT --enable-private-ip-google-access"
log "!! (or create a Cloud NAT on $VPC in $REGION)"
die "VPC egress cannot reach Google APIs; refusing to pin gateway egress into it" 2
fi
log " egress reachability: privateIpGoogleAccess=$SUBNET_PGA, CloudNAT routers=$NAT_COUNT -- OK"
else
log " egress already attached -- reachability check skipped, pinning is not being changed"
fi
# ------------------------------------------------------------------ diff -----
# The one-way warning belongs to the EGRESS leg only. Printing it when all we
# are adding is DNS peering trains the reader to scroll past the loudest
# warning in the skill, which is how it stops working the day it matters.
log ""
if [[ $HAS_EGRESS -eq 0 ]]; then
log "!! ONE-WAY CHANGE. egress.networkAttachment is settable once and IMMUTABLE"
log "!! afterwards -- removing it is itself a mutation and is rejected:"
log "!! \"network attachment is not mutable\""
log "!! The attachment cannot be deleted while the gateway holds it either"
log "!! (\"Network Attachment with connected endpoints cannot be deleted\")."
log "!! The only way back is deleting and recreating the Agent Gateway, which"
log "!! means rebinding every agent -- and agent_gateway_config is set at agent"
log "!! CREATION time, so in practice the agents get redeployed."
log "!! This is the only script here that changes a resource you already own"
log "!! in a way you cannot undo."
log ""
fi
hdr "Proposed change to $GATEWAY"
if [[ $ZONE_EXISTS -eq 1 ]]; then
row REUSE "private DNS zone $ZONE for $DOMAIN"
else
row CREATE "private DNS zone $ZONE for $DOMAIN -- the import is rejected without it"
fi
if [[ $HAS_EGRESS -eq 1 ]]; then
row REUSE "network attachment (gateway egress already attached)"
elif [[ $ATTACH_EXISTS -eq 1 ]]; then
row REUSE "network attachment $ATTACHMENT"
else
row CREATE "network attachment $ATTACHMENT"
fi
if [[ $HAS_EGRESS -eq 1 ]]; then
row MODIFY "$GATEWAY -- DNS peering for $DOMAIN only (diff below)"
elif [[ $HAS_PEERING -eq 1 ]]; then
row MODIFY "$GATEWAY -- egress attachment only (diff below)"
else
row MODIFY "$GATEWAY -- egress attachment and DNS peering (diff below)"
fi
log ""
diff -u "$WORK/before.yaml" "$WORK/after.yaml" >&2 || true
log ""
# The single most consequential warning in the skill, and it used to be in
# prose elsewhere rather than at the point of consent. Gated with the leg it
# describes -- see the note above the diff.
if [[ $HAS_EGRESS -eq 0 ]]; then
cost "IRREVERSIBLE egress.networkAttachment is immutable once set, and it pins"
cost " ALL of this gateway's egress into that VPC -- not just the"
cost " Apigee callout. Agents already running can lose access to"
cost " Google APIs unless the subnet has Private Google Access or"
cost " a Cloud NAT. Capture a known-good agent turn before applying."
log ""
fi
if [[ $APPLY -ne 1 ]]; then
printf ' %sNot applying.%s Re-run with %s--yes%s to make these changes.\n' \
"$C_BLD" "$C_RST" "$C_BLD" "$C_RST" >&2
printf '{"changed":false,"reason":"dry run, --yes not given","gateway":"%s","attachmentExists":%s}\n' \
"$GATEWAY" "$([[ $ATTACH_EXISTS -eq 1 ]] && echo true || echo false)"
exit 0
fi
# ----------------------------------------------------------------- apply -----
if [[ $ZONE_EXISTS -eq 0 ]]; then
log "==> creating private DNS zone $ZONE for $DOMAIN"
gcloud dns managed-zones create "$ZONE" \
--dns-name="$DOMAIN" --visibility=private \
--networks="$VPC" --description="Agent Gateway ext-proc callout zone" \
--project="$PROJECT" >/dev/null
fi
if [[ $ATTACH_EXISTS -eq 0 ]]; then
log "==> creating network attachment $ATTACHMENT"
gcloud compute network-attachments create "$ATTACHMENT" \
--region="$REGION" --subnets="$SUBNET" \
--connection-preference=ACCEPT_AUTOMATIC \
--project="$PROJECT" >/dev/null
fi
# The export carries an etag, so a concurrent edit fails the import instead of
# being silently overwritten.
log "==> importing gateway with networkConfig"
gcloud network-services agent-gateways import "$GATEWAY" \
--source="$WORK/after.yaml" --location="$REGION" --project="$PROJECT" \
>/dev/null 2>"$WORK/import.err" \
|| { cat "$WORK/import.err" >&2; die "import failed -- gateway unchanged" 3; }
# Verify the leg that was actually added, not just that networkConfig exists.
# Checking only egress passes trivially in the peering-only case -- egress was
# already there before the import -- so a peering insert that silently did
# nothing would still be reported as success. That is the same shape of
# false-green this script was just fixed for.
log "==> verifying"
ACTUAL="$(gcloud network-services agent-gateways describe "$GATEWAY" \
--location="$REGION" --project="$PROJECT" \
--format='value(networkConfig.egress.networkAttachment)' 2>/dev/null || true)"
[[ -n "$ACTUAL" ]] || die "import reported success but egress attachment is still absent" 3
log " egress attachment: $ACTUAL"
PEER_DOMAINS="$(gcloud network-services agent-gateways describe "$GATEWAY" \
--location="$REGION" --project="$PROJECT" \
--format='value(networkConfig.dnsPeeringConfig.domains)' 2>/dev/null || true)"
case "$PEER_DOMAINS" in
*"$DOMAIN"*) log " dns peering: $PEER_DOMAINS" ;;
*) die "import reported success but dnsPeeringConfig does not list $DOMAIN (got: ${PEER_DOMAINS:-none})" 3 ;;
esac
printf '{"changed":true,"gateway":"%s","networkAttachment":"%s","dnsDomain":"%s","dnsPeeringDomains":"%s"}\n' \
"$GATEWAY" "$ACTUAL" "$DOMAIN" "$PEER_DOMAINS"
ensure_vector_search.sh 18.9 KB
#!/bin/bash
# Stand up the Vertex AI Vector Search index the semantic cache needs, deploy it
# onto an endpoint, and read back the endpoint domain the proxy must dial.
#
# This is the only prerequisite in the skill that BILLS CONTINUOUSLY and the only
# one that takes half an hour. It is billed per node-hour for as long as the
# index is deployed, whether or not any traffic arrives -- not per query.
# Streaming updates add a documented $0.45/GB, negligible at cache scale.
#
# Four things make it worth a script rather than four gcloud commands:
#
# 1. Three index properties are IMMUTABLE and two of them are easy to get
# wrong: `dimensions` must match the embeddings model's native output
# width, and `indexUpdateMethod` must be STREAM_UPDATE. Getting either
# wrong is only discoverable at runtime and only fixable by rebuilding.
# 2. The deploy step takes ~34 minutes (measured 33m44s). Almost the entire
# cost of a rebuild is that one call, so the script must resume rather
# than restart.
# 3. The endpoint domain cannot be derived -- its leading label is assigned
# at creation time and matches no id you already hold. It has to be read
# back, which is why the proxy template cannot be filled in from the
# contract file alone.
# 4. Reusing an existing index silently is dangerous: a dimension or update
# method mismatch has no remedy except a rebuild, which would destroy a
# populated index. This refuses instead.
#
# Data goes to stdout as JSON. Diagnostics go to stderr.
set -euo pipefail
usage() {
cat <<'EOF'
Ensure a Vector Search index for the semantic cache feature.
Usage:
ensure_vector_search.sh --project P --region R --index NAME --endpoint NAME \
--deployed-index-id ID --embeddings-model MODEL [options]
Required:
--project P project holding the index and endpoint
--region R must match spec.region and the Apigee instance
--index NAME index display name; created if absent, reused if present
--endpoint NAME index endpoint display name; created if absent
--deployed-index-id ID must equal semanticCache.deployedIndexId in the
input file. Lowercase, digits and underscores only.
--embeddings-model MODEL decides the index width. One of:
gemini-embedding-001 3072
text-embedding-005 768
text-multilingual-embedding-002 768
text-embedding-004 768 (serving, but
off the
supported list)
Options:
--service-account SA deployment SA to check for roles/aiplatform.user
--machine-type TYPE default e2-standard-2. SHARD_SIZE_SMALL selects this;
MEDIUM silently selects e2-standard-16, 8x the
machine for a cache holding a handful of entries.
--timeout SECONDS wait for the deploy. Default 3600; it normally takes
about 34 minutes.
--yes apply. Without it, prints the plan and exits 0.
--help this text
Environment:
CLOUDSDK_AUTH_ACCESS_TOKEN set from ADC if unset.
Exit codes:
0 already correct, or plan shown, or applied successfully
1 usage error
2 precondition failed (unknown model, dimension or update-method mismatch,
deployedIndexId already taken by a different index)
3 apply failed, or the deployment is still not ready afterwards
EOF
}
log() { printf '%s\n' "$*" >&2; }
# ---------------------------------------------------------------- display ----
# Same palette as assess_integration.sh so the whole skill looks like one tool.
# The tty test is on fd 2, NOT fd 1: every log line here goes to stderr, so
# testing stdout would colour a piped run and leave an interactive one plain --
# exactly backwards. Honours NO_COLOR (no-color.org) and a dumb terminal.
if [[ -t 2 && -z "${NO_COLOR:-}" && "${TERM:-dumb}" != "dumb" ]]; then
C_RST=$'\033[0m'; C_DIM=$'\033[2m'; C_BLD=$'\033[1m'
C_GRN=$'\033[32m'; C_RED=$'\033[31m'; C_YEL=$'\033[33m'; C_BLU=$'\033[36m'
else
C_RST=; C_DIM=; C_BLD=; C_GRN=; C_RED=; C_YEL=; C_BLU=
fi
# hdr <title> section banner
# row <verb> <text> a planned change; CREATE/RESERVE cyan, MODIFY yellow
# cost <line>... standing-spend callout, always yellow
hdr() { printf '%s\n%s┌─ %s %s%s\n' "" "$C_DIM" "$1" "$(printf '─%.0s' $(seq 1 $(( 92 > ${#1} ? 92 - ${#1} : 3 ))))" "$C_RST" >&2; }
row() { local c="$C_BLU"; case "$1" in MODIFY|PATCH|APPEND) c="$C_YEL";; REUSE) c="$C_GRN";; esac
printf ' %s%-8s%s %s\n' "$c" "$1" "$C_RST" "$2" >&2; }
cost() { printf ' %s%s%s\n' "$C_YEL" "$*" "$C_RST" >&2; }
die() { log "ERROR: $1"; exit "${2:-1}"; }
PROJECT=""; REGION=""; INDEX_NAME=""; ENDPOINT_NAME=""; DEPLOYED_ID=""
MODEL=""; SA=""; MACHINE="e2-standard-2"; TIMEOUT=3600; APPLY=0
while [[ $# -gt 0 ]]; do
case "$1" in
--project) PROJECT="$2"; shift 2 ;;
--region) REGION="$2"; shift 2 ;;
--index) INDEX_NAME="$2"; shift 2 ;;
--endpoint) ENDPOINT_NAME="$2"; shift 2 ;;
--deployed-index-id) DEPLOYED_ID="$2"; shift 2 ;;
--embeddings-model) MODEL="$2"; shift 2 ;;
--service-account) SA="$2"; shift 2 ;;
--machine-type) MACHINE="$2"; shift 2 ;;
--timeout) TIMEOUT="$2"; shift 2 ;;
--yes) APPLY=1; shift ;;
--help) usage; exit 0 ;;
*) usage >&2; die "unknown argument: $1" 1 ;;
esac
done
for v in PROJECT REGION INDEX_NAME ENDPOINT_NAME DEPLOYED_ID MODEL; do
[[ -n "${!v}" ]] || { usage >&2; die "missing --${v,,}" 1; }
done
[[ "$TIMEOUT" =~ ^[0-9]+$ ]] || die "--timeout must be a whole number of seconds" 1
# deployedIndexId is referenced from the proxy bundle as <DeployedIndexID>; the
# API rejects hyphens and uppercase, and the failure names the field, not the
# rule.
[[ "$DEPLOYED_ID" =~ ^[a-z_][a-z0-9_]*$ ]] \
|| die "--deployed-index-id must be lowercase letters, digits and underscores, starting with a letter or underscore: got '$DEPLOYED_ID'" 1
# The embeddings policy has no dimensionality parameter -- <Embeddings><VertexAI>
# takes a URL and nothing else -- so the model's NATIVE width is what lands in
# the index, and the index width is fixed at creation. That makes this table the
# whole of the compatibility contract.
case "$MODEL" in
gemini-embedding-001) DIMS=3072 ;;
text-embedding-005) DIMS=768 ;;
text-multilingual-embedding-002) DIMS=768 ;;
text-embedding-004) DIMS=768 ;;
*) die "unknown --embeddings-model '$MODEL'; pass one of gemini-embedding-001, text-embedding-005, text-multilingual-embedding-002, text-embedding-004, or extend the table in this script after measuring the model's output width" 2 ;;
esac
: "${CLOUDSDK_AUTH_ACCESS_TOKEN:=$(gcloud auth application-default print-access-token 2>/dev/null)}"
export CLOUDSDK_AUTH_ACCESS_TOKEN
[[ -n "$CLOUDSDK_AUTH_ACCESS_TOKEN" ]] \
|| die "could not obtain an ADC token; run 'gcloud auth application-default login'" 2
g=(--region="$REGION" --project="$PROJECT")
id_of() { sed 's|.*/||'; } # full resource name -> bare numeric id
# Which index is serving under a given deployedIndexId, or empty.
#
# Deliberately NOT gcloud's --format="value(deployedIndexes.filter(...))"
# projection: that silently yields nothing here even when the deployment
# exists, and an empty answer is indistinguishable from "not deployed" -- which
# would send the script off to do a 34-minute billable deploy on top of a
# healthy one. Parse the JSON instead.
deployed_index_for() { # deployed_index_for ENDPOINT_ID DEPLOYED_ID
gcloud ai index-endpoints describe "$1" "${g[@]}" --format=json 2>/dev/null \
| python3 -c "
import json, sys
try:
d = json.load(sys.stdin)
except Exception:
sys.exit(0)
for x in d.get('deployedIndexes', []):
if x.get('id') == '$2':
print(x.get('index', '').rsplit('/', 1)[-1])
break
" 2>/dev/null || true
}
# ---------------------------------------------------------------- inspect ----
log "==> inspecting Vector Search in $PROJECT / $REGION"
log " embeddings model $MODEL -> index must be ${DIMS}-dimensional"
if [[ -n "$SA" ]]; then
if gcloud projects get-iam-policy "$PROJECT" \
--flatten="bindings[].members" --format='value(bindings.role)' \
--filter="bindings.members:serviceAccount:$SA" 2>/dev/null \
| grep -qx "roles/aiplatform.user"; then
log " $SA has roles/aiplatform.user"
else
log " WARNING: $SA does not appear to hold roles/aiplatform.user at the"
log " project level. The embeddings and findNeighbors calls run"
log " as this account; without it they fail at runtime, not now."
fi
fi
INDEX_ID="$(gcloud ai indexes list "${g[@]}" \
--filter="displayName=$INDEX_NAME" --format='value(name)' 2>/dev/null | head -1 | id_of || true)"
index_dims=""; index_method=""
if [[ -n "$INDEX_ID" ]]; then
index_dims="$(gcloud ai indexes describe "$INDEX_ID" "${g[@]}" \
--format='value(metadata.config.dimensions)' 2>/dev/null || true)"
index_method="$(gcloud ai indexes describe "$INDEX_ID" "${g[@]}" \
--format='value(indexUpdateMethod)' 2>/dev/null || true)"
log " index $INDEX_NAME: present ($INDEX_ID), dimensions=${index_dims:-?} method=${index_method:-?}"
# Both of these are immutable. Rebuilding is the only remedy, and doing it
# silently would destroy whatever the index already holds.
if [[ -n "$index_dims" && "$index_dims" != "$DIMS" ]]; then
die "index '$INDEX_NAME' is ${index_dims}-dimensional but --embeddings-model $MODEL emits $DIMS. Dimensions are fixed at index creation and the SemanticCacheLookup policy cannot truncate, so these cannot be reconciled in config. Either choose a ${index_dims}-dimensional model, or create a new index and change indexId." 2
fi
if [[ -n "$index_method" && "$index_method" != "STREAM_UPDATE" ]]; then
die "index '$INDEX_NAME' has indexUpdateMethod=$index_method. SemanticCachePopulate writes through :upsertDatapoints, which only exists on a STREAM_UPDATE index, and the conversion is closed in both directions. This index can never back the cache; create a streaming one." 2
fi
else
log " index $INDEX_NAME: ABSENT"
fi
ENDPOINT_ID="$(gcloud ai index-endpoints list "${g[@]}" \
--filter="displayName=$ENDPOINT_NAME" --format='value(name)' 2>/dev/null | head -1 | id_of || true)"
deployed_ok=0; endpoint_domain=""
if [[ -n "$ENDPOINT_ID" ]]; then
endpoint_domain="$(gcloud ai index-endpoints describe "$ENDPOINT_ID" "${g[@]}" \
--format='value(publicEndpointDomainName)' 2>/dev/null || true)"
log " endpoint $ENDPOINT_NAME: present ($ENDPOINT_ID), domain=${endpoint_domain:-<none yet>}"
existing_index="$(deployed_index_for "$ENDPOINT_ID" "$DEPLOYED_ID")"
if [[ -n "$existing_index" ]]; then
# The id is taken. It is only ours if it serves the very index we resolved;
# if our index does not exist yet, then by definition it is someone else's.
if [[ -z "$INDEX_ID" ]]; then
die "deployedIndexId '$DEPLOYED_ID' on endpoint $ENDPOINT_NAME is already serving index $existing_index, but no index named '$INDEX_NAME' exists -- so this would create a second index and try to deploy it under an id that is already taken. Pick another --deployed-index-id, or point --index at the index that is already deployed." 2
fi
if [[ "$existing_index" != "$INDEX_ID" ]]; then
die "deployedIndexId '$DEPLOYED_ID' on endpoint $ENDPOINT_NAME already serves a different index ($existing_index, not $INDEX_ID). Undeploy it first, or pick another deployedIndexId -- deploying over it is not what you want." 2
fi
deployed_ok=1
log " deployedIndexId $DEPLOYED_ID: already serving $existing_index"
else
log " deployedIndexId $DEPLOYED_ID: not deployed"
fi
else
log " endpoint $ENDPOINT_NAME: ABSENT"
fi
# ------------------------------------------------------------------- plan ----
plan=()
[[ -z "$INDEX_ID" ]] && plan+=("create ${DIMS}-dim STREAM_UPDATE index '$INDEX_NAME' (~2 min)")
[[ -z "$ENDPOINT_ID" ]] && plan+=("create public index endpoint '$ENDPOINT_NAME' (~2 min)")
[[ $deployed_ok -eq 0 ]] && plan+=("deploy the index as '$DEPLOYED_ID' on $MACHINE, min=max=1 replica (~34 MIN, and STARTS BILLING)")
if [[ ${#plan[@]} -eq 0 ]]; then
[[ -n "$endpoint_domain" ]] \
|| die "index is deployed but the endpoint reports no publicEndpointDomainName; the proxy cannot be configured without it" 3
log "==> nothing to do"
printf '{"changed":false,"indexId":"%s","indexEndpointId":"%s","deployedIndexId":"%s","endpointDomain":"%s","dimensions":%s,"embeddingsModel":"%s"}\n' \
"$INDEX_ID" "$ENDPOINT_ID" "$DEPLOYED_ID" "$endpoint_domain" "$DIMS" "$MODEL"
exit 0
fi
hdr "Proposed changes in $PROJECT / $REGION"
for p in "${plan[@]}"; do row CREATE "$p"; done
log ""
cost "COST a deployed index bills per node-hour for as long as it is deployed,"
cost " with or without traffic. It is not per-query. One $MACHINE"
cost " replica runs continuously until you undeploy it, and streaming"
cost " updates add about \$0.45/GB (negligible at cache scale)."
cost " This is the only thing in this skill that costs money while idle."
log ""
if [[ $APPLY -eq 0 ]]; then
printf ' %sNot applying.%s Re-run with %s--yes%s to make these changes.\n' \
"$C_BLD" "$C_RST" "$C_BLD" "$C_RST" >&2
printf '{"changed":false,"planned":%d,"indexId":"%s","indexEndpointId":"%s","dimensions":%s}\n' \
"${#plan[@]}" "$INDEX_ID" "$ENDPOINT_ID" "$DIMS"
exit 0
fi
# ------------------------------------------------------------------ apply ----
WORK="$(mktemp -d)"; trap 'rm -rf "$WORK"' EXIT
if [[ -z "$INDEX_ID" ]]; then
log "==> creating index $INDEX_NAME"
# No contentsDeltaUri: a cache starts empty. Pointing it at a bucket makes the
# index try to ingest whatever is there as vector data.
#
# indexUpdateMethod is NOT part of this file. --metadata-file supplies the
# Index resource's `metadata` field, which is validated against the
# NearestNeighborSearch schema, and that schema defines `config` and nothing
# else. Putting indexUpdateMethod here fails every create with
# "Cannot find field: indexUpdateMethod in message
# ...NearestNeighborSearch"
# It is a top-level field on the Index resource and gcloud exposes it as its
# own flag, spelled in kebab-case: --index-update-method=stream-update.
#
# Do NOT "fix" this by deleting the setting. The flag defaults to
# BATCH_UPDATE, and SemanticCachePopulate writes through :upsertDatapoints,
# which only exists on a STREAM_UPDATE index -- the conversion is closed in
# both directions, so a batch index can never back the cache. The guard at
# the top of this script would then correctly refuse the index it had just
# created. The flag must be passed, not dropped.
cat > "$WORK/index.json" <<JSON
{"config": {"dimensions": $DIMS,
"approximateNeighborsCount": 10,
"distanceMeasureType": "DOT_PRODUCT_DISTANCE",
"shardSize": "SHARD_SIZE_SMALL",
"algorithm_config": {"treeAhConfig": {}}}}
JSON
gcloud ai indexes create --display-name="$INDEX_NAME" \
--metadata-file="$WORK/index.json" \
--index-update-method=stream-update "${g[@]}" >/dev/null 2>"$WORK/err" \
|| { cat "$WORK/err" >&2; die "index create failed" 3; }
for _ in $(seq 1 60); do
INDEX_ID="$(gcloud ai indexes list "${g[@]}" --filter="displayName=$INDEX_NAME" \
--format='value(name)' 2>/dev/null | head -1 | id_of || true)"
[[ -n "$INDEX_ID" ]] && break
sleep 5
done
[[ -n "$INDEX_ID" ]] || die "index was created but did not become listable" 3
log " created $INDEX_ID"
fi
if [[ -z "$ENDPOINT_ID" ]]; then
log "==> creating index endpoint $ENDPOINT_NAME"
gcloud ai index-endpoints create --display-name="$ENDPOINT_NAME" \
--public-endpoint-enabled "${g[@]}" >/dev/null 2>"$WORK/err" \
|| { cat "$WORK/err" >&2; die "index endpoint create failed" 3; }
for _ in $(seq 1 60); do
ENDPOINT_ID="$(gcloud ai index-endpoints list "${g[@]}" --filter="displayName=$ENDPOINT_NAME" \
--format='value(name)' 2>/dev/null | head -1 | id_of || true)"
[[ -n "$ENDPOINT_ID" ]] && break
sleep 5
done
[[ -n "$ENDPOINT_ID" ]] || die "index endpoint was created but did not become listable" 3
log " created $ENDPOINT_ID"
fi
if [[ $deployed_ok -eq 0 ]]; then
log "==> deploying index as $DEPLOYED_ID (this takes around 34 minutes)"
# min=max=1: left unset this can autoscale, and node count is the entire cost
# of the feature.
gcloud ai index-endpoints deploy-index "$ENDPOINT_ID" \
--index="$INDEX_ID" --deployed-index-id="$DEPLOYED_ID" \
--display-name="$DEPLOYED_ID" --machine-type="$MACHINE" \
--min-replica-count=1 --max-replica-count=1 \
"${g[@]}" >/dev/null 2>"$WORK/err" \
|| { cat "$WORK/err" >&2; die "deploy-index failed" 3; }
deadline=$(( $(date +%s) + TIMEOUT ))
until [[ -n "$(deployed_index_for "$ENDPOINT_ID" "$DEPLOYED_ID")" ]]; do
[[ $(date +%s) -ge $deadline ]] \
&& die "deploy did not complete within ${TIMEOUT}s. It may still be running -- re-run this script to pick up where it left off rather than starting over." 3
sleep 60
log " still deploying... ($(( ($(date +%s) - deadline + TIMEOUT) / 60 ))m elapsed)"
done
log " deployed"
fi
# The endpoint domain is assigned at creation and matches no id you hold.
# Read it back; it is what the proxy dials.
endpoint_domain="$(gcloud ai index-endpoints describe "$ENDPOINT_ID" "${g[@]}" \
--format='value(publicEndpointDomainName)' 2>/dev/null || true)"
[[ -n "$endpoint_domain" ]] \
|| die "endpoint reports no publicEndpointDomainName after deploy; the semantic cache cannot be configured without it" 3
# Cheaper to fail here than as a runtime miss.
final_dims="$(gcloud ai indexes describe "$INDEX_ID" "${g[@]}" \
--format='value(metadata.config.dimensions)' 2>/dev/null || true)"
[[ "$final_dims" == "$DIMS" ]] \
|| die "index reports ${final_dims:-unknown} dimensions but $MODEL emits $DIMS" 3
log "==> ready"
log " index $INDEX_ID (${final_dims}-dim, STREAM_UPDATE)"
log " endpoint $ENDPOINT_ID"
log " deployedIndexId $DEPLOYED_ID"
log " endpointDomain $endpoint_domain"
log ""
log " TEARDOWN, in this order -- SCL-lookup is continueOnError:false, so"
log " undeploying underneath a live proxy faults every request:"
log " 1. set semanticCache.enabled:false and redeploy the proxy"
log " 2. gcloud ai index-endpoints undeploy-index $ENDPOINT_ID \\"
log " --deployed-index-id=$DEPLOYED_ID --region=$REGION --project=$PROJECT"
log " Undeploy, do not delete: with no replicas attached the index and"
log " endpoint cost nothing, and keeping them preserves the ids and domain"
log " so a rebuild is just the deploy step again."
printf '{"changed":true,"indexId":"%s","indexEndpointId":"%s","deployedIndexId":"%s","endpointDomain":"%s","dimensions":%s,"embeddingsModel":"%s","applied":%d}\n' \
"$INDEX_ID" "$ENDPOINT_ID" "$DEPLOYED_ID" "$endpoint_domain" "$final_dims" "$MODEL" "${#plan[@]}"
read_debug_session.sh 15.4 KB
#!/bin/bash
# Arm an Apigee debug session, and read it back as the verify.md checklist.
#
# references/verify.md lists nine things to confirm on a governed turn. Every
# one of them was a hand-written JSON parse until this script existed, and the
# transaction shape is not guessable: flow variables live under
# point[].results[].ActionResult == "VariableAccess"
# in an accessList of {Get|Set: {name, value}} objects, while step execution
# lives under
# point[].id == "Execution", results[].ActionResult == "DebugInfo"
# with properties stepDefinition-name / expressionResult / action. Step
# conditions do NOT surface as Condition points -- those carry only
# ("default" equals proxy.name) -- so "did this step run" has to be read off
# Execution, not off a condition result.
#
# The first parse attempt against a healthy trace returning nothing is the
# normal experience, and it sends you to debug the callout when the parser is
# what is broken.
#
# Two modes:
# --arm create a session and print its ABSOLUTE expiry, read back off the
# response rather than echoed from the request (see below)
# default fetch /data, fetch each transaction, print the checklist
#
# Data goes to stdout. Diagnostics go to stderr.
set -euo pipefail
usage() {
cat <<'EOF'
Arm and read an Apigee debug session for the governance proxy.
Usage:
read_debug_session.sh --org O --env E --proxy P --rev R --arm [options]
read_debug_session.sh --org O --env E --proxy P --rev R --session S [options]
Required:
--org ORG Apigee org
--env ENV environment hosting the proxy
--proxy PROXY proxy name
--rev REV revision number
Mode:
--arm create a session, print its id and absolute expiry
--session S read this session back (omit --arm)
Options (--arm):
--count N transactions to capture; min 1, max 15, default 10
--tracesize N max 5120 (default)
--timeout N seconds; min 60, max 600. SEE THE CLAMP NOTE BELOW
--filter EXPR flow-Condition expression; default captures model
calls only. Pass '' to capture everything
Options (read):
--steps also print executed-vs-skipped per policy
--json machine-readable
Exit status:
0 session read (including a legitimately empty one)
1 no transactions AND the refusal-probe advice applies
2 bad invocation
EOF
}
ORG=""; ENVNAME=""; PROXY=""; REV=""; SESSION=""; ARM=0
COUNT=10; TRACESIZE=5120; TIMEOUT=600; STEPS=0; JSON=0
FILTER='(request.uri Like "*generateContent*")'
while [[ $# -gt 0 ]]; do
case "$1" in
--org) ORG="$2"; shift 2 ;;
--env) ENVNAME="$2"; shift 2 ;;
--proxy) PROXY="$2"; shift 2 ;;
--rev) REV="$2"; shift 2 ;;
--session) SESSION="$2"; shift 2 ;;
--arm) ARM=1; shift ;;
--count) COUNT="$2"; shift 2 ;;
--tracesize) TRACESIZE="$2"; shift 2 ;;
--timeout) TIMEOUT="$2"; shift 2 ;;
--filter) FILTER="$2"; shift 2 ;;
--steps) STEPS=1; shift ;;
--json) JSON=1; shift ;;
--help) usage; exit 0 ;;
*) echo "unknown argument: $1" >&2; usage >&2; exit 2 ;;
esac
done
[[ -n "$ORG" && -n "$ENVNAME" && -n "$PROXY" && -n "$REV" ]] || { usage >&2; exit 2; }
[[ $ARM -eq 1 || -n "$SESSION" ]] || { echo "need --arm or --session" >&2; usage >&2; exit 2; }
# Colour on fd 1: this script's tables ARE its stdout, as in
# assess_integration.sh. The ensure_*/deploy_* scripts test fd 2 because they
# log progress to stderr. Each tests the stream it writes to.
if [[ -t 1 && -z "${NO_COLOR:-}" && "${TERM:-dumb}" != "dumb" ]]; then
C_RST=$'\033[0m'; C_DIM=$'\033[2m'; C_BLD=$'\033[1m'
C_GRN=$'\033[32m'; C_RED=$'\033[31m'; C_YEL=$'\033[33m'; C_BLU=$'\033[36m'
else
C_RST=; C_DIM=; C_BLD=; C_GRN=; C_RED=; C_YEL=; C_BLU=
fi
# Byte-identical to the helper in the other five scripts: rule fills to 92
# past the title, so every header in the skill is 96 columns wide.
hdr() { printf '\n%s┌─ %s %s%s\n' "$C_DIM" "$1" "$(printf '─%.0s' $(seq 1 $(( 92 > ${#1} ? 92 - ${#1} : 3 ))))" "$C_RST"; }
log() { printf '%s\n' "$*" >&2; }
die() { printf '%s\n' "$*" >&2; exit "${2:-1}"; }
# ADC, not `gcloud auth print-access-token`: a plain gcloud token is rejected
# by apigee.googleapis.com on corp accounts with
# 401 ACCESS_TOKEN_TYPE_UNSUPPORTED ("restricted due to a domain admin's
# policies"). Same choice as assess_integration.sh.
TOKEN="$(gcloud auth application-default print-access-token 2>/dev/null || true)"
[[ -n "$TOKEN" ]] || die "no ADC token; run: gcloud auth application-default login" 2
BASE="https://apigee.googleapis.com/v1/organizations/$ORG/environments/$ENVNAME/apis/$PROXY/revisions/$REV/debugsessions"
# --------------------------------------------------------------------- arm --
if [[ $ARM -eq 1 ]]; then
BODY="{\"count\":$COUNT,\"tracesize\":$TRACESIZE"
[[ -n "$FILTER" ]] && BODY="$BODY,\"filter\":$(printf '%s' "$FILTER" | python3 -c 'import json,sys;print(json.dumps(sys.stdin.read()))')"
BODY="$BODY}"
RESP="$(curl -s -X POST -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' "$BASE?timeout=$TIMEOUT" -d "$BODY" || true)"
# THE POINT OF THIS MODE. 600 is what the API validates against, not
# necessarily what you get: on a PAYG org ?timeout=600 is accepted silently
# and comes back validity=300. Echoing the requested value is how you end up
# believing you have ten minutes to go drive a turn by hand, getting five,
# and reading the resulting empty session as "the callout is not landing".
# So the expiry printed here is computed from what the SERVER returned.
python3 - "$RESP" "$TIMEOUT" <<'PY'
import json, sys, time, datetime
raw, asked = sys.argv[1], int(sys.argv[2])
try:
d = json.loads(raw)
except Exception:
sys.stderr.write("could not parse create response:\n%s\n" % raw[:600]); sys.exit(2)
if "name" not in d:
sys.stderr.write("session not created:\n%s\n" % json.dumps(d, indent=2)[:900]); sys.exit(2)
sid = d["name"].rsplit("/", 1)[-1]
validity = int(d.get("validity") or d.get("timeout") or 0)
expiry = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(seconds=validity)
print("session %s" % sid)
print("validity %ss" % validity, end="")
print(" <-- CLAMPED from the %ss requested" % asked if validity and validity < asked else "")
print("window closes %s UTC (local %s)" % (
expiry.strftime("%H:%M:%S"), expiry.astimezone().strftime("%H:%M:%S")))
PY
exit 0
fi
# -------------------------------------------------------------------- read --
# /data returns a BARE JSON LIST of transaction ids, not an object. A helper
# written as d.get("responses") or d.get("data") raises AttributeError on
# exactly that, which sends you to debug your own parser. Both shapes handled.
IDS_RAW="$(curl -s -H "Authorization: Bearer $TOKEN" "$BASE/$SESSION/data" || true)"
TXN_JSON="$(mktemp)"; trap 'rm -f "$TXN_JSON"' EXIT
printf '[' >"$TXN_JSON"
FIRST=1
for id in $(python3 -c '
import json,sys
try: d=json.loads(sys.argv[1])
except Exception: d=[]
ids = d if isinstance(d,list) else (d.get("responses") or d.get("data") or [])
print("\n".join(str(i) for i in ids))' "$IDS_RAW"); do
T="$(curl -s -H "Authorization: Bearer $TOKEN" "$BASE/$SESSION/data/$id" || true)"
[[ -z "$T" ]] && continue
[[ $FIRST -eq 1 ]] || printf ',' >>"$TXN_JSON"
printf '{"id":"%s","txn":%s}' "$id" "$T" >>"$TXN_JSON"
FIRST=0
done
printf ']' >>"$TXN_JSON"
python3 - "$TXN_JSON" "$STEPS" "$JSON" "$SESSION" \
"$C_RST" "$C_DIM" "$C_BLD" "$C_GRN" "$C_RED" "$C_YEL" "$C_BLU" <<'PY'
import json, sys
path, steps, as_json, session = sys.argv[1], sys.argv[2] == "1", sys.argv[3] == "1", sys.argv[4]
RST, DIM, BLD, GRN, RED, YEL, BLU = sys.argv[5:12]
data = json.load(open(path))
def variables(txn):
"""Flow variables, flattened. Set wins over Get -- it is the value the
policy actually produced, and a Get of an unset variable is noise."""
out = {}
for point in txn.get("point", []) or []:
for res in point.get("results", []) or []:
if res.get("ActionResult") != "VariableAccess":
continue
for acc in res.get("accessList", []) or []:
for kind in ("Get", "Set"):
v = acc.get(kind)
if not v or "name" not in v:
continue
if kind == "Set" or v["name"] not in out:
out[v["name"]] = v.get("value", "")
return out
def executed(txn):
"""Policy names that actually ran, in order. Read off Execution/DebugInfo:
a skipped step leaves no Execution point, and step conditions never appear
as Condition results, so this is the only honest source."""
seen = []
for point in txn.get("point", []) or []:
if point.get("id") != "Execution":
continue
for res in point.get("results", []) or []:
if res.get("ActionResult") != "DebugInfo":
continue
for p in (res.get("properties", {}) or {}).get("property", []) or []:
if p.get("name") == "stepDefinition-name":
n = p.get("value", "")
if n and n not in seen:
seen.append(n)
return seen
def armor_of(v, ran):
"""Model Armor verdict. filterMatchState is not a documented agw.* flow
variable, so it is discovered in the trace rather than assumed; falling
back to whether the sanitize step ran at all."""
for k, val in v.items():
if "filtermatchstate" in k.lower():
return val or "-"
return "ran" if any("sanitize" in s.lower() for s in ran) else "-"
rows = []
for item in data:
txn = item.get("txn", {}) or {}
v = variables(txn)
ran = executed(txn)
cache = next((val for k, val in v.items()
if k.endswith("cache_hit")), None)
rows.append({
"txn": item.get("id", "")[-4:],
"uri": v.get("request.uri", "-"),
"model": v.get("agw.model_name") or v.get("agw.requested_model") or "-",
"bucket": v.get("agw.req_model_bucket", "-"),
"source": v.get("agw.token_source", "-"),
"tokens": v.get("agw.total_tokens", "-"),
"prompt": "set" if v.get("agw.user_prompt") else "-",
"client": v.get("agw.client_id", "-"),
"armor": armor_of(v, ran),
"cache": {"true": "HIT", "false": "miss"}.get(str(cache).lower(), "-"),
"status": v.get("response.status.code", "-"),
"steps": ran,
# The body the CALLER actually receives. verify.md checks 1-9 are all
# inbound, and that gap shipped a real defect: enforcement verified
# clean -- 429, counters right, model never called -- while the fault
# body handed the caller the full principal:// assertion. It sat in
# three traces unnoticed because nothing put it in front of anyone.
# So it is printed for refusals, not left one fetch away.
"body": v.get("response.content", ""),
})
if as_json:
print(json.dumps({"session": session, "transactions": rows}, indent=2))
sys.exit(0)
if not rows:
# [] is a MEANINGFUL result, and it does NOT prove the callout is dead.
# Observed on a working proxy: every session on three consecutive
# revisions returned [] while traffic was demonstrably governed. The
# AuthzExtension is failOpen, so a dead callout and a healthy one look
# identical from the client -- which is why the probe, not the empty
# list, is what settles it.
print("\n%sNo transactions in session %s.%s" % (BLD, session, RST))
print("""
This does NOT prove the callout is dead. Corroborate before concluding that:
Send a prompt the governance layer must refuse -- an injection, if Model
Armor is on -- and look at the error.
A 400 carrying errorcode steps.sanitize.user.prompt.FilterMatched proves
the proxy IS in the path. Only Apigee produces that: the callout lands and
the tracing is what is broken.
No refusal, or a generic gateway error, is consistent with a dead callout.
Also check the session had not already expired -- --arm prints the absolute
window, and a PAYG org silently halves a 600s request to 300s.""")
sys.exit(1)
w = "%s┌─ %s %s%s" % (DIM, "Transactions", "─" * (92 - len("Transactions")), RST)
print(w)
print(" %-5s %-22s %-14s %-7s %-7s %-16s %-5s %s" %
("TXN", "MODEL", "BUCKET", "SOURCE", "TOKENS", "ARMOR", "CACHE", "STATUS"))
print(" %-5s %-22s %-14s %-7s %-7s %-16s %-5s %s" %
("-" * 5, "-" * 22, "-" * 14, "-" * 7, "-" * 7, "-" * 16, "-" * 5, "-" * 6))
for r in rows:
colour = GRN if r["status"] in ("200", "-") else YEL
print(" %-5s %-22s %-14s %-7s %-7s %-16s %-5s %s%s%s" % (
r["txn"], r["model"][:22], r["bucket"][:14], r["source"], r["tokens"],
r["armor"][:16], r["cache"], colour, r["status"], RST))
# verify.md check 10: what the CALLER receives on a refusal path. Printed
# unasked for any non-2xx, and scanned for the things that must never appear
# in a body that leaves the proxy.
LEAK_MARKERS = ("principal://", "reasoningEngines/", ".system.id.goog",
"/projects/", "networkAttachments/")
refusals = [r for r in rows if r["status"] not in ("200", "-") and r["body"]]
if refusals:
print("\n%s┌─ %s %s%s" % (DIM, "Refusal bodies (what the caller sees)",
"─" * (92 - len("Refusal bodies (what the caller sees)")), RST))
for r in refusals:
print(" %stxn %s HTTP %s%s" % (BLD, r["txn"], r["status"], RST))
body = r["body"]
print(" " + (body[:600] + " …" if len(body) > 600 else body))
hits = sorted({m for m in LEAK_MARKERS if m in body})
if hits:
print(" %s!! LEAKS %s -- this body reaches whoever called the agent. "
"Sanitise it in a fault rule.%s" % (RED, ", ".join(hits), RST))
else:
print(" %sno identifier or internal resource name in this body%s" % (GRN, RST))
# The checklist items that are judgements rather than values.
notes = []
for r in rows:
if r["source"] == "none":
notes.append("%stxn %s: token_source=none -- the count matched no known shape, "
"total_tokens is deliberately unset and the quota will raise "
"FailedToResolveTokenUsageCount. Check this before suspecting the quota.%s"
% (YEL, r["txn"], RST))
if r["bucket"] == "other" and "gemini" in r["model"].lower():
notes.append("%stxn %s: bucket=other on a Gemini turn -- normalization did not find "
"the model where it looked.%s" % (YEL, r["txn"], RST))
if r["prompt"] == "-" and r["armor"] != "-":
notes.append("%stxn %s: agw.user_prompt unset with Model Armor present -- that is a "
"500 per request, not a skipped scan.%s" % (RED, r["txn"], RST))
if len({r["model"] for r in rows if r["model"] != "-"}) > 1 and any(r["cache"] == "HIT" for r in rows):
notes.append("%sCache HIT with more than one model in this session: the cache key is the "
"prompt embedding alone, so verify agw.requested_model matches the shape that "
"produced the entry before believing the hit.%s" % (YEL, RST))
if notes:
print()
for n in notes:
print(" " + n)
if steps:
print("\n%s┌─ %s %s%s" % (DIM, "Steps executed", "─" * (92 - len("Steps executed")), RST))
for r in rows:
print(" %stxn %s%s %s" % (BLD, r["txn"], RST, ", ".join(r["steps"]) or "(none)"))
print("\n %sA step absent here was SKIPPED, not failed -- gated steps are expected to "
"skip on non-model calls.%s" % (DIM, RST))
PY
teardown_vector_search.sh 9.0 KB
#!/bin/bash
# Stop the semantic cache billing, in the order that does not fault traffic.
#
# ensure_vector_search.sh prints these steps on success. That was the whole
# teardown story: a comment in a log the operator has probably scrolled past,
# for the one action that STOPS money being spent and the one with a sharp
# ordering constraint. Standing the index up is --yes gated, resumable,
# cost-disclosed and idempotent; tearing it down was prose. The person doing
# it is also cost-motivated and in a hurry, which is the worst combination for
# a manual ordered procedure.
#
# THE ORDERING IS LOAD-BEARING. SCL-lookup runs continueOnError="false", so
# undeploying the index underneath a live proxy faults EVERY request -- not
# just cache lookups. The proxy has to stop referring to the index before the
# index goes away:
#
# 1. redeploy the proxy without the cache feature, and wait for EXTENSIBLE
# 2. undeploy the index from the endpoint
#
# This script refuses to start step 2 until it has confirmed step 1 landed,
# by reading the deployed revision's bundle back and checking SCL-lookup is
# gone. That check is the reason this is a script and not a runbook.
#
# UNDEPLOY, NEVER DELETE. With no replicas attached the index and endpoint
# cost nothing, and keeping them preserves the ids and the endpoint domain --
# which cannot be derived and has to be read back -- so a rebuild is just the
# deploy step again.
#
# It stops a billing resource, so it applies nothing without --yes.
#
# Data goes to stdout as JSON. Diagnostics go to stderr.
set -euo pipefail
usage() {
cat <<'EOF'
Tear down the semantic cache's Vector Search deployment, in order.
Usage:
teardown_vector_search.sh --project P --region R --endpoint EP \
--deployed-index-id ID --org ORG --env ENV --proxy PROXY [--yes]
Required:
--project P project holding the index endpoint
--region R region holding the index endpoint
--endpoint EP index endpoint id
--deployed-index-id ID the deployedIndexId to undeploy
--org ORG Apigee org, for the step-1 verification
--env ENV environment hosting the proxy
--proxy PROXY proxy name
Options:
--skip-proxy-check undeploy WITHOUT confirming the proxy no longer
references the index. Only for an already-deleted
proxy; otherwise this is the footgun
--yes actually undeploy
--help this text
Exit status:
0 undeployed, or dry run
2 bad invocation, or the proxy still references the index
3 the undeploy failed
EOF
}
PROJECT=""; REGION=""; ENDPOINT_ID=""; DEPLOYED_ID=""
ORG=""; ENVNAME=""; PROXY=""; APPLY=0; SKIP_PROXY_CHECK=0
while [[ $# -gt 0 ]]; do
case "$1" in
--project) PROJECT="$2"; shift 2 ;;
--region) REGION="$2"; shift 2 ;;
--endpoint) ENDPOINT_ID="$2"; shift 2 ;;
--deployed-index-id) DEPLOYED_ID="$2"; shift 2 ;;
--org) ORG="$2"; shift 2 ;;
--env) ENVNAME="$2"; shift 2 ;;
--proxy) PROXY="$2"; shift 2 ;;
--skip-proxy-check) SKIP_PROXY_CHECK=1; shift ;;
--yes) APPLY=1; shift ;;
--help) usage; exit 0 ;;
*) usage >&2; echo "unknown argument: $1" >&2; exit 1 ;;
esac
done
[[ -n "$PROJECT" && -n "$REGION" && -n "$ENDPOINT_ID" && -n "$DEPLOYED_ID" ]] \
|| { usage >&2; exit 2; }
if [[ $SKIP_PROXY_CHECK -eq 0 ]]; then
[[ -n "$ORG" && -n "$ENVNAME" && -n "$PROXY" ]] \
|| { usage >&2; echo "--org/--env/--proxy are required unless --skip-proxy-check" >&2; exit 2; }
fi
# fd 2: this script logs progress to stderr like the other ensure_*/deploy_*
# scripts, and emits only JSON on stdout.
if [[ -t 2 && -z "${NO_COLOR:-}" && "${TERM:-dumb}" != "dumb" ]]; then
C_RST=$'\033[0m'; C_DIM=$'\033[2m'; C_BLD=$'\033[1m'
C_GRN=$'\033[32m'; C_RED=$'\033[31m'; C_YEL=$'\033[33m'; C_BLU=$'\033[36m'
else
C_RST=; C_DIM=; C_BLD=; C_GRN=; C_RED=; C_YEL=; C_BLU=
fi
log() { printf '%s\n' "$*" >&2; }
die() { printf '%s\n' "$*" >&2; exit "${2:-1}"; }
hdr() { printf '\n%s┌─ %s %s%s\n' "$C_DIM" "$1" "$(printf '─%.0s' $(seq 1 $(( 92 > ${#1} ? 92 - ${#1} : 3 ))))" "$C_RST" >&2; }
row() { printf ' %s%-8s%s %s\n' "${2:-$C_GRN}" "$1" "$C_RST" "$3" >&2; }
cost() { printf ' %s%s%s\n' "$C_YEL" "$*" "$C_RST" >&2; }
# ------------------------------------------------------- step 1 verified ----
STILL_REFERENCED="unknown"
if [[ $SKIP_PROXY_CHECK -eq 1 ]]; then
log "==> skipping the proxy check (--skip-proxy-check)"
STILL_REFERENCED="unchecked"
else
log "==> confirming the deployed proxy no longer references the index"
TOKEN="$(gcloud auth application-default print-access-token 2>/dev/null || true)"
[[ -n "$TOKEN" ]] || die "no ADC token; run: gcloud auth application-default login" 2
REV="$(curl -s -H "Authorization: Bearer $TOKEN" \
"https://apigee.googleapis.com/v1/organizations/$ORG/environments/$ENVNAME/deployments" 2>/dev/null \
| python3 -c '
import json,sys
try: d=json.load(sys.stdin)
except Exception: d={}
print(next((x.get("revision","") for x in d.get("deployments",[]) if x.get("apiProxy")==sys.argv[1]), ""))' "$PROXY" || true)"
[[ -n "$REV" ]] || die "proxy $PROXY is not deployed in $ENVNAME -- nothing references the index from there; re-run with --skip-proxy-check if that is expected" 2
log " deployed revision: $REV"
BUNDLE="$(mktemp)"; trap 'rm -f "$BUNDLE"' EXIT
curl -s -H "Authorization: Bearer $TOKEN" \
"https://apigee.googleapis.com/v1/organizations/$ORG/apis/$PROXY/revisions/$REV?format=bundle" \
-o "$BUNDLE" 2>/dev/null || true
if python3 - "$BUNDLE" <<'PY'
import sys, zipfile
try:
z = zipfile.ZipFile(sys.argv[1])
except Exception:
sys.exit(2) # could not read -- treat as "cannot prove it is safe"
hit = any(b"SemanticCacheLookup" in z.read(n) or b"SCL-lookup" in z.read(n)
for n in z.namelist() if n.endswith(".xml"))
sys.exit(0 if hit else 1)
PY
then
STILL_REFERENCED="yes"
log ""
log "!! REFUSING. Revision $REV of $PROXY still contains SCL-lookup."
log "!!"
log "!! SCL-lookup is continueOnError=\"false\". Undeploying the index"
log "!! underneath it faults EVERY request through this proxy, not just"
log "!! cache lookups -- the symptom is a total outage that looks like"
log "!! Apigee breaking, not like a cache being turned off."
log "!!"
log "!! Do step 1 first:"
log "!! set semanticCache.enabled:false in your contract file, then"
log "!! scripts/deploy_proxy.sh --org $ORG --env $ENVNAME --proxy $PROXY \\"
log "!! --template assets/apigee-proxy-template.yaml --yes"
log "!! (wait for it to report EXTENSIBLE), then re-run this script."
die "proxy still references the index; refusing to undeploy" 2
else
rc=$?
[[ $rc -eq 2 ]] && die "could not read revision $REV's bundle to verify it is safe to undeploy. Re-run with --skip-proxy-check only if you are certain the proxy no longer uses the cache." 2
STILL_REFERENCED="no"
log " SCL-lookup is absent from revision $REV -- safe to undeploy"
fi
fi
# -------------------------------------------------------------- the plan ----
MACHINE="$(gcloud ai index-endpoints describe "$ENDPOINT_ID" --region="$REGION" --project="$PROJECT" \
--format="value(deployedIndexes.filter(\"id:$DEPLOYED_ID\").extract(\"dedicatedResources.machineSpec.machineType\"))" 2>/dev/null || true)"
hdr "Teardown plan"
row KEEP "$C_GRN" "index endpoint $ENDPOINT_ID -- undeployed, not deleted"
row KEEP "$C_GRN" "the index itself -- ids and endpoint domain preserved for a rebuild"
row REMOVE "$C_YEL" "deployed index $DEPLOYED_ID${MACHINE:+ ($MACHINE)} -- this is what bills"
log ""
cost "This STOPS the per-node-hour charge. Nothing else here bills while idle."
cost "Rebuilding later is the deploy step alone (~34 min), not a fresh index."
log ""
if [[ $APPLY -ne 1 ]]; then
printf ' %sNot applying.%s Re-run with %s--yes%s to undeploy.\n' \
"$C_BLD" "$C_RST" "$C_BLD" "$C_RST" >&2
printf '{"changed":false,"reason":"dry run, --yes not given","endpoint":"%s","deployedIndexId":"%s","proxyStillReferences":"%s"}\n' \
"$ENDPOINT_ID" "$DEPLOYED_ID" "$STILL_REFERENCED"
exit 0
fi
# ------------------------------------------------------------- step 2 -------
log "==> undeploying $DEPLOYED_ID from $ENDPOINT_ID"
gcloud ai index-endpoints undeploy-index "$ENDPOINT_ID" \
--deployed-index-id="$DEPLOYED_ID" --region="$REGION" --project="$PROJECT" \
>/dev/null 2>&1 \
|| die "undeploy failed -- the deployed index is still billing" 3
log "==> verifying no replicas remain"
REMAINING="$(gcloud ai index-endpoints describe "$ENDPOINT_ID" \
--region="$REGION" --project="$PROJECT" \
--format='value(deployedIndexes[].id)' 2>/dev/null || true)"
case " $REMAINING " in
*" $DEPLOYED_ID "*) die "undeploy reported success but $DEPLOYED_ID is still deployed" 3 ;;
esac
log " remaining deployed indexes: ${REMAINING:-none}"
[[ -z "$REMAINING" ]] && log " nothing on this endpoint bills now"
printf '{"changed":true,"endpoint":"%s","deployedIndexId":"%s","remainingDeployedIndexes":"%s","proxyStillReferences":"%s"}\n' \
"$ENDPOINT_ID" "$DEPLOYED_ID" "$REMAINING" "$STILL_REFERENCED"
License (Apache-2.0)
View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE