Skip to content

Menu

Antigravity

Use agy -p in scripts and CI: output formats, structured results, and exit codes

Run Antigravity CLI once with agy -p, pick an output format, get parseable results with --json-schema, and understand how authentication, permissions, and exit codes behave without a terminal.

min read
13
Level
Advanced
Last verified

This page is about the non-interactive use of Antigravity CLI (the agy command). After reading it, you can get a one-shot answer in a script with agy -p, retrieve parseable results with --output-format json and --json-schema, and you will know that CI cannot rely on interactive sign-in and that a refused tool call does not make the process fail. This is an independent, unofficial guide; flags, fields, and status values follow the official Headless page, and where that page is silent this page says “not documented on the official page”. The example commands were not run; only the official pages were checked.

Interactive agy gives you a terminal UI where a person approves each step. Non-interactive mode (the official docs also call it headless or print mode) sends one prompt, returns the result, and exits. Use it when a program needs the agent’s output: scripts, scheduled jobs, CI pipelines. If you are new to the CLI, start with Your first agent task; for installation and sign-in see Install and sign in to a CLI.

Pass the prompt with -p (aliases --print, --prompt); it runs once and exits:

终端窗口
agy -p "In one sentence, what is a git rebase?"

The response goes to stdout. By default a run has no time limit and waits until the turn completes; set one with --print-timeout (default 0s, meaning no limit):

终端窗口
agy -p "Summarize the design tradeoffs of optimistic locking." --print-timeout 15m

Non-interactive runs are stateless by default. To pick up earlier context, use --continue (-c) for the most recent conversation, or --conversation with a conversation_id from a previous run. Each command is a new process. The official page also offers --input-format stream-json to feed several prompts into one process; it must be paired with --output-format stream-json, and prompts can no longer be passed with -p. This page covers single runs only; for that path defer to the official page.

The official page states that the response goes to stdout, while diagnostics (errors, authentication prompts, progress, permission notices) go to stderr. So when you capture stdout with command substitution, you get a clean answer:

终端窗口
answer=$(agy -p "Name three popular version control systems, comma-separated.")

Divide the work accordingly: treat stdout as data, and leave stderr for logs or let CI display it as is. Do not merge them with 2>&1 and then try to parse the result.

--output-format sets the shape of stdout and accepts three values:

Format Shape of stdout Use it for
text (default) The response text, unwrapped Human reading, quick scripts
json One JSON object printed on completion Capturing a result plus metadata
stream-json Newline-delimited JSON events (NDJSON) Watching progress, tool calls, and token usage live

A stream-json run starts with one init event, followed by any number of step_update events, and ends with one result event whose shape matches the json envelope. Each line’s event field names its type. To concatenate the streamed text with jq, the official example uses jq -j to avoid extra newlines:

终端窗口
agy -p "Explain what a merge conflict is in two sentences." --output-format stream-json \
| jq -j 'select(.event=="step_update") | .step_update.text_delta // empty'

init records the run configuration (working directory, available tools, the effective permission mode, and so on). For step_type the official page lists “observed” values, including user_input, agent_response, tool, and checkpoint, without a full enumeration, so do not hard-code “only these four”.

--output-format json prints a single-line JSON object after the run completes; pipe it through jq to pretty-print. Fields listed on the official page:

Field Type Meaning
conversation_id string ID of the conversation, for resuming later
status string Terminal status, values below
response string The agent’s free-text response
error string Error message; present only on failure
duration_seconds number Wall-clock duration of the run
num_turns number Number of user turns in the conversation
structured_output object Parsed schema output; present only with --json-schema
json_schema object The schema that was enforced; present only with --json-schema
usage object Token counts: input_tokens, output_tokens, thinking_tokens, cache_read_tokens, total_tokens

status values and their meaning (official page):

Value Meaning
SUCCESS The run completed and produced a response
ERROR The run ended with an error
CANCELED The run was canceled
INTERRUPTED The run was interrupted (for example, SIGINT)
INVALID The run reached an invalid state
WAITING The run ended while waiting on input
RUNNING The run did not reach a terminal state

Read the response and status:

终端窗口
agy -p "Name three popular version control systems, comma-separated." --output-format json | jq -r '.status, .response'

--json-schema constrains the shape of the answer. It accepts a schema string, a path to a .json schema file, or a primitive type name (string, number, integer, boolean). The parsed object appears in structured_output, and response holds the same payload serialized as a string. The official example (fictional input):

终端窗口
agy -p "Parse the semantic version string v2.14.3 into an object with integer fields major, minor, and patch." \
--output-format json \
--json-schema '{"type":"object","properties":{"major":{"type":"integer"},"minor":{"type":"integer"},"patch":{"type":"integer"}},"required":["major","minor","patch"]}' \
| jq '.structured_output'

With stream-json, the schema applies to the final result event, which carries the same structured_output and json_schema fields as the json envelope.

Keep two things apart: a schema guarantees shape (the fields are present and typed correctly); it does not guarantee the content is right. Whether major is 2 or 3 in the example above is something you must verify with a deterministic method. For the general approach see Structured output: pass the schema first, then run semantic checks, such as value ranges, whether referenced files exist, or a cross-check against another source.

终端窗口
out=$(agy -p "Parse version v2.14.3 and return three integers: major, minor, patch." \
--output-format json --json-schema schema.json)
[[ "$(echo "$out" | jq -r '.status')" == "SUCCESS" ]] || exit 1
echo "$out" | jq -e '.structured_output | .major == 2 and .minor == 14 and .patch == 3' >/dev/null

schema.json above is your own schema file. When a semantic check fails, fail the pipeline instead of letting the result through quietly.

Authentication and behavior without a terminal

Section titled “Authentication and behavior without a terminal”

The official page says non-interactive mode uses cached credentials, so you authenticate once with an interactive agy session first. In an environment with no terminal (for example, CI), a run that is not already authenticated exits with an authentication required error instead of hanging. So:

  • Do not count on interactive sign-in in CI. There is no browser and nobody to click.
  • Two browserless paths on the authentication page (CLI part):
    • Gemini API key: set modelProvider to gemini in ~/.gemini/antigravity-cli/settings.json and export GEMINI_API_KEY in the environment. The official page states that setting only the environment variable has no effect; the CLI reads the key only from GEMINI_API_KEY in the environment and does not load .env files; at startup it only checks that the key is non-empty, so a bad key surfaces on the first conversation. Requests go directly to the Gemini API and no account session is established.
    • Application Default Credentials (ADC): generate local credentials with gcloud auth application-default login --project {GCP_PROJECT}, then set AGY_ADC_AUTH=true, optionally with GOOGLE_CLOUD_QUOTA_PROJECT and GOOGLE_CLOUD_LOCATION. The official page describes it for headless enterprise environments and automated terminal workflows.
  • How these paths affect quotas and billing is outside this page; see Accounts, plans, and quotas and the official pages.
  • Keep credentials out of the repository. In CI, inject environment variables from the platform’s secret store, and let only placeholders such as YOUR_API_KEY appear in repositories, logs, and examples; for the principles see API key safety.
  • Setting modelProvider in CI needs the config file to exist at the run user’s ~/.gemini/antigravity-cli/settings.json; how to produce it in your CI is not documented on the official page.
  • To embed the agent in a Python program rather than a command line, there is an SDK; see SDK quickstart. For the differences between entry points see Choosing an Antigravity surface.

Non-interactive mode has nobody to approve, so tool calls that need confirmation are handled by policy:

  1. By default it follows the execution mode and permission mode in your settings. The official page states that since v1.5.7, if agentMode is not set, agy -p runs in auto mode where it is available and in default mode otherwise. To keep CI behavior stable, pin the mode with --mode or agentMode in settings. When auto is unavailable (the execution modes page: it needs the terminal sandbox, which may be missing on Windows 10, earlier Windows 11 builds, and some Linux hosts or containers that block unprivileged user namespaces), --mode=auto in non-interactive mode prints a warning and continues in default mode.
  2. Actions that cannot get approval are soft-denied. Per the official page, the run continues, exits with code 0, and prints a notice to stderr naming the tool and how to allow it. This means checking only the exit code will treat “the agent could not perform the action” as success.
  3. To grant ahead of time, add action(target) rules under permissions.allow in ~/.gemini/antigravity-cli/settings.json:
{
"permissions": {
"allow": ["command(git)", "command(regex:npm run (build|lint|test))", "write_file(src/)"]
}
}

For the rule syntax and precedence (Deny > Ask > Allow) see Your first agent task and the official permissions page.

  1. --dangerously-skip-permissions auto-approves every tool permission request, including file writes and command execution. The official warning is to prefer scoped permissions.allow rules unless you fully trust the prompt and the environment. The permissions page also states that it (always-proceed), like strict, is a global override that takes precedence over execution modes. In the stream-json init event, permission_mode is request-review by default and always-proceed under this flag.

Counterexample 1: “The CI command keeps getting stuck, so add --dangerously-skip-permissions to every task.”

That removes every gate at once; a single piece of untrusted text in the prompt could lead the agent to run arbitrary commands. Rewrite: run it interactively once in a synthetic repository, note which commands are asked about, put the ones you are sure are safe into allow as precise command(...) rules, leave the rest unallowed, and pin the mode with --mode.

Counterexample 2: “Judge success by $? alone.”

With a soft-deny the exit code is 0, and the response may just say “I could not run that command”. Rewrite: use --output-format json, check status == "SUCCESS", require key fields with --json-schema, run semantic checks on structured_output, and keep stderr so the job fails when a permission notice appears.

Counterexample 3: “Merge stdout and stderr, then feed them to jq.”

Diagnostic text on stderr is not JSON, so parsing fails or, worse, parses something wrong. Rewrite: parse only stdout and redirect stderr to a log file.

Counterexample 4: “Put GEMINI_API_KEY in the repository’s .env and let the CLI read it.”

The official page says the CLI does not load .env, and the key would now be in the repository. Rewrite: inject the environment variable from the CI secret store, set modelProvider, and use only YOUR_API_KEY in examples and logs.

  • stdout and stderr are handled separately, and only stdout is parsed;
  • You use --output-format json (or the result event of stream-json) and check status == "SUCCESS";
  • You constrain the shape with --json-schema and also run semantic checks, without treating “matches the schema” as “the content is correct”;
  • The execution mode is pinned with --mode or agentMode, not left to “whatever the default is”;
  • permissions.allow grants only the minimum the task needs, with no command(*) and no permanent --dangerously-skip-permissions;
  • --print-timeout is set, rather than relying on the platform timeout as a backstop;
  • Credentials are injected from a secret store, and no real key appears in the repository, logs, or examples;
  • You have verified the authentication path (API key or ADC) in an environment with no cached sign-in.
  • Exit with authentication required: this run is not authenticated. Signing in interactively on your machine does not give another CI machine credentials; in CI use an API key or ADC and confirm that both the configuration and the environment variable are in place.
  • Startup says GEMINI_API_KEY is not set: modelProvider is gemini but the key is missing from the environment. Export the variable, or remove modelProvider.
  • --model names an unknown model: non-interactive mode does not fall back silently; it exits non-zero with status ERROR, and in the official example the exit code is 1. List valid slugs with agy models.
  • Exit code 0 but the work was not done: look for a soft-deny notice on stderr and add a precise permissions.allow rule; do not reach for the dangerous flag.
  • status is WAITING, CANCELED, INTERRUPTED, or another non-success state: the official page gives only the meaning, not an exit code for each, so decide success or failure by status and write the error field to your logs.
  • More detailed exit codes: the official page states only that success is 0 and failure is non-zero with the reason on stderr, and it gives 1 for an unknown model and 1 or 2 for certain streaming-input errors; a full exit-code table is not documented on the official page, so do not assume more in scripts.
  • Commands not run: the examples on this page were not run in a recorded environment; confirm them in a synthetic repository before wiring them into a real pipeline. In enterprise or managed environments, administrator policy governs.

Next: to see which mode and rule guards each step, go back to Your first agent task; for sign-in problems see Install and sign in to a CLI; for quotas and account types see Accounts, plans, and quotas; to embed the agent in a Python program see SDK quickstart.