改造 agy 启动体验:agyr 启动器、目录级会话隔离与终端五色通知

0 阅读10分钟

把 agy CLI(Google Antigravity 命令行端)当日常主力跑了一阵,真正让人烦的往往不是模型写代码准不准,而是外围体验里的四件小事:

  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:

flowchart TD
    IN["终端敲 agyr [args...]"] --> SSH{"检测到 SSH_* 且本机 D-Bus 可用?"}
    SSH -- "是" --> UNSET["子进程 env -u SSH_* 复用桌面 Keyring"]
    SSH -- "否" --> RAW["直接调用 command agy"]
    UNSET --> TTY{"交互终端且无参 / 仅 -r?"}
    RAW --> TTY
    TTY -- "无参" --> PICK1["agy-pick.py --new-first<br/>+ 新建会话排第一"]
    TTY -- "仅 -r / --resume" --> PICK2["agy-pick.py<br/>最近历史排第一"]
    TTY -- "其他参数" --> SUB
    PICK1 --> SUB{"是否子命令或 -h/-v?"}
    PICK2 --> SUB
    SUB -- "是 (mcp/plugin/models...)" --> PASS["原样透传,不加会话参数"]
    SUB -- "否" --> HAS{"已传 --project / -r / -c?"}
    HAS -- "是" --> EXEC["执行 agy"]
    HAS -- "否" --> PROJ["agy-project.py 推导并懒建 Project JSON<br/>追加 --project <slug>"]
    PROJ --> EXEC

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 子进程的那一行临时剥掉这三个变量:

# 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() 函数

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):

[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:

#!/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 索引库过滤出仅属于当前目录/仓库的会话。

关键过滤逻辑

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 把 + 新建会话 放第一行(回车秒开新对话),敲 agyr -r 则把最近会话放第一行(回车秒续聊)。

四、五色窗口标题 + 失焦桌面通知(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:

sequenceDiagram
    participant A as Gemini Agent
    participant H as hooks.json<br/>(ask-question-state.py)
    participant F as /tmp/agy-waiting-choice/
    participant T as title.sh (周期刷新)
    participant D as Linux 桌面 (xdotool / notify-send)

    A->>H: PreToolUse (matcher: ask_question)
    H->>F: 写入 conv-<sha256[:24]>.flag
    H->>D: xdotool 检查焦点非终端 → notify-send 🔵 等待选择
    T->>F: 检测存在 .flag 且 state != idle
    T-->>T: 标题栏点亮 🔵 dir | title | branch
    Note over A,D: 用户回到终端做出选择
    A->>H: PostToolUse (matcher: ask_question)
    H->>F: 删除 .flag,标题自动切回 🟣 运行中
    A->>H: Stop (NO_TOOL_CALL / ERROR)
    H->>F: 清理残留 .flag + 15s 冷却检查
    H->>D: 失焦时发 🟢 已完成 或 🔴 执行出错

1. Hooks 配置(~/.gemini/config/hooks.json)

{
  "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"} 避免阻塞工具调用。
#!/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 读入数组,彻底杜绝错位:

#!/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:

{
  "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底部双行胶囊状态栏

系列导航


原文首发于小河马博客:改造 agy 启动体验:agyr 启动器、目录级会话隔离与终端五色通知 更多 Google Antigravity 实战与工程化笔记见博客主页:hippo0913.com/