把 agy CLI 當作日常主力工具跑了一陣子,真正讓人煩躁的往往不是模型寫程式碼準不準,而是外圍使用體驗裡的四件小事:

  1. SSH 連開發機反覆要求驗證:本機桌面明明已經登入過,SSH 連進去輸入 agy 卻又跳出 OOB 登入連結;
  2. 多儲存庫工作階段容易串台:本機同時開三四個儲存庫,原生清單裡一不留神就點開隔壁專案的舊工作階段,輕則污染上下文,重則改錯目錄;
  3. 專案對應不想手動硬編碼:想依儲存庫分開 Project,又不想每新建一個儲存庫就得改一次 ~/.zshrc;
  4. 多分割視窗切走就漏看狀態:Terminator 裡同時跑著好幾個工作階段,切去瀏覽器看兩眼文件,完全不知道哪個視窗跑完了、哪個出錯了、哪個正卡在 ask_question 等你選選項。

這篇把我本機實際在跑的一套方案拆開說清楚:整條鏈路只依賴 Python 標準函式庫、jq、xdotool 與 notify-send,底下貼出的腳本與設定都來自本機真實檔案(僅對使用者名稱與主機名稱做去識別化處理)。

agyr 啟動器、目錄級隔離與終端機狀態聯動架構


最終用起來是什麼體驗

先看改造完每天實際看到的這三個介面——目錄級工作階段選擇器、Terminator 五色視窗標題列、底部雙行膠囊狀態列:

agy-pick 工作階段選擇器、title.sh 五色視窗標題與 agy-powerline 狀態列介面效果預覽

平時進到任意儲存庫只需輸入一個指令 agyr,後續的登入共用、工作階段篩選、Project 綁定、標題狀態更新與背景通知就會全部自動接管。

演進提示:本文記錄的是 Linux 首版落地架構(~/.zshrc 內聯 agyr() + title.sh 五色標題)。後續為了跨平台共用(macOS + Linux)與視覺化並行排查,已在 #4 跨平台備份與一鍵還原 拆出獨立的 agyr.zsh 並以純 Python title.py 取代 title.sh,並在 #5 多工作階段 Chrome 護欄與橙色 UI 狀態 進一步升級為六色狀態列。若打算直接套用組態,建議搭配後兩篇一起閱讀。


一、用 ~/.zshrc 的 agyr() 接管啟動入口

先看整個 agyr 啟動時的判定邏輯:哪些情況直接透傳、哪些情況跳出選擇器或自動掛上 --project:

1. SSH 下共用本機已解鎖的桌面 Keyring

最初透過 SSH 連上自己的 Linux 開發機,輸入 agy 總得重新走一遍 OOB 授權。排查下來原因很直接:

  • SSH 工作階段裡預設缺少 XDG_RUNTIME_DIR 與 DBUS_SESSION_BUS_ADDRESS,連不上本機已經解鎖的桌面 Keyring;
  • 更隱蔽的一點是,**agy 只要偵測到環境變數裡有 SSH_CONNECTION / SSH_CLIENT / SSH_TTY,就會主動繞過桌面 Keyring**,改走遠端 OOB 流程。

解法分兩步:在 ~/.zshrc 裡補齊執行期匯流排路徑,但**絕不在外層 Shell 全域 unset SSH_***(否則會破壞終端機提示字元、剪貼簿判斷與其他工具的 SSH 偵測),只在啟動 agy 子程序的那一行暫時移除這三個變數:

1
2
3
4
5
6
7
8
9
10
11
12
13
# SSH 登入時複用本機已解鎖的桌面 Keyring (D-Bus) 與顯示環境,避免 agy 重複驗證
if [[ -z "${XDG_RUNTIME_DIR:-}" && -d "/run/user/$(id -u)" ]]; then
export XDG_RUNTIME_DIR="/run/user/$(id -u)"
fi
if [[ -z "${DBUS_SESSION_BUS_ADDRESS:-}" && -S "${XDG_RUNTIME_DIR:-}/bus" ]]; then
export DBUS_SESSION_BUS_ADDRESS="unix:path=${XDG_RUNTIME_DIR}/bus"
fi
if [[ -n "${SSH_CONNECTION:-}" && -z "${DISPLAY:-}" ]]; then
export DISPLAY=":1"
fi

# 上下文成長到 80% 時提前自動壓縮,避免逼近上限才臨時搶救
export AGY_CLI_AUTO_COMPACT_OVERRIDE="80%"

2. 完整的 agyr() 函式

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
agyr() {
local agyr_arg
local -a agyr_defaults
local -a agyr_cmd=(command agy)

# agy 偵測到 SSH_* 變數後會繞過本機桌面 Keyring;本機桌面匯流排可用時僅為 agy 子程序清除它們
if [[ -S "${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/bus" && ( -n "${SSH_CONNECTION:-}" || -n "${SSH_CLIENT:-}" || -n "${SSH_TTY:-}" ) ]]; then
agyr_cmd=(env -u SSH_CONNECTION -u SSH_CLIENT -u SSH_TTY agy)
fi

# 互動式無參數啟動,或無參數的 -r/--resume:彈出僅限目前目錄/儲存庫的對話選擇器
if [[ -t 0 && -t 1 ]]; then
if (( $# == 0 )); then
local picked
picked="$(python3 "$HOME/.gemini/bin/agy-pick.py" --new-first)" || return $?
if [[ "$picked" != "__NEW__" ]]; then
set -- -r "$picked"
fi
elif (( $# == 1 )) && [[ "$1" == "-r" || "$1" == "--resume" ]]; then
local picked
picked="$(python3 "$HOME/.gemini/bin/agy-pick.py")" || return $?
if [[ "$picked" == "__NEW__" ]]; then
shift
else
set -- -r "$picked"
fi
fi
fi

# 子命令或檢視說明/版本時直接透傳,不附加對話參數
case "${1:-}" in
acp|agent|agents|changelog|conversations|help|install|mcp|mic-serve|models|plugin|plugins|remote-control|update)
"${agyr_cmd[@]}" "$@"
return
;;
esac
for agyr_arg in "$@"; do
case "$agyr_arg" in
-h|--help|-v|--version)
"${agyr_cmd[@]}" "$@"
return
;;
esac
done

# 本機個人開發習慣可依需求加上權限預設;若希望走預設沙盒可留空
agyr_defaults=()

# 若已明確指定專案或恢復對話參數,則不覆寫 --project
local has_project_or_resume=0
for agyr_arg in "$@"; do
case "$agyr_arg" in
--project|--project=*|--new-project|-r|--resume|--resume=*|--conversation|--conversation=*|-c|--continue)
has_project_or_resume=1
;;
esac
done

# 依目前儲存庫/目錄自動推導並確保對應的原生 Project 存在
if (( ! has_project_or_resume )); then
local auto_project
auto_project="$(python3 "$HOME/.gemini/bin/agy-project.py" 2>/dev/null)" || auto_project=""
if [[ -n "$auto_project" ]]; then
agyr_defaults+=(--project "$auto_project")
fi
fi

"${agyr_cmd[@]}" "${agyr_defaults[@]}" "$@"
}

3. 踩坑:不要在 agyr 裡順手加上 --remote-control

我最早曾在 agyr_defaults 裡塞過 --remote-control,想著隨時能用手機或網頁接管終端機。結果開了五六個分割視窗之後,網頁端直接冒出一堆隨機執行個體名稱,根本分不清誰是誰。

正確的做法是把遠端控制徹底從終端機啟動參數裡拿掉,統一交給使用者層級的 systemd 背景服務跑一個常駐單一實例(~/.config/systemd/user/antigravity-cli-daemon.service):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[Unit]
Description=antigravity remote-control daemon
After=network.target
StartLimitIntervalSec=0

[Service]
Type=simple
ExecStart=/home/user/.local/bin/agy remote-control serve
Restart=on-failure
RestartSec=10s
RestartPreventExitStatus=3
TimeoutStopSec=30s
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=default.target

搭配 ~/.gemini/config/config.json 裡的 "cliRemoteControlHostname": "my-dev-host",開機自動啟動一個固定名稱的實例,每個新開的終端機視窗只管專心幹活,網頁端再也不會刷出一排幽靈實例。


二、免硬編碼自動推導 Project(agy-project.py)

一開始我曾考慮在 .zshrc 裡寫個 case "$PWD" 對照表,替每個常用儲存庫設定 --project。寫了兩行就放棄了——每 clone 一個新儲存庫都要改一次 .zshrc,純粹是給自己找維護負擔。

更好的做法是讓腳本依目前目錄自動推導,且只在對應的 Project 檔案不存在時才延遲建立:

  • 先查詢 git -C <cwd> rev-parse --show-toplevel,在儲存庫的任意子目錄輸入 agyr 都能歸一到同一個 Git 根目錄;
  • 若不在 Git 儲存庫裡,就退回目前的真實路徑 realpath(cwd);
  • 明確排除 /、$HOME、/tmp 與 /tmp/*,在這些公共目錄不強行建立 Project;
  • 將路徑名稱轉成合法 slug,若撞上保留字(空字串或 default-cli-project)則以路徑 SHA-256 前 8 碼兜底;
  • 寫入 ~/.gemini/config/projects/<slug>.json 時使用 os.open(..., O_WRONLY | O_CREAT | O_EXCL) 進行原子建立,多個終端機並行啟動也不會互相覆蓋或把 JSON 寫壞。

核心實作儲存在 ~/.gemini/bin/agy-project.py:

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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#!/usr/bin/env python3
"""Resolve (and lazily create) a native Antigravity Project ID from the current directory."""
import argparse
import hashlib
import json
import os
import re
import subprocess

DEFAULT_PROJECTS_DIR = os.path.expanduser("~/.gemini/config/projects")
RESERVED_IDS = {"", "default-cli-project"}


def is_excluded(path: str, home: str) -> bool:
return path in ("/", home, "/tmp") or path.startswith("/tmp/")


def detect_git_root(cwd: str, home: str) -> str | None:
try:
res = subprocess.run(
["git", "-C", cwd, "rev-parse", "--show-toplevel"],
capture_output=True, text=True, timeout=2.0, check=False,
)
except (OSError, subprocess.SubprocessError):
return None
if res.returncode != 0 or not res.stdout.strip():
return None
top = os.path.realpath(res.stdout.strip())
return None if is_excluded(top, home) else top


def resolve_root(cwd: str, home: str) -> str | None:
real_cwd = os.path.realpath(cwd)
git_root = detect_git_root(real_cwd, home)
if git_root:
return git_root
return None if is_excluded(real_cwd, home) else real_cwd


def derive_project(root: str) -> tuple[str, str]:
name = os.path.basename(root)
slug = re.sub(r"[^a-z0-9-]+", "-", name.lower()).strip("-")[:64].strip("-")
if slug in RESERVED_IDS:
digest = hashlib.sha256(root.encode("utf-8")).hexdigest()[:8]
slug = f"proj-{digest}"
return slug, name or slug


def ensure_project_file(projects_dir: str, project_id: str, name: str) -> str:
os.makedirs(projects_dir, exist_ok=True)
path = os.path.join(projects_dir, f"{project_id}.json")
if os.path.exists(path):
return path
payload = json.dumps(
{"id": project_id, "name": name, "projectResources": {}},
ensure_ascii=False, indent=2,
) + "\n"
try:
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)
except FileExistsError:
return path
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
f.write(payload)
except Exception:
try:
os.unlink(path)
except OSError:
pass
raise
return path


def main() -> int:
parser = argparse.ArgumentParser(description="Resolve/create native Antigravity Project ID.")
parser.add_argument("--cwd", default=os.getcwd(), help="Target working directory")
parser.add_argument("--projects-dir", default=DEFAULT_PROJECTS_DIR, help="Projects JSON directory")
parser.add_argument("--dry-run", action="store_true", help="Print resolved project ID without writing JSON")
args = parser.parse_args()

home = os.path.realpath(os.path.expanduser("~"))
root = resolve_root(args.cwd, home)
if not root:
return 0

project_id, name = derive_project(root)
if not args.dry_run:
ensure_project_file(args.projects_dir, project_id, name)
print(project_id)
return 0


if __name__ == "__main__":
raise SystemExit(main())

平時也可以先用 python3 ~/.gemini/bin/agy-project.py --dry-run 預演目前目錄會對應出哪個 Project ID,確認無誤再實際寫入磁碟。


三、嚴格依目前目錄過濾的工作階段選擇器(agy-pick.py)

光靠 Project 隔離還不夠——原生的續聊選擇器裡偶爾還是會混入其他工作區的歷史紀錄。我乾脆寫了一個零依賴的 Python TUI 選擇器 ~/.gemini/bin/agy-pick.py,直接從底層的 SQLite 索引資料庫過濾出僅屬於目前目錄/儲存庫的工作階段。

關鍵過濾邏輯

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
DB_PATH = os.path.expanduser("~/.gemini/antigravity-cli/conversation_summaries.db")
CONV_DIR = os.path.expanduser("~/.gemini/antigravity-cli/conversations")

def load_conversations(cwd: str) -> list[dict]:
if not os.path.exists(DB_PATH):
return []
targets = {os.path.normpath(cwd), os.path.realpath(cwd)}
git_root = detect_git_root(cwd)
if git_root:
targets.add(os.path.normpath(git_root))
targets.add(git_root)

# 以唯讀 URI 開啟,絕不干擾 agy 主程序的 SQLite WAL 寫入
conn = sqlite3.connect(f"file:{DB_PATH}?mode=ro", uri=True, timeout=2.0)
try:
rows = conn.execute("""
SELECT conversation_id, title, preview, step_count, workspace_uris, last_modified_time
FROM conversation_summaries
WHERE step_count > 0
AND COALESCE(parent_conversation_id, '') = ''
AND (source = '' OR source = 'CORTEX_TRAJECTORY_SOURCE_CLI')
ORDER BY last_modified_time DESC
""").fetchall()
finally:
conn.close()

items = []
for cid, title, preview, steps, ws_json, mtime in rows:
if not os.path.exists(os.path.join(CONV_DIR, f"{cid}.db")):
continue
uris = json.loads(ws_json) if ws_json else []
if not any(uri_to_paths(u) & targets for u in uris if isinstance(u, str)):
continue
label = (title or preview or "(untitled)").replace("\n", " ").strip()
items.append({"id": cid, "title": label, "steps": steps, "age": format_age(mtime)})
return items

這裡有四個細節都是踩過坑後補上去的:

  1. 唯讀模式+檢查 .db 存在:conversation_summaries.db 開啟了 WAL 模式,必須用 mode=ro 開啟;另外清理過舊工作階段後索引表可能還留有殘餘資料列,多檢查一次 conversations/<cid>.db 是否存在就能濾掉失效項目。
  2. 過濾子 Agent 與空工作階段:step_count > 0 去除剛打開就退出的空工作階段,COALESCE(parent_conversation_id, '') = '' 濾掉背景 Subagent 紀錄,清單瞬間乾淨許多。
  3. 直連 /dev/tty 繪製 TUI:因為 agyr() 是透過指令替換 picked="$(python3 agy-pick.py ...)" 擷取選中結果的,stdout 已經被重新導向給變數;互動介面必須直接讀寫 /dev/tty,最後只把選中的 conversation_id(或 __NEW__)印到 stdout。
  4. 中文寬字元對齊+兩種預設排序:用 unicodedata.east_asian_width 計算顯示寬度來截斷標題,防止中文標題把右側的 steps / age 擠到換行;無參數輸入 agyr 會傳入 --new-first 把 + 新建工作階段 放第一行(按 Enter 秒開新對話),輸入 agyr -r 則把最近工作階段放第一行(按 Enter 秒續聊)。

四、五色視窗標題+未聚焦桌面通知(hooks.json + title.sh)

agy 支援在 settings.json 裡設定 title 腳本來動態修改終端機標題,但它傳給腳本的即時 JSON 裡只有 agent_state 與 tool_confirmation_pending——能區分「閒置/執行中/等待工具核准/出錯」,唯獨區分不出「Agent 正在呼叫 ask_question 等你做選擇題」。

在我的日常工作流裡,ask_question 恰恰是最容易把人晾在一旁的場景:視窗標題還亮著「執行中」,我以為它正在寫程式碼,過了十分鐘切回去一看,它其實早就停下來等我選 A 還是 B 了。

完整狀態聯動鏈路

透過一個極輕量的本機 Flag 檔案橋接 Hooks 與 title.sh:

1. Hooks 設定(~/.gemini/config/hooks.json)

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
{
"title-waiting-choice": {
"PreToolUse": [
{
"matcher": "ask_question",
"hooks": [
{
"type": "command",
"command": "python3 ~/.gemini/config/hooks/ask-question-state.py set",
"timeout": 5
}
]
}
],
"PostToolUse": [
{
"matcher": "ask_question",
"hooks": [
{
"type": "command",
"command": "python3 ~/.gemini/config/hooks/ask-question-state.py clear",
"timeout": 5
}
]
}
],
"Stop": [
{
"type": "command",
"command": "python3 ~/.gemini/config/hooks/ask-question-state.py clear",
"timeout": 5
}
]
}
}

2. 狀態標記與防打擾通知腳本(ask-question-state.py)

如果每次任務結束都無腦跳通知,人正盯著終端機看的時候右上角也一直跳視窗,會非常吵。腳本裡加了三道防打擾保護:

  • 焦點偵測:呼叫 xdotool getactivewindow getwindowclassname,只要目前作用中的視窗屬於終端機白名單(Terminator、Kitty、Alacritty、WezTerm、Ghostty 等),直接靜音;
  • 15 秒節流:Stop 通知依工作階段 Key 記錄時間戳 notify-<key>.ts,避免連續子回合反覆跳通知;
  • 環境變數逃生閥:需要錄影或簡報示範時用 AGY_NO_NOTIFY=1 一鍵靜音;PreToolUse 裡必須輸出 {"decision": "allow"} 避免阻塞工具呼叫。
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
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/usr/bin/env python3
"""Antigravity hook: track ask_question state for title.sh and send desktop notifications when unfocused."""
import hashlib, json, os, shutil, subprocess, sys, time
from pathlib import Path

STATE_DIR = Path("/tmp/agy-waiting-choice")
TERMINAL_CLASSES = (
"terminator", "gnome-terminal", "kitty", "alacritty",
"wezterm", "konsole", "xfce4-terminal", "tilix", "xterm", "ghostty",
)
STOP_NOTIFY_COOLDOWN_S = 15.0

def key_for(value: str) -> str:
return hashlib.sha256(value.encode("utf-8")).hexdigest()[:24]

def collect_keys(payload: dict) -> list[str]:
conv_id = str(payload.get("conversationId") or payload.get("conversation_id") or "").strip()
if conv_id:
return ["conv-" + key_for(conv_id)]
keys = []
for raw in payload.get("workspacePaths") or []:
if isinstance(raw, str) and raw.strip():
keys.append("ws-" + key_for(os.path.realpath(raw.strip())))
return keys

def terminal_is_focused() -> bool:
if not os.environ.get("DISPLAY") or not shutil.which("xdotool"):
return False
res = subprocess.run(
["xdotool", "getactivewindow", "getwindowclassname"],
capture_output=True, text=True, timeout=0.5, check=False,
)
return res.returncode == 0 and any(t in res.stdout.strip().lower() for t in TERMINAL_CLASSES)

def should_throttle(key: str) -> bool:
stamp = STATE_DIR / f"notify-{key}.ts"
now = time.time()
try:
if now - float(stamp.read_text().strip()) < STOP_NOTIFY_COOLDOWN_S:
return True
except (OSError, ValueError):
pass
stamp.write_text(f"{now}\n")
return False

def send_desktop_notification(title: str, body: str, urgency: str = "normal") -> None:
if os.environ.get("AGY_NO_NOTIFY") == "1" or not os.environ.get("DISPLAY"):
return
notify_bin = shutil.which("notify-send")
if not notify_bin or terminal_is_focused():
return
subprocess.Popen(
[notify_bin, "-a", "Antigravity", "-u", urgency, "-t", "6000", title, body],
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
start_new_session=True, close_fds=True,
)

def main() -> int:
action = sys.argv[1] if len(sys.argv) > 1 else ""
payload = json.load(sys.stdin) if not sys.stdin.isatty() else {}
STATE_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
keys = collect_keys(payload)
label = os.path.basename(str(payload.get("cwd") or "").rstrip("/")) or "agy"

if action == "set":
for k in keys:
(STATE_DIR / f"{k}.flag").write_text("1\n")
send_desktop_notification(f"🔵 Antigravity 等待選擇 ({label})", "Agent 提出了問題,請回到終端機確認選項。")
print('{"decision": "allow"}')
elif action == "clear":
for k in keys:
(STATE_DIR / f"{k}.flag").unlink(missing_ok=True)
if payload.get("hookEventName") == "Stop":
reason = str(payload.get("terminationReason") or "")
fully_idle = payload.get("fullyIdle", True)
tk = keys[0] if keys else "global"
if reason == "ERROR" and not should_throttle(tk):
send_desktop_notification(f"🔴 Antigravity 執行出錯 ({label})", "對話因錯誤中止,請回到終端機檢視詳情。", "critical")
elif reason == "NO_TOOL_CALL" and fully_idle and not should_throttle(tk):
send_desktop_notification(f"🟢 Antigravity 已完成 ({label})", "目前任務已回覆完畢。", "low")
print("{}")
return 0

if __name__ == "__main__":
raise SystemExit(main())

3. 五色視窗標題腳本(~/.gemini/antigravity-cli/title.sh)

寫 title.sh 時踩過一個跟當年寫 Claude 狀態列一模一樣的坑:如果用 IFS=$'\t' read 解多個欄位,遇到空的 branch 或 title 欄位時 bash 會把連續空白摺疊掉,導致後面的所有變數集體左移。這裡改用單次 jq 每行輸出一個欄位+mapfile -t 讀入陣列,徹底杜絕錯位:

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
#!/usr/bin/env bash
set -euo pipefail

# 單次 jq 解析即時對話狀態 JSON;逐行讀出避免空欄位被 IFS 摺疊錯位
mapfile -t FIELDS < <(
jq -r '[
(.agent_state // "idle"),
(if .tool_confirmation_pending == true then "1" else "0" end),
((.subagents // []) | if type == "array" then map(select(type == "object" and .status == "running")) | length else 0 end | tostring),
((.task_count // 0) | if type == "number" and . > 0 then floor else 0 end | tostring),
(.workspace.current_dir // .workspace.project_dir // .cwd // ""),
(.vcs.branch // .workspace.vcs.branch // ""),
(.conversation_title // .title // ""),
(.conversation_id // .conversationId // .session_id // "")
] | map(tostring | gsub("[\r\n\t]+"; " ")) | .[]' 2>/dev/null || printf 'idle\n0\n0\n0\n\n\n\n\n'
)

STATE="${FIELDS[0]:-idle}"
CONFIRM="${FIELDS[1]:-0}"
RUNNING_SUBAGENTS="${FIELDS[2]:-0}"
RUNNING_TASKS="${FIELDS[3]:-0}"
CWD="${FIELDS[4]:-}"
BRANCH="${FIELDS[5]:-}"
TITLE="${FIELDS[6]:-}"
CONV_ID="${FIELDS[7]:-}"

WAITING_CHOICE="0"
if [ "$STATE" != "idle" ] && [ -d /tmp/agy-waiting-choice ]; then
if [ -n "$CONV_ID" ]; then
CONV_KEY=$(printf '%s' "$CONV_ID" | sha256sum)
[ -f "/tmp/agy-waiting-choice/conv-${CONV_KEY:0:24}.flag" ] && WAITING_CHOICE="1"
elif [ -n "$CWD" ]; then
REAL_CWD=$(realpath -m "$CWD" 2>/dev/null || printf '%s' "$CWD")
WS_KEY=$(printf '%s' "$REAL_CWD" | sha256sum)
[ -f "/tmp/agy-waiting-choice/ws-${WS_KEY:0:24}.flag" ] && WAITING_CHOICE="1"
fi
fi

if [ "$STATE" = "error" ]; then
DOT="🔴"
elif [ "$WAITING_CHOICE" = "1" ]; then
DOT="🔵"
elif [ "$CONFIRM" = "1" ]; then
DOT="🟡"
elif [ "$STATE" != "idle" ] || [ "$RUNNING_SUBAGENTS" -gt 0 ] || [ "$RUNNING_TASKS" -gt 0 ]; then
DOT="🟣"
else
DOT="🟢"
fi

DIR=""
[ -n "$CWD" ] && DIR=$(basename "$CWD")
[ "${#TITLE}" -gt 32 ] && TITLE="${TITLE:0:31}…"

PARTS=()
[ -n "$DIR" ] && PARTS+=("$DIR")
[ -n "$TITLE" ] && PARTS+=("$TITLE")
[ -n "$BRANCH" ] && PARTS+=("$BRANCH")

if [ "${#PARTS[@]}" -eq 0 ]; then
printf '%s agy\n' "$DOT"
else
OUT="${PARTS[0]}"
for ((i = 1; i < ${#PARTS[@]}; i++)); do OUT+=" | ${PARTS[$i]}"; done
printf '%s %s\n' "$DOT" "$OUT"
fi

五、雙行膠囊狀態列(agy-powerline)與 settings.json 掛載

視窗標題解決的是「切去別處或開多分割視窗時一眼看出狀態」,而正在輸入指令的目前終端機底部,我直接採用社群的 agy-powerline(比手寫 Shell 狀態列省事得多,還內建寬度自適應與配額節奏條)。

我的 ~/.agy-powerline/statusline.config.json 拆成兩行,依「位置/程式碼狀態」與「資源/配額狀態」分工:

行 啟用的 Widgets 看什麼
第一行 cwd(depth:2) · agentState · git(gitLink) · gitFiles · gitChanges · gitStash · gitWorktree · model · contextTokens(warn:65, crit:85) · mode 我在哪個儲存庫、分支乾不乾淨、用了什麼模型、上下文快滿了沒
第二行 title(maxWidth:24) · tasks(alwaysShow) · queue · cacheHit · fiveHourPct · fiveHourReset · weeklyPct · weeklyReset · sessionTime · tokensToday 背景有幾個任務/佇列訊息、快取命中率、5 小時與週配額還剩多少

最後把 statusLine 與 title 一起掛進 ~/.gemini/antigravity-cli/settings.json:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
"enableTerminalSandbox": true,
"pickerGrouping": "grouped",
"statusLine": {
"type": "command",
"command": "'/usr/bin/node' '/home/user/.agy-powerline/statusline.js'",
"enabled": true
},
"title": {
"type": "command",
"command": "~/.gemini/antigravity-cli/title.sh",
"enabled": true
}
}

如果你啟用了 enableTerminalSandbox: true,順手檢查一下 settings.json 裡的 permissions.deny:read_file(...) 只能寫精確目錄路徑(如 read_file(/home/user/.ssh)),不能帶 /** 萬用字元,否則沙箱校驗會直接報錯阻斷所有沙箱指令。


整套腳本清單

這套改造全部落在使用者層級的目錄,完全不侵入任何業務儲存庫:

檔案 職責
~/.zshrc(agyr) SSH 共用 Keyring、無參數/-r 呼叫選擇器、子指令透傳、自動注入 --project
~/.gemini/bin/agy-project.py 依 Git 根目錄推導並原子延遲建立 ~/.gemini/config/projects/<slug>.json
~/.gemini/bin/agy-pick.py 唯讀查詢 conversation_summaries.db,嚴格依目前目錄/儲存庫過濾工作階段
~/.config/systemd/user/antigravity-cli-daemon.service 常駐單一實例託管 agy remote-control serve(Remote Control 原理與 loginctl enable-linger 詳見 基礎系列第 12 篇)
~/.gemini/config/hooks.json + hooks/ask-question-state.py 追蹤 ask_question 狀態標記並在終端機未聚焦時發送桌面通知
~/.gemini/antigravity-cli/title.sh 單次 jq 解析即時狀態並點亮五色圓點視窗標題
~/.agy-powerline/statusline.config.json 底部雙行膠囊狀態列

系列導覽