前面 14 篇基本上把 Antigravity(AGY)作為 CLI 工具與團隊平台的玩法都拆解完了。收官這一篇要處理兩個很實際的落地問題:一是當 Shell 腳本裡的 agy -p 不夠用、需要把 Agent 直接嵌入 Python 服務或自動化評測套件時,官方 Python SDK 該怎麼寫;二是如果你手上已經累積了一整套 Claude Code、Cursor、Codex 或 Gemini CLI 的 MCP、Skills、Subagents 與規則檔,該如何一次遷移過來,並且隨時都能零殘留回滾。

這兩件事我都對照官方 sdk.md 參考文件與內建 migrate-agent-settings 技能逐條核對過,以下直接整理實戰重點與容易踩坑的邊界。

一、什麼時候該用 Python SDK,而不是 agy -p?

第 02 篇講過非互動模式 agy -p --output-format stream-json。日常在 GitHub Actions 裡加上一步自動審查,或是在 Shell 管線裡做文字處理,直接用 CLI 就夠了,沒必要引入 Python 相依套件。

但只要進入以下幾種情境,改用 google-antigravity Python SDK 會順手得多:

比較維度 agy -p --output-format stream-json google-antigravity Python SDK
典型情境 Shell 管線、CI 單步指令、快速腳本 Python 服務內嵌、自動化測試與評測框架
事件消費 手動解析 stdout 裡的 JSONL 文字串流 直接迭代內文串流、thoughts 與強型別 tool_calls
策略與權限 依賴全域組態、儲存庫設定與 CLI 參數 在程式碼中透過 LocalAgentConfig 與 CapabilitiesConfig 宣告
互動複用 單輪無頭呼叫或搭配 --resume 續跑 可用 run_interactive_loop 兩行啟動客製終端機助手

一句話區分:外部排程調度用 agy -p,需要與現有 Python 業務程式碼、pytest 斷言、非同步日誌系統整合時,直接用 Python SDK。

google-antigravity Python SDK 執行架構與 Claude Code 四大生態系遷移對照

二、google-antigravity Python SDK 實戰拆解

2.1 安裝:務必透過 PyPI wheel,別直接複製原始碼

官方 SDK 儲存庫位於 GitHub 的 google-antigravity/antigravity-sdk-python,安裝指令很單純:

1
pip install google-antigravity

安裝硬提醒:千萬別為了省事,直接從原始碼儲存庫把 .py 檔案複製進專案裡執行。SDK 相依於一份已編譯的執行期二進位檔,這份執行檔只會隨 PyPI 上對應平台的 wheel(platform-specific wheel)一起發布。請一律使用 pip install google-antigravity 安裝,才能取得相符的執行期二進位檔。

2.2 核心物件與「預設唯讀」安全設計

SDK 的入口相當克制,核心就三個類別:Agent、LocalAgentConfig 與 CapabilitiesConfig。

  • Agent(config) 是一個非同步上下文管理器,透過 async with Agent(config) as agent: 啟動與釋放。底層執行檔探索、工具裝配、Hook 註冊與預設策略載入全由它接管,離開程式區塊即自動清理。
  • LocalAgentConfig(system_instructions=..., capabilities=...) 負責宣告系統提示詞與能力邊界。它預設以唯讀模式啟動(read-only by default),未傳入 capabilities 時模型只能讀不能改;只有明確傳入 capabilities=CapabilitiesConfig(),才會開啟 edit_file、run_command 等寫入檔案與執行指令的能力。

先看一個最精簡的讀寫範例,跑通初始化與內文串流輸出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import asyncio
import sys
from google.antigravity import Agent, LocalAgentConfig, CapabilitiesConfig


async def main() -> None:
# 預設唯讀;明確傳入 CapabilitiesConfig() 才開啟 edit_file / run_command 等寫入工具
config = LocalAgentConfig(
system_instructions="You are an expert assistant for codebase navigation.",
capabilities=CapabilitiesConfig(),
)

async with Agent(config) as agent:
# agent.chat() 會立即回傳回應物件,不阻塞目前協程
response = await agent.chat("Write a short python script to list files.")

async for token in response:
sys.stdout.write(token)
sys.stdout.flush()
print()


if __name__ == "__main__":
asyncio.run(main())

2.3 三大串流通道與 CI 非同步稽核腳本

await agent.chat(...) 回傳的 response 物件會同時暴露三條非同步串流,非常適合在工程實務中用來做監控與測試斷言:

  1. 內文 Token 串流:async for token in response:,逐段取得最終回答文字;
  2. 思考過程串流:async for thought in response.thoughts:,即時監聽模型的推理 delta,可以獨立寫進評測日誌或前端除錯面板,不汙染內文輸出;
  3. 強型別工具呼叫串流:async for call in response.tool_calls:,即時取得強型別的工具呼叫事件,直接讀取 call.name 與 call.args。

以下是一個可以直接改造成 CI 巡檢或評測腳本的完整範例。這裡刻意不傳入 capabilities,讓 Agent 執行在預設的唯讀模式下,再用 asyncio.gather 並行消費內文、思考串流與工具呼叫串流,最後透過斷言驗證沒有觸發任何寫入工具:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import asyncio
import json
import sys
from pathlib import Path
from google.antigravity import Agent, LocalAgentConfig


async def stream_answer(response) -> str:
chunks: list[str] = []
async for token in response:
sys.stdout.write(token)
sys.stdout.flush()
chunks.append(token)
print()
return "".join(chunks)


async def collect_thoughts(response) -> list[str]:
thoughts: list[str] = []
async for thought in response.thoughts:
thoughts.append(str(thought))
return thoughts


async def audit_tool_calls(response) -> list[dict]:
records: list[dict] = []
async for call in response.tool_calls:
print(f"[ToolCall] {call.name} args={call.args}", file=sys.stderr)
records.append({"name": call.name, "args": call.args})
return records


async def run_ci_audit() -> None:
# 不傳 capabilities:強制維持預設唯讀模式
config = LocalAgentConfig(
system_instructions=(
"你是 CI 安全巡檢助手。僅讀取儲存庫設定並輸出風險清單,嚴禁修改檔案。"
),
)

async with Agent(config) as agent:
response = await agent.chat(
"檢查目前儲存庫的 CI 設定與腳本,列出存在高權限或憑證外洩風險的位置。"
)
answer, thoughts, tool_calls = await asyncio.gather(
stream_answer(response),
collect_thoughts(response),
audit_tool_calls(response),
)

# 持久化稽核軌跡,便於評測回溯
Path("audit-trace.json").write_text(
json.dumps(
{
"answer_length": len(answer),
"thought_chunks": len(thoughts),
"tool_calls": tool_calls,
},
ensure_ascii=False,
indent=2,
),
encoding="utf-8",
)

# 在測試套件中直接對強型別 tool_calls 做斷言
write_tools = {"edit_file", "write_file", "run_command"}
violated = [c["name"] for c in tool_calls if c["name"] in write_tools]
assert not violated, f"唯讀巡檢觸發了非預期寫入工具: {violated}"


if __name__ == "__main__":
asyncio.run(run_ci_audit())

2.4 兩行程式碼啟動客製互動終端機

如果你的目標不是無人值守批次執行,而是替團隊封裝一個帶有固定系統提示詞與權限集的內部命令列助手,不需要自己手刻 input() 迴圈,直接複用 SDK 內建的 run_interactive_loop 即可:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import asyncio
from google.antigravity import Agent, LocalAgentConfig, CapabilitiesConfig
from google.antigravity.utils.interactive import run_interactive_loop


async def main() -> None:
config = LocalAgentConfig(
system_instructions="你是本儲存庫發布值班助手,所有變更前先總結影響範圍。",
capabilities=CapabilitiesConfig(),
)
async with Agent(config) as agent:
await run_interactive_loop(agent)


if __name__ == "__main__":
asyncio.run(main())

跑起來就是一套開箱即用的多輪互動終端機,比自己在業務程式碼裡從頭維護對話狀態省事得多。

Python SDK 串流消費 thoughts/tool_calls 與可逆遷移外掛實操速查

三、從 Claude Code / Cursor / Codex / Gemini CLI 無痛遷移

許多資深玩家想試試 AGY,卻遲遲沒有動手,原因在於已經在 Claude Code 或 Cursor 裡養出一整套 MCP、指令、子代理與規則檔,全部重設一遍太耗時,又擔心遷移把原工具的環境弄亂。

3.1 官方建議策略:可逆單一外掛四步遷移

AGY 內建了 migrate-agent-settings 技能,直接在對話中告訴它「幫我把本機的 Claude Code / Cursor / Codex 設定遷移到 Antigravity」即可觸發。它的設計相當穩健,核心原則就一條:將所有遷過來的設定裝進同一個獨立外掛目錄(預設建議 ~/.gemini/config/plugins/migrated-settings/),絕不更動原工具的任何檔案。

整個流程強制分為四個步驟:

  1. Discover(唯讀盤點):掃描本機四個生態系的組態路徑,同時比對 ~/.gemini/config/ 中 AGY 已有的 MCP、Skills、外掛與目前已載入的規則(例如 ~/.gemini/GEMINI.md 若已生效就會自動略過,避免重複注入);
  2. Confirm(確認計畫):依來源分組彙總數量與名稱,說明哪些項目會被略過,絕不在對話中印出 Token 或 API Key 明文。在使用者明確確認前,絕不寫入磁碟;若掃描到目前工作區裡的 .mcp.json 或 .cursor/rules/,也會提前提醒「放進全域外掛後會對所有工作區生效」,方便你決定要不要保留;
  3. Write(寫入單一外掛):產生 plugin.json(僅保留 name、displayName、version、description 四個有效欄位)、mcp_config.json、skills/、agents/、rules/;
  4. Hand back(驗證交付):重讀驗證 plugin.json 與 mcp_config.json 能否正常解析為 JSON,最後提供外掛頁面連結 customization://migrated-settings。

這種做法最大的好處是完全可逆:想要對比測試或回滾時,只要在外掛頁面停用它,或刪除 ~/.gemini/config/plugins/migrated-settings/ 這一個資料夾,就能一秒恢復乾淨狀態,原本的 Claude Code / Cursor 絲毫無損。

3.2 四大生態系設定檔對照總表

如果你打算自行核對或手動整理,以下這張 4 欄表格涵蓋 migrate-agent-settings 所掃描的全部路徑:

來源工具 MCP 設定位置 Skills / Commands / Subagents Rules / 指令檔
Claude Code ~/.claude.json(頂層 mcpServers);<workspace>/.mcp.json ~/.claude/skills/*/SKILL.md;~/.claude/commands/*.md;~/.claude/agents/*.md ~/.claude/CLAUDE.md
Codex ~/.codex/config.toml 的 [mcp_servers.<name>] ~/.codex/skills/*/SKILL.md;~/.codex/prompts/*.md ~/.codex/AGENTS.md
Cursor ~/.cursor/mcp.json;<workspace>/.cursor/mcp.json — <workspace>/.cursor/rules/*.mdc
Gemini CLI ~/.gemini/settings.json 的 mcpServers ~/.gemini/commands/**/*.toml ~/.gemini/GEMINI.md

3.3 遷移時最容易踩坑的 5 條轉換規則

無論是自動遷移還是手動改寫,真正決定「能不能直接跑起來」的,是以下這 5 處細節差異:

1. Claude Code Subagent 工具名稱重新對應與必填欄位

將 Claude Code 的 ~/.claude/agents/*.md 遷移到外掛 agents/<name>.md 後,內文保留作為 system prompt,但 YAML frontmatter 必須進行四項改寫:

  • 明確宣告角色:加上 subagent: true 與 mainAgent: false,防止它被當成主 Agent;
  • 明確宣告工具清單:在 AGY 中若省略 tools,只會分配一個極小的唯讀預設集;因此如果原 Claude agent 沒寫 tools(代表全開),遷移時要明確補齊為 [read_file, edit_file, write_file, run_command, manage_task, search_web];
  • 依對應關係轉換工具名稱:Read、Glob、Grep 統一對應至 read_file;Edit、MultiEdit 對應至 edit_file;Write 對應至 write_file;Bash 對應至 run_command 與 manage_task;WebSearch、WebFetch 對應至 search_web;沒有對應項的權限直接移除並做紀錄;
  • 清理專有欄位與避免撞名:刪除 model 與 color;若名稱與內建或既有 Agent(self、browser、research、deepagent、review-agent)衝突,加上來源前綴,例如改為 claude-reviewer。

2. Slash Commands / Prompts 轉 Skills,以及缺少 frontmatter 被丟棄的坑

  • ~/.claude/commands/*.md、~/.codex/prompts/*.md 與 Gemini CLI 的 ~/.gemini/commands/**/*.toml 都會轉成 skills/<name>/SKILL.md。Gemini 的巢狀子目錄路徑以 - 串接成技能名稱(例如 git/commit.toml 變成 git-commit),內文取指令內容(TOML 取 prompt 欄位);
  • 指令中的 $ARGUMENTS、$1、{{args}} 需要改寫為自然語言指示(例如「將上述步驟套用到使用者目前的請求上」);
  • 高頻踩坑點:Claude Code 允許 SKILL.md 不寫 frontmatter 或漏掉 name,但 AGY 會直接丟棄這類檔案。遷移時每個 SKILL.md 都必須具備完整的 YAML frontmatter,且 name 必須與資料夾名稱嚴格一致、description 不可為空;原目錄下的 scripts/ 與 references/ 連同資料夾整包複製過來即可。

3. Cursor .mdc 轉 AGY Rules 的觸發器與 glob 規範

將 Cursor 的 <workspace>/.cursor/rules/*.mdc 遷移成獨立的 rules/<name>.md 時,觸發條件依下列優先順序對應:

  1. alwaysApply: true → trigger: always_on;
  2. 存在非空 globs → trigger: glob;
  3. 存在非空 description → trigger: model_decision;
  4. 兩者皆空 → trigger: manual。

另外有兩條硬性限制須提前處理:AGY 的 globs 必須是單一逗號分隔字串,且比對的是絕對路徑與檔名,因此需要將 YAML 清單攤平、把大括號 **/*.{ts,tsx} 展開為 **/*.ts, **/*.tsx,並幫相對路徑補上 **/ 前綴(src/**/*.ts 改為 **/src/**/*.ts)。單一規則檔的上限為 24 KB,原檔案超長時切勿靜默截斷,應主動拆分為多個依路徑觸發的規則,並順手移除「使用 Bash 工具」這類舊工具專屬措辭。

4. MCP 環境變數與 variables 的反直覺機制

這是遷移後 MCP 報錯最多的一塊。AGY 外掛中的 mcp_config.json 不會自動展開作業系統的環境變數!

  • 合法欄位僅承認 command、args、env、cwd、url、headers、disabled、variables(type、timeout、trust、alwaysAllow 會被忽略;Gemini CLI 的 httpUrl 與 Codex 的 url 統一對應至 url;Codex 的 http_headers 放進 headers,env_http_headers 與 bearer_token_env_var 轉成 headers 裡的 ${X} 並加上 variables 宣告);
  • 刪除純透傳的環境變數項目:如果你在原 stdio env 中寫過 "GITHUB_TOKEN": "${GITHUB_TOKEN}"、"GITHUB_TOKEN": "$GITHUB_TOKEN" 或 Cursor 的 "${env:GITHUB_TOKEN}",遷到外掛裡反而應該刪掉這一行——刪掉後子程序會直接繼承目前環境的同名變數,留著又不設定 variables 反而會把字面字串 ${GITHUB_TOKEN} 傳進去;
  • 真正需要插值的佔位符必須補齊變數宣告:例如遠端 MCP 的 "Authorization": "Bearer ${API_KEY}",要把 $X、${env:X}、${X:-default} 統一改寫為 ${X}(預設值寫進描述),並在該 server 下宣告 variables 陣列(包含 name、title、description)。注意:只要外掛中任一個 server 宣告了 variables,外掛預設會以停用狀態啟動,必須前往外掛頁面填完值後再手動啟用;
  • 所有路徑提前展開為絕對路徑:cwd 不支援變數替換,且相對路徑會相對於外掛目錄本身解析,因此 ${workspaceFolder}、$HOME、~、相對路徑以及 ${CLAUDE_PLUGIN_ROOT} 都必須在寫入前展開為真實絕對路徑;若 server 名稱與 AGY 既有組態衝突,加上來源前綴(例如 claude-github)。

5. 明確無法自動遷移的 4 類資產

別指望用腳本硬轉以下這四樣,直接依邊界分流處理更省時間:

無法自動遷移的資產 原因 正確處理方式
Claude Code settings.json 中的 hooks 與 permissions 工具名稱(Bash/Edit)與 protojson/規則語法不同 參考本系列 #07(Hooks)與 #14(權限引擎)手動重寫
~/.claude/plugins/ 與 ~/.gemini/extensions/ 屬於完整外掛/擴充套件包,非零散使用者設定 直接執行 agy plugin import claude 或 agy plugin import gemini
Cursor 用戶端內建資料庫裡的個人使用者規則 儲存於應用程式本機 DB,不在檔案系統組態裡 從 Cursor 設定介面複製出內文,放進 ~/.gemini/config/rules/
舊版 SSE 協定 MCP("type": "sse" 或 /sse) AGY 遠端 MCP 採用 Streamable HTTP 優先改連 /mcp 端點;無新版端點時改用 stdio 橋接 npx -y mcp-remote <url>

四、整套 15 篇今天就能落地的最小閉環

全系列寫到這裡正好 15 篇,不同角色沒必要一口氣把所有功能全部設好,挑自己當下最痛的那一環切入就行:

  • 個人日常主力切換:先跑一次 migrate-agent-settings 把舊工具的 MCP 與 Skills 收進 migrated-settings 可逆外掛,再設定好 ~/.gemini/config/AGENTS.md 以及順手的快捷鍵與 /plan,當天就能無縫上工。
  • 團隊儲存庫標準化:在專案根目錄提交一份精簡的 AGENTS.md、依路徑拆好的 .agents/rules/*.md(控制在 24 KB 以內),再用 hooks.json 與權限 deny 規則把敏感檔案與高風險指令鎖死,全員 git pull 即刻生效。
  • 工程自動化與評測:簡易管線先用 agy -p --output-format stream-json 接進 CI;當需要把 Agent 嵌入 Python 測試套件、監控推理串流並對 tool_calls 做嚴格斷言時,再導入 google-antigravity Python SDK,從預設唯讀模式起步,依需求逐步開放 CapabilitiesConfig。

系列導覽