agy CLI を日々の主力ツールとして使い込んでいくと、本当に気になるのはモデルのコード生成精度そのものではなく、周辺ワークフローにある次の 4 つの小さな引っかかりです。
SSH 接続のたびに再認証を求められる :ローカルデスクトップではすでにログイン済みなのに、SSH 経由で agy を叩くと毎回 OOB ログインリンクが表示される;
マルチリポジトリ間でセッションが混線しやすい :手元で 3〜4 個のリポジトリを同時に開いていると、標準の一覧からうっかり隣プロジェクトの古いセッションを選んでしまい、コンテキストが汚染されたり別ディレクトリを編集してしまったりする;
プロジェクト対応表をハードコードしたくない :リポジトリごとに Project を分けたいものの、新しいリポジトリを作るたびに ~/.zshrc を書き換えるのは手間がかかる;
マルチペインで別ウィンドウへ移ると状態を見失う :Terminator で同時に何本かのセッションを走らせたままブラウザでドキュメントを調べていると、どのペインが完了し、どれがエラーになり、どれが ask_question で選択待ちになっているのか分からなくなる。
本記事では、自分の Linux 開発マシンで実際に稼働させている構成を分解して解説します。依存しているのは Python 標準ライブラリ、jq、xdotool、notify-send だけです。以下に掲載するスクリプトと設定はすべて実環境のファイルそのものです(ユーザー名とホスト名のみマスクしています)。
最終的な仕上がり まず改造後に毎日目にする 3 つの画面――ディレクトリ単位のセッションピッカー、Terminator の 5 色ウィンドウタイトルバー、下部の 2 行カプセル型ステータスバー――を確認します。
普段はどのリポジトリでも agyr と 1 回打つだけで、ログイン情報の再利用、セッションの絞り込み、Project の紐付け、タイトルバーの状態更新、バックグラウンド通知まですべて自動で処理されます。
1. ~/.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{"対話 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 を再利用する 当初、自分の Linux 開発マシンへ SSH 接続して agy を実行すると、毎回 OOB 認証フローをやり直す羽目になっていました。調べてみると原因は明快でした。
SSH シェルにはデフォルトで XDG_RUNTIME_DIR と DBUS_SESSION_BUS_ADDRESS が設定されていないため、すでにロック解除されているローカルデスクトップの Keyring に接続できない;
さらに見落としやすい点として、**agy は環境変数に SSH_CONNECTION / SSH_CLIENT / SSH_TTY のいずれかを検出すると、意図的にデスクトップ Keyring を迂回して**リモート OOB フローへ切り替えます。
対処は 2 段階に分けています。~/.zshrc でランタイム D-Bus のパスを補完しつつ、外側のシェルでグローバルに unset SSH_* は絶対にしない (プロンプト表示、クリップボード判定、その他ツールの SSH 検知が壊れるため)ようにし、agy の子プロセスを起動する瞬間だけ 3 つの環境変数を外します。
1 2 3 4 5 6 7 8 9 10 11 12 13 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 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) 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 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=() 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 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 を入れていました。ところがペインを 5〜6 枚開いた途端、Web 側にランダム名のインスタンスがずらっと並び、どれがどれだか全く見分けがつかなくなってしまいました。
正しい構成は、ターミナルの起動オプションからリモート制御を完全に外し、ユーザー領域の 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 daemonAfter =network.targetStartLimitIntervalSec =0 [Service] Type =simpleExecStart =/home/user/.local/bin/agy remote-control serveRestart =on -failureRestartSec =10 sRestartPreventExitStatus =3 TimeoutStopSec =30 sStandardOutput =journalStandardError =journal[Install] WantedBy =default.target
あわせて ~/.gemini/config/config.json に "cliRemoteControlHostname": "my-dev-host" を設定しておけば、起動時に固定名のインスタンスが 1 つだけ立ち上がります。新しく開いたターミナルは目の前の作業だけに集中でき、Web 側にゴーストインスタンスが溢れることもありません。
2. ハードコード不要で Project を自動導出する(agy-project.py) 最初は .zshrc に case "$PWD" のマッピングを書いて、よく使うリポジトリへ --project を割り当てようとしました。しかし 2 行書いたところで手が止まりました――新しいリポジトリを git clone するたびに .zshrc をメンテするのは、完全に自爆設計です。
そこで、カレントディレクトリから自動で ID を導出し、該当の 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 """Resolve (and lazily create) a native Antigravity Project ID from the current directory.""" import argparseimport hashlibimport jsonimport osimport reimport subprocessDEFAULT_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 へ対応付けられるか事前確認できます。
3. カレントディレクトリで厳密に絞り込むセッションピッカー(agy-pick.py) Project 分離だけではまだ不十分で、標準の再開ピッカーには別ワークスペースの履歴が紛れ込むことがありました。そこで外部依存ゼロの Python TUI ピッカー ~/.gemini/bin/agy-pick.py を自作し、内部の SQLite インデックス DB から現在のディレクトリ/リポジトリに属するセッションだけ を直接抽出するようにしました。
コアとなるフィルタ処理 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) 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
ここには実運用で踏んだ落とし穴を塞ぐ 4 つの工夫が入っています。
読み取り専用オープン+.db 実在チェック :conversation_summaries.db は WAL モードで稼働しているため、必ず mode=ro で開きます。また古いセッションを削除した後にインデックス行だけ残ることがあるため、conversations/<cid>.db の存在確認を入れてデッドエントリを弾いています。
Subagent と空セッションの除外 :step_count > 0 で開いた直後に閉じた空セッションを落とし、COALESCE(parent_conversation_id, '') = '' で裏の Subagent 履歴を除外するだけで、一覧がぐっと見やすくなります。
/dev/tty 直結での TUI 描画 :agyr() がコマンド置換 picked="$(python3 agy-pick.py ...)" で選択結果を受け取るため、stdout は変数にキャプチャされています。対話 UI の描画とキー入力は /dev/tty へ直接行い、最後に選択された conversation_id(または __NEW__)だけを stdout に出力します。
全角文字の幅計算と 2 通りの初期並び順 :unicodedata.east_asian_width で表示幅を計算してタイトルを切り詰めることで、日本語や中国語のタイトルが右端の steps / age を押し出して折り返すのを防いでいます。引数なしの agyr は --new-first で + 新規セッション を先頭に置き(Enter 一発で新規開始)、agyr -r は最新履歴を先頭に置きます(Enter 一発で直前セッションを再開)。
4. 5色ウィンドウタイトル + 非フォーカス時のデスクトップ通知(hooks.json + title.sh) agy は settings.json の title スクリプトでターミナルのウィンドウタイトルを動的に更新できますが、スクリプトへ渡されるリアルタイム JSON に含まれるのは agent_state と tool_confirmation_pending のみです。「待機中 / 実行中 / ツール承認待ち / エラー」までは区別できるものの、「Agent が ask_question を呼んでユーザーの選択を待っている状態」だけは判別できません 。
自分の普段のワークフローでは、まさにこの ask_question が一番放置されやすいポイントでした。タイトルバーが「実行中」のままなのでコードを書いているのだろうと思い込み、10 分後に戻ってみると 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 を削除 + 15秒クールダウン判定
H->>D: 非フォーカス時のみ 🟢 完了 または 🔴 エラー通知を送信
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) タスク完了のたびに無条件でデスクトップ通知を飛ばすと、目の前でターミナルを見ているときまで画面右上にポップアップが出続けてうるさくなります。そこで 3 重の通知抑止を入れています。
フォーカス判定 :xdotool getactivewindow getwindowclassname を呼び出し、現在のアクティブウィンドウがターミナル系ホワイトリスト(Terminator、Kitty、Alacritty、WezTerm、Ghostty など)であれば通知を送らない;
15 秒スロットリング :Stop 通知はセッションキーごとにタイムスタンプ 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 """Antigravity hook: track ask_question state for title.sh and send desktop notifications when unfocused.""" import hashlib, json, os, shutil, subprocess, sys, timefrom pathlib import PathSTATE_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. 5色ウィンドウタイトルスクリプト(~/.gemini/antigravity-cli/title.sh) title.sh を書く際には、以前 Claude Code のステータスバーを作ったときと同じ定番の Bash の落とし穴を踏みました。IFS=$'\t' read で各フィールドを分割すると、branch や title が空だったときに連続するタブが Bash に圧縮され、後ろの変数がすべて左へずれてしまいます。そこで 1 回の jq 実行で 1 フィールド 1 行を出力し、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 pipefailmapfile -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
5. 2行カプセル型ステータスバー(agy-powerline)と settings.json の組み込み ウィンドウタイトルは「別アプリへ切り替えているときやマルチペイン時にひと目で状態を把握する」ための仕組みです。一方、実際にコマンドを打っているアクティブなターミナル下部には、コミュニティ製の agy-powerline をそのまま採用しました(シェルスクリプトを自前で組むより圧倒的に楽で、幅の自動調整やクォータ消化ペース表示まで標準搭載されています)。
自分の ~/.agy-powerline/statusline.config.json は 2 行に分け、「場所・コード状態」と「リソース・クォータ状態」で役割を整理しています。
行
有効化している Widgets
確認できる情報
1 行目
cwd(depth:2) · agentState · git(gitLink) · gitFiles · gitChanges · gitStash · gitWorktree · model · contextTokens(warn:65, crit:85) · mode
どのリポジトリにいるか、ブランチの差分状態、使用中のモデル、コンテキストの逼迫度
2 行目
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 ルートから ID を導出し、~/.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
1 回の jq でリアルタイム状態を解析し、5 色ドット付きのウィンドウタイトルを更新
~/.agy-powerline/statusline.config.json
ターミナル下部の 2 行カプセル型ステータスバー設定
シリーズナビゲーション