diff --git a/examples/agent_demo/make_showcase.py b/examples/agent_demo/make_showcase.py index 96f23b4..ea52f2c 100644 --- a/examples/agent_demo/make_showcase.py +++ b/examples/agent_demo/make_showcase.py @@ -39,12 +39,13 @@ ("pi", "session"), ("pi", "message_update"), ("pi", "message_start"), + ("antigravity", "init"), } def sanitize(agent: str, line: str, run_dir: Path) -> str | None: event = json.loads(line) - if (agent, event.get("type")) in _DROP: + if (agent, event.get("type") or event.get("event")) in _DROP: return None text = json.dumps(event) for path in sorted({str(run_dir), str(run_dir.resolve())}, key=len, reverse=True): diff --git a/examples/agent_demo/run.sh b/examples/agent_demo/run.sh index 0b01696..b412c77 100755 --- a/examples/agent_demo/run.sh +++ b/examples/agent_demo/run.sh @@ -5,7 +5,7 @@ # export DEMO_SCENARIO=insurance # default: readmission # uv run --extra mcp python examples/agent_demo/prepare_data.py # export TABCTX_API_KEY=vp_... # your Vector gateway key -# examples/agent_demo/run.sh claude|codex|gemini|pi +# examples/agent_demo/run.sh claude|codex|gemini|antigravity|pi # uv run --extra mcp python examples/agent_demo/score.py examples/agent_demo/runs/insurance/claude # # Each run works in its own copy of the workspace (runs///) @@ -32,10 +32,10 @@ set -euo pipefail HERE=$(cd "$(dirname "$0")" && pwd) REPO=$(cd "$HERE/../.." && pwd) -AGENT=${1:?usage: run.sh claude|codex|gemini|pi} +AGENT=${1:?usage: run.sh claude|codex|gemini|antigravity|pi} case $AGENT in -claude | codex | gemini | pi) ;; -*) echo "unknown agent '$AGENT': use claude, codex, gemini or pi" >&2; exit 2 ;; +claude | codex | gemini | antigravity | pi) ;; +*) echo "unknown agent '$AGENT': use claude, codex, gemini, antigravity or pi" >&2; exit 2 ;; esac : "${TABCTX_API_KEY:?set TABCTX_API_KEY to your Vector gateway key (vp_...)}" export TABCTX_BASE_URL=${TABCTX_BASE_URL:-https://proxy.vectorinstitute.ai} @@ -114,6 +114,25 @@ codex) -c 'mcp_servers.tabctx.default_tools_approval_mode="approve"' \ "$PROMPT" transcript.jsonl ;; +antigravity) + # agy's terminal can't be turned off from here: in a scenario where the + # agents get no shell, it would get one when the others don't. + if [[ $SHELL_TOOLS != 1 ]]; then + echo "antigravity always has a shell, and this scenario gives agents none" >&2 + exit 2 + fi + # The Antigravity CLI (agy), signed in with your Google account; its MCP + # servers for this run only, in the workspace's .agents/mcp_config.json + # (no key in it: the server inherits this environment). + mkdir -p .agents + printf '{"mcpServers": {"tabctx": {"command": "%s"}}}\n' "$SERVER" >.agents/mcp_config.json + # Headless, it can't ask before each tool. --sandbox restricts its + # terminal but still lets it read any file you can (the answers too), + # so it is for local runs, not the hosted demo. + agy -p "$PROMPT" --model "${AGY_MODEL:-gemini-3.8-flash-high}" \ + --output-format stream-json --dangerously-skip-permissions --sandbox \ + transcript.jsonl + ;; gemini) mkdir -p .gemini exclude='["run_shell_command"]' diff --git a/examples/agent_demo/ui/app.py b/examples/agent_demo/ui/app.py index b52c8ed..fd356cb 100644 --- a/examples/agent_demo/ui/app.py +++ b/examples/agent_demo/ui/app.py @@ -482,7 +482,7 @@ async def _stream(run: Run): elif run.running: await asyncio.sleep(POLL_SECONDS) else: - for event in parser.feed(pending): + for event in [*parser.feed(pending), *parser.finish()]: yield _sse("event", event) break yield _sse("outcome", outcome(run)) diff --git a/examples/agent_demo/ui/runner.py b/examples/agent_demo/ui/runner.py index 45003e8..fb1cebe 100644 --- a/examples/agent_demo/ui/runner.py +++ b/examples/agent_demo/ui/runner.py @@ -63,6 +63,13 @@ "llm": "Gemini (your login)", "tools": "MCP · shell" if _SHELL else "MCP · no shell", }, + "antigravity": { + "label": "Antigravity", + "binary": "agy", + "llm": "Gemini 3.8 Flash (your login)", + # Always a shell, so only for scenarios that give agents one. + "tools": "MCP · shell" if _SHELL else "always has a shell: not this scenario", + }, "pi": { "label": "pi", "binary": "pi", @@ -73,6 +80,8 @@ def installed(agent: str) -> bool: + if agent == "antigravity" and not _SHELL: + return False # it always has a shell; run.sh refuses it here binary = os.environ.get("PI_BIN") if agent == "pi" else None return ( bool(binary and Path(binary).is_file()) diff --git a/examples/agent_demo/ui/static/actions.js b/examples/agent_demo/ui/static/actions.js index 4aa0f37..4554e5d 100644 --- a/examples/agent_demo/ui/static/actions.js +++ b/examples/agent_demo/ui/static/actions.js @@ -49,9 +49,9 @@ const Actions = (() => { if (/\.md$/i.test(path)) return { kind: "report", title: "Wrote the report" }; return { kind: "script", title: /clean/i.test(path) ? "Wrote the cleaning script" : `Wrote ${fileOf(path)}` }; } - if (/^(edit|multiedit|replace|str_replace|apply_patch|patch)$/.test(t)) return { kind: "edit", title: `Adjusted ${fileOf(path) || "a script"}` }; - if (/^(read|read_file|read_many_files|view|cat)$/.test(t)) return { kind: "look", title: `Read ${fileOf(path)}` }; - if (/^(ls|glob|grep|find|list|list_directory|search_file_content)$/.test(t)) return { kind: "look", title: "Looked around the folder" }; + if (/^(edit|multiedit|replace|str_replace|apply_patch|patch|edit_file|replace_file_content|multi_replace_file_content|sed_file)$/.test(t)) return { kind: "edit", title: `Adjusted ${fileOf(path) || "a script"}` }; + if (/^(read|read_file|read_many_files|view|view_file|cat)$/.test(t)) return { kind: "look", title: `Read ${fileOf(path)}` }; + if (/^(ls|glob|grep|find|list|list_directory|search_file_content|list_dir|find_by_name|grep_search)$/.test(t)) return { kind: "look", title: "Looked around the folder" }; const cmd = commandOf(tool, a); if (!cmd) return { kind: "other", title: a.description || tool }; if (/(?:^|[\s;&|(])(?:md5(?:sum)?|sha\d*sum|cmp|diff)\s/m.test(cmd)) return { kind: "verify", title: "Re-ran it to confirm nothing changed" }; diff --git a/examples/agent_demo/ui/transcripts.py b/examples/agent_demo/ui/transcripts.py index 84e05d0..2ffc48f 100644 --- a/examples/agent_demo/ui/transcripts.py +++ b/examples/agent_demo/ui/transcripts.py @@ -17,6 +17,7 @@ from __future__ import annotations import json +import re from typing import Any TABCTX_TOOLS = { @@ -83,6 +84,10 @@ def feed(self, line: str) -> list[Event]: def _events(self, raw: dict) -> list[Event]: raise NotImplementedError + def finish(self) -> list[Event]: + """Events held back when the transcript ends (a stopped run).""" + return [] + def _call(self, call_id: str, raw_name: str, args: Any) -> Event: name, tabctx = tool_name(raw_name) self._tools[call_id] = (name, tabctx) @@ -302,14 +307,128 @@ def _events(self, raw: dict) -> list[Event]: return events +class AntigravityParser(Parser): + """agy -p --output-format stream-json (the Antigravity CLI)""" + + # Its tools' parameters, as the other agents name them (the page reads + # command and file_path). + _FILE_TOOLS = {"write_file", "edit_file", "view_file", "read_file"} + # States a step ends in; any other (ACTIVE, PENDING, ...) is still going. + _ENDED = {"DONE", "ERROR", "FAILED", "CANCELLED", "CANCELED", "SKIPPED"} + _EXIT = re.compile(r"Command exited with code (-?\d+)\.") + + def __init__(self) -> None: + super().__init__() + self._message = "" + self._ended: set[str] = set() + self._open: str | None = None # a step without an index (to pair its end) + self._n = 0 + + def _flush(self) -> list[Event]: + text, self._message = self._message, "" + return [{"type": "message", "text": text}] if text.strip() else [] + + def finish(self) -> list[Event]: + return self._flush() # a run stopped before its result event + + def _tool(self, name: str, params: dict) -> tuple[str, dict]: + if name == "call_mcp_tool" and params.get("ServerName") == "tabctx": + return f"tabctx_{params.get('ToolName', '')}", params.get("Arguments") or {} + if name == "run_command": + return name, {"command": params.get("CommandLine", "")} + if name in self._FILE_TOOLS: + return name, {"file_path": params.get("Path", "")} + return name, params + + def _id(self, step: dict) -> str: + if step.get("step_index") is not None: + return f"{step.get('conversation_id', '')}:{step['step_index']}" + # No index: a step's updates come in a row, so pair them in order. + if self._open is None: + self._n += 1 + self._open = f"step-{self._n}" + return self._open + + def _command(self, output: str) -> tuple[str, bool]: + """A run_command's output without its header, and whether it failed + (a non-zero exit code; no code found is not a failure).""" + code = self._EXIT.search(output) + body = ( + output.partition("Command output:\n")[2] + if "Command output:\n" in output + else output + ) + if code and body is output: + body = ( + "" if "No output from the command." in output else output[code.end() :] + ) + return body.strip("\n") + ("\n" if body.strip() else ""), bool( + code and code.group(1) != "0" + ) + + def _events(self, raw: dict) -> list[Event]: + kind = raw.get("event") + if kind == "step_update": + step = raw.get("step_update") or {} + if step.get("step_type") == "agent_response": + self._message += step.get("text_delta") or "" + return self._flush() if step.get("state") == "DONE" else [] + if step.get("step_type") != "tool": + return [] + events = self._flush() + call_id = self._id(step) + state = str(step.get("state", "")) + ended = state in self._ENDED + if call_id in self._ended: + return events # a repeated end + info = step.get("tool_info") or {} + name = step.get("tool_name") or info.get("name") or "tool" + params = info.get("parameters") or {} + # Wait for the arguments: an early update may not have them yet. + if call_id not in self._tools and (params or ended): + raw_name, args = self._tool(name, params) + events.append(self._call(call_id, raw_name, args)) + if not ended: + return events + self._ended.add(call_id) + if self._open == call_id: + self._open = None + output = _text(info.get("output") or "") + error = state != "DONE" + if name == "run_command": + output, failed = self._command(output) + error = error or failed + events.append(self._result(call_id, output, error)) + return events + events = self._flush() + if kind == "result": + result = raw.get("result") or {} + if result.get("status") not in (None, "SUCCESS"): + events.append({"type": "error", "text": json.dumps(result)[:2000]}) + else: + events.append( + { + "type": "done", + "stats": { + "seconds": round(result.get("duration_seconds", 0), 1), + "turns": result.get("num_turns"), + }, + } + ) + elif kind == "error": + events.append({"type": "error", "text": json.dumps(raw)[:2000]}) + return events + + PARSERS: dict[str, type[Parser]] = { "claude": ClaudeParser, "codex": CodexParser, "gemini": GeminiParser, + "antigravity": AntigravityParser, "pi": PiParser, } def parse_lines(agent: str, lines) -> list[Event]: parser = PARSERS[agent]() - return [event for line in lines for event in parser.feed(line)] + return [event for line in lines for event in parser.feed(line)] + parser.finish() diff --git a/tests/unit/test_agent_demo_data.py b/tests/unit/test_agent_demo_data.py index 3228a1e..d56d909 100644 --- a/tests/unit/test_agent_demo_data.py +++ b/tests/unit/test_agent_demo_data.py @@ -148,3 +148,14 @@ def test_showcase_transcripts_hide_the_machine(tmp_path, monkeypatch): make_showcase.sanitize("codex", json.dumps({"type": "thread.started"}), run_dir) is None ) + + +def test_showcase_drops_the_antigravity_init_event(tmp_path): + import make_showcase + + init = json.dumps( + {"event": "init", "init": {"cwd": "/Users/jdoe/run", "model": "m"}} + ) + assert make_showcase.sanitize("antigravity", init, tmp_path) is None + step = json.dumps({"event": "step_update", "step_update": {"step_index": 1}}) + assert make_showcase.sanitize("antigravity", step, tmp_path) is not None diff --git a/tests/unit/test_agent_demo_hosted.py b/tests/unit/test_agent_demo_hosted.py index 9ef1c7a..ef4901b 100644 --- a/tests/unit/test_agent_demo_hosted.py +++ b/tests/unit/test_agent_demo_hosted.py @@ -453,3 +453,12 @@ def test_pids_of_reads_real_effective_and_saved_uids(tmp_path, monkeypatch): monkeypatch.setattr(runner_module, "PROC", tmp_path) assert sorted(runner_module._pids_of(20001)) == [7, 8] assert runner_module._pids_of(20002) == [] + + +def test_the_hosted_demo_never_offers_or_starts_antigravity(open_hosted): + module, client, started = open_hosted + client.post("/api/login", json={"key": KEY}) + ids = [a["id"] for a in client.get("/api/setup").json()["agents"]] + assert "antigravity" not in ids + r = client.post("/api/runs", json={"agent": "antigravity", **ASK}) + assert r.status_code == 403 and not started diff --git a/tests/unit/test_agent_demo_transcripts.py b/tests/unit/test_agent_demo_transcripts.py index 320e180..3fcce4a 100644 --- a/tests/unit/test_agent_demo_transcripts.py +++ b/tests/unit/test_agent_demo_transcripts.py @@ -285,3 +285,228 @@ def test_junk_lines_are_skipped(): parse_lines("claude", ["", "not json", "[1, 2]", json.dumps({"type": "other"})]) == [] ) + + +def test_antigravity(): + def step(i, state, kind, **extra): + return { + "event": "step_update", + "step_update": { + "conversation_id": "c", + "step_index": i, + "state": state, + "step_type": kind, + **extra, + }, + } + + mcp = { + "name": "call_mcp_tool", + "parameters": { + "Arguments": {"name": "m"}, + "ServerName": "tabctx", + "ToolName": "predict", + }, + } + shell = {"name": "run_command", "parameters": {"CommandLine": "wc -l x.csv"}} + events = parse_lines( + "antigravity", + lines( + {"event": "init", "init": {"model": "gemini-3.8-flash-high"}}, + step(1, "ACTIVE", "agent_response", text_delta="Let me "), + step(1, "DONE", "agent_response", text_delta="look."), + step(2, "ACTIVE", "tool", tool_name="run_command", tool_info=shell), + step( + 2, + "DONE", + "tool", + tool_name="run_command", + tool_info={ + **shell, + "output": "Created At: x\nCommand exited with code 0.\n\nCommand output:\n 2 x.csv\n", + }, + ), + step(3, "ACTIVE", "tool", tool_name="call_mcp_tool", tool_info=mcp), + step( + 3, + "DONE", + "tool", + tool_name="call_mcp_tool", + tool_info={**mcp, "output": json.dumps(RESULT)}, + ), + step( + 4, + "DONE", + "tool", + tool_name="run_command", + tool_info={ + "name": "run_command", + "parameters": {"CommandLine": "false"}, + "output": "Command exited with code 1.\n\nNo output from the command.", + }, + ), + step( + 5, + "DONE", + "tool", + tool_name="write_file", + tool_info={ + "name": "write_file", + "parameters": {"Path": "/w/report.md"}, + }, + ), + { + "event": "result", + "result": { + "status": "SUCCESS", + "duration_seconds": 12.34, + "num_turns": 1, + }, + }, + ), + ) + assert kinds(events) == [ + ("message", None), + ("tool_call", "run_command"), + ("tool_result", "run_command"), + ("tool_call", "predict"), + ("tool_result", "predict"), + ("tool_call", "run_command"), + ("tool_result", "run_command"), + ("tool_call", "write_file"), + ("tool_result", "write_file"), + ("done", None), + ] + assert events[0]["text"] == "Let me look." + assert events[1]["args"] == {"command": "wc -l x.csv"} + assert events[2]["text"] == " 2 x.csv\n" and not events[2]["error"] + assert events[3]["tabctx"] and events[3]["args"] == {"name": "m"} + assert events[4]["result"] == RESULT + assert events[6]["error"] + assert events[7]["args"] == {"file_path": "/w/report.md"} + assert events[9]["stats"] == {"seconds": 12.3, "turns": 1} + + +def test_antigravity_failure(): + events = parse_lines( + "antigravity", + lines({"event": "result", "result": {"status": "ERROR", "error": "quota"}}), + ) + assert events[0]["type"] == "error" and "quota" in events[0]["text"] + + +def _agy_step(i, state, kind="tool", **extra): + return { + "event": "step_update", + "step_update": { + "conversation_id": "c", + "step_index": i, + "state": state, + "step_type": kind, + **extra, + }, + } + + +def _shell(i, state, output=None, cmd="wc -l x.csv"): + info = {"name": "run_command", "parameters": {"CommandLine": cmd} if cmd else {}} + if output is not None: + info["output"] = output + return _agy_step(i, state, tool_name="run_command", tool_info=info) + + +def test_antigravity_ends_a_step_once_and_waits_for_its_arguments(): + events = parse_lines( + "antigravity", + lines( + _shell(1, "PENDING", cmd=None), # no arguments yet: no call + _shell(1, "ACTIVE"), + _shell(1, "WAITING"), # still going: no result + _shell( + 1, "DONE", "Command exited with code 0.\n\nCommand output:\n2 x.csv\n" + ), + _shell( + 1, "DONE", "Command exited with code 0.\n\nCommand output:\n2 x.csv\n" + ), + ), + ) + assert kinds(events) == [ + ("tool_call", "run_command"), + ("tool_result", "run_command"), + ] + assert events[0]["args"] == {"command": "wc -l x.csv"} + assert events[1]["text"] == "2 x.csv\n" and not events[1]["error"] + + +@pytest.mark.parametrize( + ("state", "output", "text", "error"), + [ + ("DONE", "plain output, no header", "plain output, no header\n", False), + ( + "DONE", + "Created At: x\nCommand exited with code 0.\n\nNo output from the command.", + "", + False, + ), + ( + "DONE", + "Command exited with code 2.\n\nCommand output:\nboom\n", + "boom\n", + True, + ), + ( + "DONE", + "Command exited with code 1.\n\nNo output from the command.", + "", + True, + ), + ("CANCELLED", "", "", True), + ], +) +def test_antigravity_shell_results(state, output, text, error): + events = parse_lines("antigravity", lines(_shell(1, state, output))) + assert kinds(events) == [ + ("tool_call", "run_command"), + ("tool_result", "run_command"), + ] + assert events[1]["text"] == text and events[1]["error"] is error + + +def test_antigravity_pairs_steps_without_an_index_and_flushes_a_stopped_run(): + def step(state, out=None): + e = _shell(0, state, out) + del e["step_update"]["step_index"] + return e + + events = parse_lines( + "antigravity", + lines( + step("ACTIVE"), + step("DONE", "Command output:\na\n"), + step("ACTIVE"), + step("DONE", "Command output:\nb\n"), + _agy_step(9, "ACTIVE", "agent_response", text_delta="Half a thought"), + ), + ) + ids = [e["id"] for e in events if e["type"] in ("tool_call", "tool_result")] + assert ids[0] == ids[1] and ids[2] == ids[3] and ids[0] != ids[2] + assert events[-1] == { + "type": "message", + "text": "Half a thought", + } # no result event came + + +def test_antigravity_other_mcp_servers_are_not_tabctx(): + info = { + "name": "call_mcp_tool", + "parameters": {"ServerName": "other", "ToolName": "predict", "Arguments": {}}, + } + events = parse_lines( + "antigravity", + lines( + _agy_step( + 1, "DONE", tool_name="call_mcp_tool", tool_info={**info, "output": "{}"} + ) + ), + ) + assert events[0]["tool"] == "call_mcp_tool" and not events[0]["tabctx"]