Skip to content

4.2 Package & CLI Reference (esmeralda)

One Audited Contract for Every Runtime Hook and Operator Command

This page is the complete API and CLI reference for esmeralda (source; installed from this repository, see Installing the package). While the usage guide walks through recipes by task, this reference documents the exact contract of every module, function, class, CLI flag, telemetry JSON payload, and environment variable so platform engineers and application developers have a single authoritative specification.


Why We Built It This Way (Key Decisions & Rationale)

Decision Alternative Considered Why We Chose This
Small, Focused Submodules (app, lifecycle, plugin, auth, auth_manager, mcp, mcp_authz, a2a, ops) A single monolithic utility file Keeps runtime dependencies minimal inside agent containers while isolating operational tooling (esmeralda.ops, fastmcp) to developer and CI workflows.
Plan-First Destroy Guard in esmeralda apply (infra.apply_unit) Running raw terragrunt apply directly Inspects the saved plan JSON before applying and refuses with exit code 2 whenever destroy > 0 unless --allow-destroy is explicitly passed.
JSON-First esmeralda.ops Functions (--json) Parsing unstructured human text in scripts and MCP tools Every CLI subcommand (status, doctor, units, plan, apply, verify, logs, contracts, guard) and every esmeralda mcp tool shares the same structured dict return values and OpsError hints.

Top-level API

import esmeralda exposes:

Name Defined in Summary
prepare(steps=PREPARE) esmeralda.lifecycle Runs the prepare steps
finalize(steps=FINALIZE) esmeralda.lifecycle Runs the finalize steps
create_app(root_agent, *, name="agent", plugins=()) esmeralda.app ADK App with EsmeraldaTelemetryPlugin
EsmeraldaTelemetryPlugin esmeralda.plugin The per-request ADK plugin

esmeralda.app

create_app(root_agent, *, name="agent", plugins=()) -> google.adk.apps.App

Returns an ADK App whose plugins are EsmeraldaTelemetryPlugin() followed by plugins.

Parameter Description
root_agent The agent (or any ADK node) the app serves
name App name. Must match the agent package directory and --gemini_enterprise_app_name (both agent in this repo)
plugins Additional ADK plugins, run after EsmeraldaTelemetryPlugin

When ESMERALDA_MODEL_GATEWAY_URL is set, it first calls esmeralda.models.route_models(root_agent).

esmeralda.models_limits

check_model_settings(model, thinking=None, max_output_tokens=None, location=None) validates the thinking level, output token limit, and location at startup. It raises ValueError for unsupported settings on a known model. For an unknown model it logs a warning and returns.

esmeralda.models

Model egress through a model gateway (Apigee llm-gateway). A no-op unless ESMERALDA_MODEL_GATEWAY_URL is set.

Function / class Description
route_models(root_agent) Replaces every Gemini model name in the agent tree with gemini(name); model objects and inherited models are left alone. Returns root_agent
gemini(model, *, url=None) model unchanged without a gateway, else an ADK Gemini with base_url = the gateway, explicit project / location (MODEL_LOCATION, else global) and GatewayIdTokenCredentials; each request also carries the current span's traceparent (trace_headers())
GatewayIdTokenCredentials(audience) Bearer credentials holding an unbound ID token (auth.unbound_id_token_credentials) for the agent's runtime identity, its Agent Identity on Agent Runtime (never SERVICE_ACCOUNT_EMAIL), refreshed before expiry
trace_headers() W3C traceparent / tracestate of the current span, or {}
gateway_url() The configured gateway URL (must be https), or None

esmeralda.lifecycle

Process lifecycle. Each step is a function without arguments (Step = Callable[[], None]), is idempotent, and raises on failure.

prepare(steps=PREPARE) -> None

Runs steps in order. Call it once, at the top of the agent package, before the agent definition is imported.

finalize(steps=FINALIZE) -> None

Runs steps in order. Cheap to call repeatedly: EsmeraldaTelemetryPlugin calls it at the start of every run.

PREPARE

Default prepare steps, in this order:

Step What it does
log_egress_proxy() Logs the *_proxy environment variables the runtime advertises for gateway egress
default_environment() Sets GOOGLE_CLOUD_PROJECT from Application Default Credentials (only if unset; a warning if there are no credentials), and defaults GOOGLE_CLOUD_LOCATION=global, GOOGLE_GENAI_USE_VERTEXAI=True, GRPC_DNS_RESOLVER=native. Never overrides an explicit value
genai_over_httpx() Makes google-genai use httpx instead of aiohttp. aiohttp ignores https:// proxies, so the Gemini and Vertex session calls would bypass the egress proxy and fail
aiohttp_trust_env() Makes aiohttp.ClientSession default to trust_env=True, so other aiohttp users honor the proxy env. No-op if aiohttp isn't installed
genai_client_defaults() On every google.genai.Client: if MODEL_LOCATION is set, uses it as the location; otherwise defaults the location to global. Defaults project to GOOGLE_CLOUD_PROJECT

FINALIZE

Step What it does
baggage_span_processor() Registers BaggageSpanProcessor on the global tracer provider, once per provider. If there is no OpenTelemetry SDK provider, logs a warning once and does nothing

esmeralda.plugin

class EsmeraldaTelemetryPlugin(google.adk.plugins.base_plugin.BasePlugin)

EsmeraldaTelemetryPlugin(*, agent_name=None, finalize_steps=lifecycle.FINALIZE, emitter=None,
                         recorder=None, legacy_events=None)
Parameter Description
agent_name workload.name of usage records (unless ESMERALDA_WORKLOAD_NAME is set) and agent_id in legacy events. Defaults to the AGENT_NAME environment variable, then unknown_agent
finalize_steps The steps passed to finalize() at the start of each run
emitter A TelemetryEmitter for the legacy events. Defaults to one on usage.transport_from_env() (stdout)
recorder The usage.UsageRecorder for esmeralda.usage records. Defaults to one on the emitter's transport, with workload from the environment and framework adk
legacy_events Also write the legacy genai_token_consumption / mcp_tool_execution events. Defaults to ESMERALDA_LEGACY_TELEMETRY_EVENTS (on)

Plugin name: esmeralda_telemetry. Callbacks:

Callback Behavior
before_run_callback Runs finalize. Reads the caller context (context.from_invocation) and, if present, attaches it as baggage for the run. Starts the invocation's latency clock and token roll-up
after_run_callback Emits agent.invocation (latency, token roll-up, status=error if a model call failed) and detaches the baggage of that invocation
before_tool_callback Records the tool start time
after_tool_callback Emits tool.call with status=ok (and legacy mcp_tool_execution with status=SUCCESS)
on_tool_error_callback Emits tool.call with status=error and the exception type (and legacy mcp_tool_execution with status=ERROR and a redacted error_reason). Returns None, so the agent's own error handling still runs
before_model_callback Records the model start time and the requested model
after_model_callback For complete (non-partial) responses with token counts, emits llm.call (and legacy genai_token_consumption)
on_model_error_callback Emits llm.call with status=error and the exception type

Usage records carry caller.declared = the caller context (project_id, agent_name) with caller.verified=false, because that context is self-declared. Token counts follow OpenTelemetry GenAI semantics: usage.input_tokens = prompt + tool-use prompt tokens (cached included), usage.output_tokens = candidate + reasoning tokens.

None of the callbacks change the request or the response. Telemetry failures are logged and never break the run. Per-invocation bookkeeping is bounded (1024 entries) for runs that never reach after_run.

esmeralda.usage

Producer of the esmeralda.usage contract (contracts/usage-event.schema.json; see 2.5 Usage Telemetry Contract). Framework-agnostic: no ADK import.

Records

Function / method Event
record_llm_call(*, request_model=None, response_model=None, system=None, input_tokens=None, output_tokens=None, cached_tokens=None, reasoning_tokens=None, finish_reasons=None, operation_name="generate_content", agent_name=None, conversation_id=None, status="ok", error_type=None, latency_ms=None, caller=None, dimensions=None, span=None, timestamp=None) llm.call
record_tool_call(*, name, status="ok", duration_ms=None, server=None, call_id=None, error_type=None, agent_name=None, conversation_id=None, caller=None, dimensions=None, span=None, timestamp=None) tool.call
record_agent_invocation(*, agent_name, latency_ms=None, status="ok", error_type=None, input_tokens=None, output_tokens=None, cached_tokens=None, reasoning_tokens=None, conversation_id=None, caller=None, dimensions=None, span=None, timestamp=None) agent.invocation

The module functions run on the process-wide recorder (get_recorder(), replaced with set_recorder(recorder)); the same methods exist on every UsageRecorder. Each returns the record as sent. trace_id / span_id come from span (default: the current span) and are omitted outside a span. Unknown values are omitted, never sent as null.

Classes

Name Description
UsageRecorder(transport=None, *, workload=None, framework=None, source="workload", dimensions=None, validate=None) Builds (build(event, ...)) and sends (emit(record)) records. workload is a Workload or a callable returning one (default: Workload.from_env(framework=framework) per record). dimensions are added to every record. validate checks each record against the shipped schema and logs violations (default: ESMERALDA_USAGE_VALIDATE)
Workload(name, team=None, runtime=None, framework=None, cloud=None) Workload.from_env(*, name=None, framework=None) reads the environment variables below; runtime is detected (Agent Runtime, Cloud Run, GKE, else external)
Caller(principal=None, team=None, verified=False, declared={}) Caller.from_declared(mapping) builds an unverified caller from declared context
StdoutTransport(stream=None) One JSON line per record on stdout (Cloud Logging jsonPayload). The default
OTelLogsTransport(logger_provider=None) One OpenTelemetry log record per record (body = the record, event name esmeralda.usage)
MultiTransport(*transports) Sends to several transports; one failing does not stop the others
UsageSpanProcessor(recorder=None, *, framework=None) OpenTelemetry SpanProcessor that turns finished GenAI spans into records: generate_content / chat / text_completion → llm.call, execute_tool → tool.call, invoke_agent → agent.invocation. caller.* attributes become caller.declared, esmeralda.dimension.<key> attributes become dimensions. Don't combine it with EsmeraldaTelemetryPlugin in one process

Functions

Function Description
transport_from_env(stream=None) Transport chosen by ESMERALDA_USAGE_TRANSPORT
usage_from_span(span, recorder=None) The record for one finished span (not sent), or None for non-GenAI spans
redact(value) Drops credential-like keys and masks token-like values (bearer tokens, OAuth access tokens, JWTs, API keys). Applied to every record and legacy event
is_secret_key(key) Whether redact drops a key; includes user_auth_token and the key named by USER_AUTH_ID
string_map(values) Normalizes dimensions / caller.declared (snake_case keys, string values, at most 32 entries of 256 characters)
schema_text() / schema() The contract shipped in the package (esmeralda/contracts/usage-event.schema.json, a copy of contracts/ kept identical by a test), as text / parsed
validate(record) List of contract violations (empty when valid). Needs jsonschema

Constants: SCHEMA = "esmeralda.usage", SCHEMA_VERSION = 1, EVENTS, RUNTIMES, CLOUDS.

esmeralda.context

Caller context, for telemetry only.

class CallerContext(project_id: str, agent_name: str)

A frozen dataclass.

Member Description
CallerContext.from_mapping(value) Builds one from untrusted input. Returns None unless value is a mapping with a non-empty string project_id or agent_name. Values are trimmed and cut to 128 characters; a missing field becomes unknown
to_dict() {"project_id": ..., "agent_name": ...}

Functions

Function Description
current_identity() -> CallerContext This agent's identity, from GOOGLE_CLOUD_PROJECT and AGENT_NAME
outgoing_metadata() -> dict {"caller_context": current_identity().to_dict()}, for A2A request metadata
user_token(ctx) The end user's token for the invocation, or None. ctx is an invocation context or a callback, tool or readonly context. Reads temp:<USER_AUTH_ID> session state first, then run_config.custom_metadata["a2a_metadata"]["user_auth_token"]. A secret: forward it only through esmeralda.user_credential, never log it
user_token_state_key() temp:<USER_AUTH_ID> (default temp:user_auth_token)
from_invocation(invocation_context) Returns a CallerContext, or None. Reads the session state key temp:caller_context first, then run_config.custom_metadata["a2a_metadata"]["caller_context"]
attach_baggage(caller) -> token Sets the baggage entries caller.project_id and caller.agent_name in the current context
detach_baggage(token) -> None Restores the previous context. Skipped if the run was closed from another asyncio task

Constants

Constant Value
CALLER_CONTEXT_KEY caller_context
STATE_KEY temp:caller_context
A2A_METADATA_KEY a2a_metadata
BAGGAGE_PROJECT_ID caller.project_id
BAGGAGE_AGENT_NAME caller.agent_name

USER_TOKEN_KEY = user_auth_token: the A2A metadata key, and the default authorization id.

esmeralda.auth

Name Description
id_token(audience) -> str A Google-signed ID token for audience, for the runtime identity (on Agent Runtime, the agent's own Agent Identity). Always requested unbound (google.oauth2.id_token.fetch_id_token_credentials(audience, bind_id_token=False); google-auth before 2.61 takes no such argument and never binds), so it survives the Agent Gateway and the entry point. With the deprecated SERVICE_ACCOUNT_EMAIL opt-in, minted through impersonation of that service account instead (falls back to the runtime identity, with a warning, if impersonation fails). Cached per audience and service account; refreshed before expiry. Raises if no token can be minted
id_token_async(audience) id_token in a worker thread
unbound_id_token_credentials(audience, request) The uncached google-auth credentials behind id_token for the runtime identity (never impersonation), always unbound. esmeralda.models uses them for the model gateway
access_token() -> str An OAuth2 access token (scope cloud-platform) for the runtime identity; for SERVICE_ACCOUNT_EMAIL through impersonation when that deprecated opt-in is set (same fallback as id_token). Cached; refreshed before expiry
access_token_async() access_token in a worker thread
token_kind(url) -> "id" \| "access" "access" for hosts listed in ACCESS_TOKEN_HOSTS and for *.googleapis.com; "id" otherwise
bearer_token(url, kind=None) -> str access_token() or id_token(audience_for(url)); kind ("id" or "access") overrides token_kind(url)
audience_for(url) The URL's origin, scheme://host[:port]
is_local(url) True for localhost, 127.0.0.1, ::1
clear_cache() Drops cached credentials (tests)

esmeralda.mcp

Name Description
toolset(url, *, prefix, api_key=None, auth_provider=None, timeout=30.0, sse_read_timeout=300.0, token=None, **kwargs) An ADK McpToolset (streamable HTTP) for the server at url. Tool names get <prefix>_. token ("id" or "access") overrides auth.token_kind(url). Extra kwargs go to McpToolset (for example tool_filter)
headers_for(url, ctx=None, *, api_key=None, token=None, auth_provider=None) The headers of one request: Accept, Content-Type, X-API-Key (api_key, else AGENT_NAME), Authorization: Bearer <token> (kind from token, else auth.token_kind(url); not for local URLs; skipped with a logged error if no token can be minted), the user credential header (user_credential.outgoing_headers: only when url's host is listed in ESMERALDA_USER_CREDENTIAL_TARGETS, in its configured header, default X-User-Token, with the value from auth_manager.resolve_user_token(ctx, auth_provider=...)), and X-Agent-Spiffe-Id (when auth_manager.spiffe_id() is present)

esmeralda.auth_manager

Name Description
DelegatedContext(user_identity=None, agent_spiffe_id=None, auth_provider=None, scopes=()) Frozen dataclass representing the Three-Identity Delegation tuple (User identity + Agent SPIFFE identity = Delegated identity)
spiffe_id() -> str \| None Returns the agent's runtime SPIFFE / principal:// ID from AGENT_SPIFFE_ID or AGENT_WORKLOAD_CERT_PATH
delegated_context(ctx=None, *, auth_provider=None, scopes=()) -> DelegatedContext Builds a DelegatedContext for an invocation
acquire_token(auth_provider, *, user_id=None, session_id=None, scopes=(), base_url=None, timeout=10.0) -> str Acquires a 3LO/2LO token or API key from Agent Identity Auth Manager ({auth_provider}:acquireToken)
resolve_user_token(ctx=None, *, auth_provider=None, scopes=()) -> str \| None When auth_provider or AGENT_AUTH_PROVIDER is configured, a delegated token via acquire_token (preferred; a failure raises, no fallback to the raw token); otherwise context.user_token(ctx)

esmeralda.user_credential

Name Description
Targets.parse(raw) -> Targets Parses the ESMERALDA_USER_CREDENTIAL_TARGETS JSON ({"<host>[:<port>]": "<header>" \| null \| true \| false}). Invalid input, wildcards and reserved header names are dropped (fail closed)
targets() -> Targets The targets from ESMERALDA_USER_CREDENTIAL_TARGETS (re-read when it changes)
header_for(url) -> str \| None / accepts(url) -> bool The header url's host reads the credential from, or None when the host isn't listed
outgoing_headers(url, ctx=None, *, auth_provider=None) -> dict {header: credential} for a listed host, else {}. Failures are logged without the value
redact(value, secrets=()) -> value A copy with each secret string, and the values of sensitive keys (user_auth_token, temp:<USER_AUTH_ID>, credential headers, Authorization, ...), replaced by [REDACTED]
describe_error(exc, secrets=()) -> str "<Type>: <message>" with secrets masked
DEFAULT_HEADER X-User-Token

esmeralda.mcp_authz

Name Description
verify_request(headers=None, *, enforce=None, allowed_domains=None) -> VerifiedCaller Verifies the user credential header (user_token_headers()) and X-Agent-Spiffe-Id without network I/O; rejects *.gserviceaccount.com tokens and fails closed when MCP_ENFORCE_USER_AUTH=true
user_token_headers() -> list[str] The headers read, in order: USER_CREDENTIAL_HEADER (else X-User-Token), X-User-Token, the legacy User-Auth-Token
decode_jwt_claims(token) -> dict \| None Decodes the JSON payload of a 3-part JWT locally
is_service_account_email(value) -> bool True when value is a *.gserviceaccount.com service account identifier
AuthorizationError(reason, *, status_code=403) Raised when verification fails

esmeralda.attribution

The catalog caller guard: it maps the platform-verified caller to a catalog caller and team, and rejects (deny) or flags callers missing from the catalog. Standard library only; the MCP servers vendor it unchanged as caller_guard.py. See 5.3 §5.

Name Description
CallerGuard(app, allowlist=None, *, exempt_paths=("/health", "/healthz")) ASGI middleware. allowlist defaults to Allowlist.from_env(); without one it passes everything through. Denied requests get 401 (no verified identity) or 403 (unmapped caller, declared mismatch) with a JSON reason. Allowed requests carry the decision in scope["state"]["esmeralda.caller"] and current(), plus X-Esmeralda-Billed-Team when attributed
Allowlist.from_env() / from_json(text) / from_mapping(data) The compiled allowlist ({"policy": {...}, "token_validated_by": "cloud_run_iam", "callers": [{principal, caller, team, cost_centers, shared}]}); invalid values raise
verified_principal(headers, *, validated_by=None) -> str \| None The caller from the Google ID token in X-Serverless-Authorization or Authorization: email, else sub (spiffe:// ids in their principal:// form). With validated_by="cloud_run_iam" (Cloud Run IAM validated the header) the token counts as is; otherwise only a platform signature-stripped token counts. Malformed or missing tokens give None
identity_evidence(headers) -> dict The shape of each identity header (absent, opaque, jwt_signed, jwt_stripped, malformed), never its value; logged with unverified decisions
decide(allowlist, principal, declared_cost_center=None) -> Decision Applies unmapped_caller and declared_mismatch
Decision allowed, status, reason (mapped, unmapped, unverified, declared_mismatch), principal, caller, team, cost_center, declared_cost_center, declared_mismatch; verified is true only for a mapped principal with a team; caller_record() is the usage record's caller
current() -> Decision \| None The decision for the request being served (the plugin uses it to fill caller.verified, caller.principal, caller.team)
ALLOWLIST_ENV, DECLARED_COST_CENTER_HEADER, BILLED_TEAM_HEADER ESMERALDA_CALLER_ALLOWLIST, X-Esmeralda-Cost-Center, X-Esmeralda-Billed-Team

esmeralda.a2a

Name Description
remote_agent(name, *, url, description="", api_key=None, timeout=60.0, token=None) An ADK RemoteA2aAgent for the agent at url. Card from <url>/v1/card, with every RPC address pinned to url before ADK's checks. Every request gets a bearer token for url (kind from token, else auth.token_kind(url); not for local URLs) and X-API-Key
request_metadata(invocation_context, a2a_message=None, *, url=None) The A2A request metadata: caller_context, plus user_auth_token when the invocation has one and url's host is listed in ESMERALDA_USER_CREDENTIAL_TARGETS (never without url)
request_metadata_for(url) request_metadata bound to url; usable as a2a_request_meta_provider (remote_agent uses it)
request_converter(request, part_converter=None) ADK's A2A request converter, with user_auth_token moved from the request metadata (which ADK copies into every stored event) into temp:<USER_AUTH_ID> state. esmeralda serve uses it (A2aAgentExecutorConfig(request_converter=...))

esmeralda.a2a_retry

Timeout and retries of a2a.remote_agent. Its timeout argument now defaults to None, meaning $A2A_TIMEOUT_SECONDS, else 300 s.

An A2A message:send is not idempotent (a re-send runs the remote agent again), so remote_agent only re-sends failures that happen before the callee starts work. At most 3 attempts, with jittered exponential backoff (about 0.5 s, then 1 s; a Retry-After up to 10 s is honored).

Failure Retried
Connect error (refused, DNS, TLS handshake), connect or pool timeout Yes
429 Yes
502 / 503 without an A2A task in the body Yes
502 / 503 whose body carries a task No
504, read timeout No: the callee keeps running, so the error is surfaced
Any other status or error No
Name Description
client_timeout(timeout=None) -> float timeout if given, else $A2A_TIMEOUT_SECONDS, else 300
should_retry(attempt, *, status=None, error=None, task_created=False) -> bool The decision table above, for 1-based attempt
RetryTransport(inner=None, *, sleep=asyncio.sleep) httpx.AsyncBaseTransport applying it

esmeralda.telemetry

class TelemetryEmitter(stream=None, *, transport=None, recorder=None)

Backwards-compatible facade over esmeralda.usage. transport defaults to usage.StdoutTransport(stream) when stream is given, else usage.transport_from_env(). emitter.usage is a usage.UsageRecorder on the same transport (or recorder). Every event goes through usage.redact.

Member Event
usage esmeralda.usage records (record_llm_call, record_tool_call, record_agent_invocation)
transport The shared transport
emit(payload) Any payload (redacted)
token_consumption(*, agent_id, session_id, user_id, model, prompt_tokens, completion_tokens, total_tokens, thoughts_tokens=0, cached_tokens=0, finish_reason="STOP", execution_path=None, turn_index=1) Legacy genai_token_consumption (deprecated)
tool_execution(*, agent_id, tool_name, session_id, user_id, status, duration_ms, error_reason=None) Legacy mcp_tool_execution (deprecated)

class BaggageSpanProcessor(opentelemetry.sdk.trace.SpanProcessor)

When a span starts, copies the baggage entries caller.project_id and caller.agent_name onto it as attributes.

Legacy event schemas

The current Layer 4 log sinks, log-based metrics and dashboards key on jsonPayload.event, so the plugin keeps writing these events (ESMERALDA_LEGACY_TELEMETRY_EVENTS, on by default) next to the esmeralda.usage records. New consumers select jsonPayload.schema = "esmeralda.usage" instead.

genai_token_consumption:

{
  "event": "genai_token_consumption",
  "session_id": "...", "user_id": "...", "agent_id": "support_assistant",
  "execution_path": "support_assistant@1", "turn_index": 1,
  "trace_id": "<32 hex>", "span_id": "<16 hex>",
  "model": "gemini-...",
  "tokens": {"prompt_tokens": 100, "completion_tokens": 50, "thoughts_tokens": 20, "cached_tokens": 40, "total_tokens": 170},
  "implicit_caching": {"cache_hit": true, "cache_hit_ratio": 0.4},
  "finish_reason": "STOP"
}

mcp_tool_execution:

{
  "event": "mcp_tool_execution",
  "session_id": "...", "user_id": "...", "agent_id": "order_ops_specialist",
  "tool_name": "get_order", "status": "SUCCESS", "duration_ms": 182.4,
  "trace_id": "<32 hex>", "span_id": "<16 hex>",
  "error_reason": "TimeoutError: ..."
}

error_reason is present only when status is ERROR. trace_id and span_id are unknown_trace / unknown_span outside a span.

esmeralda.certs

Agent Gateway trust.

Name Description
parse_bundle(raw) -> list[str] The PEM certificates in raw. Literal \n sequences are accepted
install_gateway_ca(environ=os.environ, *, system_dir=SYSTEM_CA_DIR, certifi_path=None, update_command=UPDATE_COMMAND) -> int Writes each certificate to system_dir/agw-<n>.crt and runs update-ca-certificates, if both exist (otherwise logs a warning). Appends missing certificates to the certifi bundle. Returns the number of certificates; 0 (with a warning) if the variable is unset. Raises ValueError if it is set but holds no certificate. Safe to run twice
ENV_VAR AGENT_GATEWAY_ROOT_CERTIFICATES
SYSTEM_CA_DIR /usr/local/share/ca-certificates
UPDATE_COMMAND ("update-ca-certificates",)

esmeralda command line (esmeralda.cli)

esmeralda run -- <command> [args...]
  1. Runs install_gateway_ca() and prints ✅ Installed N Agent Gateway root certificate(s) from AGENT_GATEWAY_ROOT_CERTIFICATES.
  2. Replaces itself with <command> (exec), so the server keeps PID 1 and receives signals directly.

Exit codes (when it doesn't exec): 2 for a usage error, 1 if the certificate bundle is invalid. Other failures (for example update-ca-certificates failing) stop the container with a traceback.

esmeralda query [--agent-dir DIR] [--url URL | --engine RESOURCE | --local-mcp] [--user ID] [--session ID]
                [--caller PROJECT/AGENT] [--timeout SECONDS] [--fail-on-tool-error] [--verbose] MESSAGE
Option Default Description
--agent-dir . Agent directory, with agent.yaml and the agent package
--url A running server. ADK: POST <url>/api/stream_reasoning_engine. A2A: card at <url>/v1/card (or /.well-known/agent-card.json), then message:send
--engine projects/P/locations/L/reasoningEngines/ID. ADK: :streamQuery. A2A: <engine>/a2a. Authenticated with ADC, else gcloud auth print-access-token
--local-mcp off In-process run with the local MCP servers up: starts the servers whose localhost:<port> URLs are in local_env (esmeralda.local_mcp.SERVERS, bound to 127.0.0.1, logs in .esmeralda/local-mcp/), waits for /health, and stops them after the query, also on Ctrl+C. Servers already running are reused and left running. Exit code 1 if a server doesn't start
--user esmeralda-cli User id
--session new session Session id (ADK) or context id (A2A) to continue
--caller <project>/esmeralda_cli Caller context. The project comes from GOOGLE_CLOUD_PROJECT, else ADC
--timeout 300 HTTP timeout, in seconds
--fail-on-tool-error off Also fail when a tool call returned an error
--verbose off Print raw events and tracebacks

Without --url or --engine, the agent runs in-process with env + local_env applied. Exit codes: 0 passed, 1 failed run (including failed toolset loads), 2 usage or configuration error (including empty --url or --engine). Toolset load failures are only detected for in-process runs (with --url or --engine, toolsets load on the server).

esmeralda serve [--agent-dir DIR] [--host HOST] [--port PORT] [--local | --local-mcp] [--web] [--otel-to-cloud]
Option Default Description
--agent-dir . Agent directory, with agent.yaml and the agent package
--host 0.0.0.0 Bind address
--port $PORT, else 8080 Port
--local off Apply local_env (workstation runs). Without it, only env is applied, as defaults
--local-mcp off --local, plus the local MCP servers up while the agent serves: starts the servers whose localhost:<port> URLs are in local_env (as query --local-mcp), and stops them when the server stops, also on Ctrl+C. Servers already running are reused and left running. Exit code 1 if a server doesn't start
--web off ADK dev UI (adk web) instead of the API server. ADK agents only
--otel-to-cloud off Export traces and logs to Google Cloud (--otel_to_cloud for ADK; the GCP exporters for A2A)

ADK agents: replaces itself with adk api_server <dir> --host --port --no-reload --gemini_enterprise_app_name agent [--otel_to_cloud] (with --local-mcp, runs it as a child process instead, so the MCP servers can be stopped afterwards). A2A agents: runs uvicorn with esmeralda.serve.a2a_server(config). Exit code 2 for a usage or configuration error.

esmeralda mcp [--repo PATH]

Read-only MCP server on stdio (fastmcp). The repository root is --repo, else ESMERALDA_REPO, else the checkout containing the working directory (the first parent with infrastructure/live/root.hcl). Exit code 2 when there is no checkout or fastmcp is not installed. Tools: see Operating a checkout from an agent.

Operational CLI subcommands

Every operational subcommand accepts --repo PATH (defaults to $ESMERALDA_REPO or the git checkout root) and --json for machine-readable JSON output:

esmeralda status [--env dev|prd] [--unit UNIT [--output NAME]] [--json] [--repo PATH]
esmeralda doctor [--env dev|prd] [--json] [--repo PATH]
esmeralda units [--env dev|prd] [--layer 0..5] [--json] [--repo PATH]
esmeralda plan [<unit> | --all] [--env dev|prd] [--json] [--repo PATH]
esmeralda apply <unit> [--env dev|prd] [--allow-destroy] [--allow-local-state] [--json] [--repo PATH]
esmeralda deploy [<unit>... | --layer N... | --all] [--env dev|prd] [--allow-destroy] [--allow-local-state] [--timeout 1800] [--dry-run] [--skip-build] [--skip-tests] [--skip-verify-images] [--tag TAG] [--cicd-dir DIR] [--json] [--repo PATH]
esmeralda destroy --env dev --confirm dev [--dry-run] [--timeout 1800] [--json] [--repo PATH]
esmeralda build <agents|services|images|package|IMAGE> [--tag TAG] [--skip-tests] [--dry-run] [--jobs N] [--timeout 3600] [--cicd-dir DIR] [--json] [--repo PATH]
esmeralda build --verify [--env dev|prd] [--json] [--repo PATH]
esmeralda lock [PKG...] [--dry-run] [--timeout 1200] [--cicd-dir DIR] [--json] [--repo PATH]
esmeralda lock --check [--json] [--repo PATH]
esmeralda lock --terraform [--timeout 1200] [--json] [--repo PATH]
esmeralda lock --terraform --check [--json] [--repo PATH]
esmeralda release status [--env prd] [--repo PATH]
esmeralda release promote --version vX.Y.Z --source dev-<gitsha> [--verified YYYY-MM-DD] [--env prd] [--repo PATH]
esmeralda verify [--env dev|prd] [--scenario store|factory|all] [--runtime auto|vm|gke] [--team TEAM] [--keep-agent] [--probe NAME] [--skip-query] [--skip-catalog] [--catalog-strict] [--partner] [--model-armor] [--json] [--repo PATH]
esmeralda logs <target> [--env dev|prd] [--minutes 30] [--severity DEFAULT] [--limit 50] [--json] [--repo PATH]
esmeralda contracts [--section all|entrypoint|gateway_adapter|agent_card|env_yaml] [--json] [--repo PATH]
esmeralda guard [--staged | --diff RANGE | --all | --message-file FILE] [--json] [--repo PATH]
esmeralda state status [--env all|shared|dev|prd] [--json] [--repo PATH]
esmeralda state migrate [--bucket NAME] [--env all|shared|dev|prd] [--dry-run] [--yes] [--write-env] [--backup-dir DIR] [--timeout 600] [--json] [--repo PATH]
Subcommand Backed by Description
status esmeralda.ops.repo.status / infra.status Git branch, HEAD SHA, dirty/clean state, active worktrees, local state units, image tags/digests vs HEAD, and deployed environment outputs. With --unit <unit> --output <name> it prints only that output's raw value (for scripts, e.g. engine_id)
doctor esmeralda.ops.repo.doctor Preflight check: required tools (git, python3 >= 3.10, uv, terraform >= 1.5, terragrunt, gcloud, jq), the user-local env file and the source of ESMERALDA_BILLING_ACCOUNT (warns if unset), ESMERALDA_ORG_ID and ESMERALDA_ALERT_EMAIL (values never printed; a missing file or billing account points to the template infrastructure/esmeralda.env.example, see the env file), ADC token, uv.lock check (offline, as lock --check), local state readability, and the state backend (state_backend: warns, with the exact esmeralda state migrate --bucket <bucket> --write-env command, while the env uses local state although Layer 0 exports tfstate_bucket_name). Exits non-zero if required checks fail
units esmeralda.ops.infra.list_units Lists Terragrunt units for <env>, their layer (0..5), dependencies, whether enabled/excluded in env.yaml, and whether local state exists
plan esmeralda.ops.infra.plan_unit Runs read-only terragrunt plan -lock=false on a unit (full path or short name such as entrypoint; shared/layer-0-cicd or layer-0-cicd for Layer 0) or --all enabled units, and prints the resource change summary (to add, to change, to destroy, to replace). Like apply and deploy, it runs every unit with the exact provider versions of infrastructure/versions.yaml (pinned by root.hcl, with the committed infrastructure/.terraform.lock.hcl; see lock --terraform)
apply esmeralda.ops.infra.apply_unit Plans <unit> to a planfile first, inspects the plan for destroy or replace actions, refuses to apply with exit code 2 if destroy > 0 unless --allow-destroy is passed, and otherwise applies the saved planfile. Accepts shared/layer-0-cicd (alias layer-0-cicd). Local-state guard: while the env uses local state although Layer 0 exports tfstate_bucket_name, every unit other than shared/layer-0-cicd is refused with exit code 2 before any Terragrunt call, with the esmeralda state migrate command to run, unless --allow-local-state is passed (plan only warns on stderr; skipped when the Layer 0 state can't be read). See Remote state
deploy esmeralda.ops.deploy.deploy Applies units one at a time through the same path as apply (planfile + destroy guard + local-state guard per unit; --allow-local-state as for apply), stops at the first failure or refusal, and prints a summary. Targets: named units (applied in dependency order); --layer N (repeatable): 0 = shared/layer-0-cicd (refused from a git worktree whose layer-0 state lives in the main checkout, unless --cicd-dir), 1–4 = layer-1-projects, layer-2-networking, layer-3-security, layer-4-governance, 5 = every enabled layer-5-workloads unit in Terragrunt dependency order with iap-egress last, then the running-image check (build --verify; skip with --skip-verify-images); --all = L0 → L1–L3 → L4 → image builds (tests first unless --skip-tests, none with --skip-build) → L5. --dry-run plans every unit read-only and prints the build commands. Make aliases: deploy-cicd, deploy-projects, deploy-networking, deploy-security, deploy-foundations, deploy-governance, deploy-workloads, deploy-services, deploy-agents, deploy-gateway, deploy-entrypoint, deploy-iap-egress, deploy-all
destroy esmeralda.ops.deploy.destroy Destroys an environment's Layers 5 → 1 unit by unit. Requires --confirm <env> (the env name again), refuses prd, and never touches Layer 0. --dry-run lists the units in order. Make alias: destroy-all
build esmeralda.ops.build.build_images / build_package, esmeralda.ops.release.verify_images Builds images with Cloud Build in the shared CI/CD project (settings from the layer-0 outputs; a worktree without layer-0 state reads the main checkout's, override with --cicd-dir) and pushes them as :dev-latest (or --tag / $BUILD_TAG) and :dev-<gitsha>. Targets: agents, services, images (services, then agents), package (standalone wheel and sdist into dist/), or one image: orders-service, notifications, customers, envoy-gateway, order-ops-specialist, support-assistant. Agent builds run make lock-check test test-terraform first unless --skip-tests. Logs go to .esmeralda/build-logs/. --verify --env <env> checks that every Layer 5 workload runs the expected digest: the one in release/<env>.yaml, or the digest of its container_tag when there is no manifest; running digests come from the Cloud Run revisions serving traffic and the Agent Runtime engines' container spec (--json for a structured result). Make aliases: build-*, build-package, verify-images
lock esmeralda.ops.lock.lock / check Regenerates uv.lock against public PyPI: uploads the workspace pyproject.toml files and uv.lock to Cloud Build in the shared CI/CD project (settings from the layer-0 outputs, as build), runs uv lock there (PKG arguments, NAME or NAME==VERSION, are also upgraded), and writes the new uv.lock into the working copy for review; nothing is committed. --check only runs the offline check uv lock --check --offline --default-index https://pypi.org/simple (the same check as doctor and the pre-push hook) and exits 1 if uv.lock is out of date. --terraform (esmeralda.ops.provider_lock) works on the Terraform providers instead: it regenerates the single committed lock file infrastructure/.terraform.lock.hcl from the exact versions in infrastructure/versions.yaml (terraform providers lock for linux_amd64, darwin_arm64 and darwin_amd64; registry access, no Terragrunt, no state); with --check it only verifies, offline, that the lock has exactly the pinned providers and versions with a checksum per platform (also tests/guards/test_provider_versions.py). Make aliases: lock, lock-check
release esmeralda.ops.release.status / promote status shows release/<env>.yaml (version, source, digests) and the shared repositories (--json available); promote copies every image tagged --source dev-<gitsha> by digest into the immutable release repository as --version and writes release/<env>.yaml (all-or-nothing: every tag is checked before anything is copied, an existing tag with another digest is refused; --verified defaults to today; --dry-run copies and writes nothing; no deploy). Make aliases: status-release, promote
verify esmeralda.ops.runtime.verify / verify_factory.verify_factory Runs gateway conformance probes (runtime.test_gateway, optionally filtered by --probe), the Agent Registry egress check, the catalog-drift step (runtime.verify_catalog_drift, backed by esmeralda.catalog.commands.drift_report: catalog diff findings, offline plus live for each enabled snapshot source, counted per kind; warning only unless --catalog-strict or policy.verify.catalog_drift: fail; an unreachable source is a notice; skipped with --skip-catalog or --probe) and, unless --skip-query is passed, runs remote queries against order-ops-specialist and support-assistant (or with --partner, runs Apigee partner conformance checks via runtime.test_partner; with --model-armor, runs esmeralda.ops.model_armor.verify_model_armor; with --scenario factory, runs esmeralda.ops.verify_factory.verify_factory against the Scion Hub and BigQuery usage_events for --runtime auto|vm|gke, optional --team, and --keep-agent). --json includes the full structured report. Exits non-zero if any check fails
logs esmeralda.ops.logs.agent_logs Pulls recent Cloud Logging entries for an agent (Reasoning Engine) or MCP/gateway service (Cloud Run), collapsing tracebacks and deduplicating repeats
contracts esmeralda.ops.contracts.describe_contracts Prints architectural contracts (all, entrypoint, gateway_adapter, agent_card, env_yaml)
guard esmeralda.ops.guard.run_guard Public-repository sensitive-content scanner across --staged changes, --diff <range>, --all tracked files, or --message-file. Exits non-zero if any secret, forbidden path, or internal/customer marker is detected. Committed catalog snapshots (*/snapshots/*.json, or any JSON file with the esmeralda.catalog.snapshot header) are also rejected when they hold a raw 12-digit project number, an organization or folder id, an email or IAM member, or a token-like string
state esmeralda.ops.state.state_status / migrate status reports the active Terraform backend (local vs gcs), ESMERALDA_STATE_BUCKET configuration, Layer 0 tfstate_bucket_name discovery, and local state files across environments. migrate resolves the target bucket (--bucket > ESMERALDA_STATE_BUCKET > layer-0-cicd tfstate_bucket_name), previews the ordered plan with --dry-run, and with --yes writes a 0700 backup outside the repo before running terragrunt init -migrate-state -force-copy per unit (shared/layer-0-cicd → dev/* → prd/*); --write-env persists ESMERALDA_STATE_BUCKET in ~/.config/esmeralda/env (chmod 600) after a clean migration

Catalog subcommands

esmeralda catalog resolve [--env ENV|all] [--format json|hcl|terraform] [--write | --check] [--repo PATH]
esmeralda catalog show [--env ENV] [--target NAME] [--caller NAME] [--provenance] [--inventory] [--format table|tree] [--legend|--no-legend] [--json] [--repo PATH]
esmeralda catalog sources [--env ENV] [--json] [--repo PATH]
esmeralda catalog fetch --source NAME|all [--env ENV] [--dry-run] [--json] [--repo PATH]
esmeralda catalog diff [--env ENV] [--live] [--json] [--repo PATH]
Subcommand Backed by Description
catalog resolve esmeralda.catalog.resolve / write_resolved / check_resolved Merges the sources of catalog/sources.yaml, applies environments/<env>.yaml, validates, and prints the resolved catalog (json), the Terraform map (hcl) or the .resolved/<env>.json content (terraform). --write regenerates catalog/.resolved/<env>.json, --check exits 1 when it is stale. Offline: external sources are read from their snapshots only. Exit 2 on a catalog error
catalog show esmeralda.catalog.show Who can call each target, through which gateway, and who pays. Shows a two-level layout per target (route: printed once when catalog gateway and deployed env.yaml ingress agree, or both highlighted when they differ), status badges ([example], [not compiled], [adopted from ...], [enforced]/[declared only]), an aligned callers table (--format table, default) or compact --format tree, a one-line summary, and a field legend (--no-legend to omit). --provenance adds where each entry and each externally contributed field came from (source, origin, strategy, shadowed values) and, without --target/--caller, the teams with their projects; --inventory lists the discovered entries no catalog file adopts (never compiled) instead
catalog sources esmeralda.catalog.commands.describe_sources Every source in merge order, enabled or not: type, capabilities and, for snapshot sources, the snapshot path, status (ok, missing with the fetch command, invalid), sha256 and entry count. Offline. Exit 1 on an error
catalog fetch esmeralda.catalog.commands.fetch_sources Calls the adapter's fetch() of one source (enabled or not) or of every enabled snapshot source (all), normalizes the result (entries and keys sorted, volatile fields dropped, environment literals as placeholders, no timestamp) and writes catalog/snapshots/<source>/<env>.json, reporting added, removed and changed entry ids. Every source is fetched before anything is written. --dry-run writes nothing. Refuses a snapshot that still holds an environment literal or a secret-like string. Exit 2 when a live source is unreachable (nothing written), 1 on any other error
catalog diff esmeralda.catalog.commands.diff_catalog Findings for review: discovered entries no catalog file adopts, shadowed / overridden external values, label_mismatch where source data (project labels) disagrees with the catalog files (listed whatever policy.attribution.label_mismatch says), missing_snapshot for optional sources and, with --live (network, never written), live_drift per entry that changed since the snapshot and missing per Agent Registry entry the compiled catalog registers that the live registry doesn't list. Exit 0 with no finding, 3 with findings, 2 when a live source is unreachable, 1 on an error

Built-in snapshot sources (esmeralda.catalog.adapters): project_labels (team attribution from the labels of the environment's projects; fills teams.<team>.projects and the owner_team of discovered inventory, compiles attribution.project_teams, never creates teams or cost centres) and agent_registry (agents, MCP servers and endpoints of Agent Registry as discovered inventory, excluding what Esmeralda registers; never compiled, adopted only through a deploy.registry pin; catalog diff --live adds missing registry entries). An adopted Agent Runtime agent compiles into adopted_targets (esmeralda.catalog.compile_adopted_targets: a governance registry entry on the engine's URLs, esmeralda.catalog.engine_urls) and, as a caller, into a principal derived from its runtime resource (esmeralda.catalog.runtime_principal).

Factory subcommands

esmeralda factory bootstrap [--env ENV] [--team TEAM] [--broker NAME [--set-default-broker]] [--reconciler-sa EMAIL] [--git-remote URL] [--no-default-scratchpad] [--dry-run] [--auth auto|sa|iap|tunnel|token] [--sa EMAIL] [--iap-audience CLIENT_ID] [--impersonate-sa EMAIL] [--json] [--repo PATH]
esmeralda factory status [--env ENV] [--team TEAM] [--auth auto|sa|iap|tunnel|token] [--sa EMAIL] [--iap-audience CLIENT_ID] [--json] [--repo PATH]
esmeralda factory sync [--env ENV] [--team TEAM] [--dry-run [--offline]] [--auth ...] [--sa EMAIL] [--iap-audience CLIENT_ID] [--skill-version X.Y.Z] [--json] [--repo PATH]
esmeralda factory start --team TEAM --agent AGENT [--issue N] [--task TEXT] [--role ROLE] [--dry-run] [--env ENV] [--auth ...] [--sa EMAIL] [--iap-audience CLIENT_ID] [--json] [--repo PATH]
esmeralda factory reconcile [--env ENV] [--team TEAM] [--day YYYY-MM-DD] [--hub-file FILE] [--usage-file FILE] [--auth ...] [--sa EMAIL] [--iap-audience CLIENT_ID] [--json] [--repo PATH]
esmeralda factory logs AGENT [--tail N] [--team TEAM] [--env ENV] [--auth ...] [--sa EMAIL] [--iap-audience CLIENT_ID] [--json] [--repo PATH]
esmeralda factory look AGENT [--lines N] [--team TEAM] [--env ENV] [--auth ...] [--sa EMAIL] [--iap-audience CLIENT_ID] [--json] [--repo PATH]
esmeralda factory conversations [AGENT] [--limit N] [--full] [--team TEAM] [--env ENV] [--auth ...] [--sa EMAIL] [--iap-audience CLIENT_ID] [--json] [--repo PATH]
esmeralda factory inspect AGENT [--out DIR] [--no-workspace] [--last N] [--team TEAM] [--env ENV] [--json] [--repo PATH]
Subcommand Backed by Description
factory bootstrap esmeralda.ops.factory_bootstrap.bootstrap Idempotent, zero-touch Scion Hub bootstrap from the catalog and Terraform outputs (recommended with --auth sa using the hub's headless factory_admin_sa_email SA — zero browser, zero OAuth secret, zero manual UI clicks): disables default_scratchpad when GKE is enabled (or --no-default-scratchpad), creates missing team projects (POST /api/v1/projects), registers and verifies every compiled (team x agent) GCP service account, grants least-privilege project-viewer to sa-factory-reconcile-<env> (printing the one-line gcloud run jobs execute hint if the user is not auto-provisioned yet), attaches an online --broker as a provider (and sets it as default with --set-default-broker), runs factory sync, and reports any project missing a GitHub App installation with its direct UI URL. --dry-run changes nothing. Exit 0 ok, 1 if any step failed, 2 on error
factory status esmeralda.ops.factory.status Hub health and the signed-in user, then per team Scion project of the catalog (factory_projects): drift between the catalog and the hub (missing project, env vars missing or outdated, service accounts not registered or verified, settings, skill not published or not auto-injected, templates missing or outdated by file manifest, a stored GITHUB_TOKEN secret). [manual] items need the hub UI. Exit 0 in sync, 3 with drift, 2 on an error
factory sync esmeralda.ops.factory.sync Fixes every non-manual drift item, in order: env vars, service accounts (register + verify), settings (defaultHarnessConfig, assign mode with the team's lead account as default), skill, templates. Idempotent (a second run writes nothing) and never starts agents. --dry-run lists what would change; --dry-run --offline prints the desired state without contacting the hub. Exit 1 when an item failed
factory start esmeralda.ops.factory.start Starts one run of --agent in the --team project with that team's service account for the agent (gcp_identity assign), labels esmeralda-team/esmeralda-agent/esmeralda-issue, role full for the lead (use --auth iap for role=full, since Scion User Access Tokens cannot carry project.secret_read); prints the run id and link. --dry-run prints the request
factory reconcile esmeralda.ops.factory_reconcile Read only: compares a day's (default yesterday, UTC) recorded run origin in usage_events (run_root, run_parent, run_scion_project, billing_team, run_initiated_by, run_origin) with the hub's agents and ancestry per team project, and lists each discrepancy (unknown root or parent, parent outside the tree, project, payer, initiator or origin mismatch). --hub-file / --usage-file read exports instead of the hub / BigQuery. Exit 0 clean, 3 with discrepancies, 2 on an error
factory logs esmeralda.ops.factory_debug.logs The agent's agent.log, relayed hub → broker (GET /api/v1/projects/{id}/agents/{agent}/logs, the endpoint scion logs reads), last --tail lines (default 100, 0 for all). Works for stopped agents
factory look esmeralda.ops.factory_debug.look The agent's current terminal (tmux capture-pane through the hub's exec endpoint, what scion look runs; --lines adds scrollback), or the screen the hub saved at its last suspend. A stopped agent has no terminal: it prints why and exits 1
factory conversations esmeralda.ops.factory_debug.conversations Per team project: every agent (or just AGENT) with its phase, template, creator, lineage (ancestry) and initial task (appliedConfig.task); the project's conversations with their last --limit messages; and your hub notifications (state changes, input needed). Reading conversations and notifications with a Scion token needs its inbox:read scope; without it, the agents and tasks still print, with a warning
factory inspect esmeralda.ops.factory_debug.inspect Post-mortem of a stopped agent, strictly read-only: over IAP SSH to the hub VM it lists the agent's container, copies its gemini-cli session history (the session files in the agent's gemini-cli home), task.md, session-metrics.json and docker logs out with docker cp, and, unless --no-workspace, computes git status, log, stash and the diffs (uncommitted, and commits ahead of origin) on a throwaway copy of /workspace (heavy caches left out, the copy's git config replaced so nothing in the repository can run). Never starts a container or runs anything in one, and never copies the Scion token or harness secrets. Writes to --out (default ~/.cache/esmeralda/factory-inspect/<agent>/<UTC time>/, mode 0700; refused inside the repository) and prints model calls, tokens, tool calls by tool, the last --last actions, tool calls waiting for confirmation or never finished, the exit reason and the workspace changes

The hub URL, VM, headless admin SA and factory project come from the factories/scion-hub, factories/scion-reconcile, and layer-1-projects outputs (a worktree without state reads the main checkout's, or pass --state-repo). --auth: sa (headless IAP via Proxy-Authorization and IAM Credentials signJwt with zero OAuth client or browser — defaults to factories/scion-hub output factory_admin_sa_email, overridable via --sa or ESMERALDA_FACTORY_HUB_SA), iap (you, through IAP via Proxy-Authorization: Bearer <id_token>, acting as an interactive web session with full admin authority — for human operators, Desktop OAuth PKCE with ESMERALDA_FACTORY_HUB_OAUTH_CLIENT_ID / _SECRET; for service accounts or impersonation, gcloud auth print-identity-token with --iap-audience / ESMERALDA_FACTORY_IAP_CLIENT_ID / ESMERALDA_FACTORY_BROKER_IAP_CLIENT_ID and optional --impersonate-sa / ESMERALDA_FACTORY_IAP_IMPERSONATE_SA), tunnel (an IAP SSH port forward to the VM plus a Scion User Access Token from ESMERALDA_SCION_HUB_TOKEN), token (the token straight to --hub-url); auto picks iap or --sa when explicitly configured, else tunnel when a Scion token is set, else sa when ESMERALDA_FACTORY_HUB_SA or factory_admin_sa_email is available. All values come from the user-local env file and are never printed. inspect needs no hub credentials, only gcloud compute ssh access to the hub VM through IAP. When --team is omitted, logs, look and conversations search every team project of the catalog.

esmeralda.ops

The functions behind the operational CLI subcommands and esmeralda mcp, usable from scripts. Each returns a small JSON-serialisable dict and raises esmeralda.ops.OpsError with an actionable message.

Name Description
repo.repo_root(start=None) ESMERALDA_REPO, else the nearest checkout at or above start (default: cwd)
repo.status(root, env="dev") / repo.doctor(root, env="dev") Combined git/worktree/image/infra status; workstation preflight checks
repo.units(root, env) / repo.unit_state(root, env, unit) Unit paths of an env; a unit's non-sensitive outputs and managed resource count (local state, else terragrunt output -json)
infra.status(root, env, unit=None) / infra.list_units(root, env, layer=None) Environment/unit outputs; unit catalog with layer, dependencies, enabled/excluded, and local_state
infra.plan_unit(root, env, unit) / infra.summarize_plan(plan_json) Read-only plan of a unit (or --all); the summary of a terraform show -json plan document
infra.apply_unit(root, env, unit, allow_destroy=False) Plan-first apply of a unit with the destroy guard (returns refused=True, exit_code=2 when destroy > 0 without allow_destroy)
deploy.layer_steps(root, env, layer) / deploy.all_steps(root, env) / deploy.unit_steps(root, env, names) / deploy.deploy(root, env, steps, opts) The ordered steps of a layer, of a full environment, or of named units; runs them through infra.apply_unit, stopping at the first failure
deploy.destroy_order(root, env) / deploy.destroy(root, env, ...) Layers 5 → 1 in reverse dependency order; the dev-only destroy (refuses prd, never Layer 0)
build.select(target) / build.build_images(root, ...) / build.build_package(root) Image batches for a build target; Cloud Build submission; the standalone package build
release.verify_images(root, env) / release.status(root, env) / release.promote(root, version=..., source=...) The running-image check; release status; promotion by digest (all return dicts, echo streams the human report)
release_manifest.render(...) / parse(text) / load(path) Writer and reader of release/<env>.yaml (standard library only)
runtime.query_agent(root, env, agent, message) (async) / runtime.test_gateway(root, env, probe=None) / runtime.verify(root, env, probe=None, skip_query=False, skip_catalog=False, catalog_strict=False) (async) / runtime.verify_catalog_drift(root, env, strict=False) Remote query through esmeralda.query.run; gateway probes from the test VM (scripts/vm/gateway_probes.sh) parsed per host; end-to-end verification; the catalog-drift step (never raises)
testvm.resolve(root, env) / testvm.run(vm, script, vars=, files=) The test VM (name, zone, project), entry point IP and domain, and internal Root CA from the unit outputs; runs a bash payload on the VM over IAP SSH (variables and base64 files sent on stdin)
partner_load.main(argv) (python -m esmeralda.ops.partner_load) make load-test-partner: runs scripts/vm/partner_load.sh (Locust) on the test VM against the partner front door, copies the CSV and HTML reports back to tests/load_test/.results/partner/ and prints a per-scenario summary
logs.agent_logs(root, env, agent, since=, minutes=, severity=, limit=) / logs.reduce_entries(entries, limit) Reasoning Engine or Cloud Run logs; the collapse / dedupe step on {time, severity, payload} entries
contracts.describe_contracts(root, section_name="all") Architectural contract sections (entrypoint, gateway_adapter, agent_card, env_yaml) and each env's gateways block
guard.run_guard(root, mode="staged", diff_range=None, message_file=None) Public-repository sensitive-content and forbidden-path scanner
server.build_server(root=None) The FastMCP server (tests use it with the in-memory fastmcp.Client)

esmeralda.serve

Name Description
serve(config, *, host="0.0.0.0", port=None, local=False, web=False, otel_to_cloud=False) Serves the agent, as the CLI does
adk_command(config, *, host, port, web=False, otel_to_cloud=False) The adk command line for an ADK agent
a2a_server(config, *, otel_to_cloud=False) The FastAPI app for an A2A agent: the package's app behind the A2A REST transport, mounted at /, /a2a and /api/a2a. Uses the package's a2a_task_store_builder if it has one, else InMemoryTaskStore (warns if resources.max_instances > 1 without a custom builder)
agent_card(config) The A2A AgentCard from agent.yaml agent_card. A2A_AGENT_URL overrides url; missing fields get defaults
session_service() VertexAiSessionService when GOOGLE_CLOUD_AGENT_ENGINE_ID is set and USE_IN_MEMORY_SESSIONS isn't 1; else InMemorySessionService
install_caller_guard(server) -> bool Adds attribution.CallerGuard when ESMERALDA_CALLER_ALLOWLIST is set, except on Agent Runtime (the container never sees the caller's credential; the Agent Gateway record attributes those calls). Called by a2a_server

esmeralda.config

class AgentConfig

AgentConfig.load(directory=".") reads <directory>/agent.yaml.

Field From agent.yaml Description
name name Deployment name (defaults to the directory name)
framework framework google-adk (default) or a2a; anything else raises ValueError
env env Environment of the deployed agent (values as strings; booleans as true/false)
local_env local_env Overrides for local runs only
agent_card agent_card A2A agent card

apply_local_env(environ=os.environ) sets env, then local_env, without overriding variables already set.

esmeralda.query and esmeralda.report

Name Description
Query(message, user_id="esmeralda-cli", session_id=None, caller=None, timeout=300.0) One query
run(config, query, report, *, url=None, engine=None) Runs the query on the chosen target and feeds the report
load_package(config) Imports the agent package (agent) from the agent directory
load_app(config) The package's app (or its root_agent wrapped with create_app)
parse_caller("project/agent") A CallerContext
Report(stream=sys.stdout, verbose=False) Renders ADK events (adk_event) and A2A tasks (a2a_task); summary(fail_on_tool_error=False) prints the result and returns the exit code. answer, authors, tool_names, tool_errors, tokens and failures() hold the result for programmatic use

Environment variables

Variable Read by Effect
AGENT_GATEWAY_ROOT_CERTIFICATES esmeralda run PEM bundle to trust. Injected by Terraform (Layer 4 output agw_root_ca_bundle)
AGENT_NAME Plugin, current_identity, usage.Workload.from_env Agent name in telemetry and in outgoing caller context
GOOGLE_CLOUD_PROJECT default_environment, genai_client_defaults, current_identity Set from ADC if missing
GOOGLE_CLOUD_LOCATION default_environment Defaulted to global if missing
GOOGLE_GENAI_USE_VERTEXAI default_environment Defaulted to True if missing
GRPC_DNS_RESOLVER default_environment Defaulted to native if missing
MODEL_LOCATION genai_client_defaults Location for every genai client (for example global)
MODEL_NAME Plugin Fallback model in token events and usage records, when neither the request nor the response names one
*_PROXY log_egress_proxy Logged at startup
SERVICE_ACCOUNT_EMAIL auth.id_token, auth.access_token Deprecated opt-in: service account to impersonate for ID and access tokens. Unset by default (agents use their own Agent Identity); Terraform sets it only with legacy_shared_invoker = true
ACCESS_TOKEN_HOSTS auth.token_kind Comma-separated hostnames that take an access token instead of an ID token (agent hosts served by direct; set by Terraform from the service catalog)
ESMERALDA_REPO esmeralda mcp, esmeralda.ops Repository root (default: the checkout containing the working directory)
USER_AUTH_ID context.user_token, usage.redact Gemini Enterprise authorization id of the user token (default user_auth_token); that key is never emitted in telemetry
ESMERALDA_USER_CREDENTIAL_TARGETS user_credential, mcp.headers_for, a2a.request_metadata JSON {"<host>": "<header>"}: the only hosts that receive the delegated user credential, and the header each reads (default X-User-Token). Unset or malformed: none
USER_CREDENTIAL_HEADER mcp_authz.verify_request (MCP servers) Header the server reads the user credential from (default X-User-Token)
ESMERALDA_CALLER_ALLOWLIST attribution.CallerGuard, serve.install_caller_guard JSON allowlist compiled from the catalog (attribution in catalog/.resolved/<env>.json, written by the Terraform unit). Unset: guard off. Invalid: startup error
ESMERALDA_WORKLOAD_NAME usage.Workload.from_env workload.name of usage records (default: the plugin's agent name, else AGENT_NAME, OTEL_SERVICE_NAME, K_SERVICE)
ESMERALDA_TEAM usage.Workload.from_env workload.team
ESMERALDA_RUNTIME usage.Workload.from_env workload.runtime (agent_engine, cloud_run, gke, external); detected from GOOGLE_CLOUD_AGENT_ENGINE_ID, K_SERVICE, KUBERNETES_SERVICE_HOST if unset
ESMERALDA_FRAMEWORK usage.Workload.from_env workload.framework (default set by the producer: adk for the plugin)
ESMERALDA_CLOUD usage.Workload.from_env workload.cloud (default gcp)
ESMERALDA_USAGE_TRANSPORT usage.transport_from_env stdout (default), otel, or stdout,otel
ESMERALDA_USAGE_VALIDATE usage.UsageRecorder true validates every record against the shipped schema and logs violations (needs jsonschema)
ESMERALDA_LEGACY_TELEMETRY_EVENTS Plugin false stops the legacy genai_token_consumption / mcp_tool_execution events (default on)
ESMERALDA_MODEL_GATEWAY_URL models.route_models (via create_app) Gemini base URL of the model gateway, e.g. https://apigee.esmeralda.internal/llm. Set by Terraform only when governance.capabilities.model_gateway = "apigee"; unset = direct Vertex AI calls