Once you use agy CLI as your daily driver for a while, the friction rarely comes from model code quality. It comes from four recurring papercuts around the edges:

  1. Repeated auth prompts over SSH: Even when your local desktop session is already signed in, running agy over SSH still prompts you with an out-of-band (OOB) login link.
  2. Cross-repo session collisions: With three or four repositories open locally, it is far too easy to pick a stale conversation from a neighboring project in the native list—polluting context at best, editing the wrong directory at worst.
  3. Hardcoded project mappings: Separating native Projects per repository is useful, but editing ~/.zshrc every time you add a new repo is pure overhead.
  4. Lost visibility across split panes: Running several sessions in Terminator and switching over to a browser to check docs leaves you blind to which pane finished, which one errored out, and which one is blocked on ask_question waiting for your input.

This post walks through the exact setup running on my daily Linux workstation. The entire pipeline relies only on the Python standard library, jq, xdotool, and notify-send. Every script and config snippet below comes straight from the live files on my machine (with only the username and hostname redacted).

Architecture of the agyr launcher, directory-scoped session isolation, and terminal status integration


What the Finished Setup Looks Like

Here are the three interfaces you actually see every day after the upgrade—the directory-scoped session picker, the 5-color Terminator window title bar, and the two-line powerline status bar at the bottom:

Preview of the agy-pick session picker, title.sh 5-color terminal title, and agy-powerline status bar

In any repository, you run a single command: agyr. Keyring reuse, session filtering, Project binding, window title updates, and background notifications all happen automatically.

Evolution note: This post documents the initial Linux implementation (agyr() inline in ~/.zshrc + title.sh 5-color title bar). To support cross-platform reuse (macOS + Linux) and visual concurrency troubleshooting, #4 Cross-Platform Backup and One-Click Bootstrap later extracts agyr.zsh into a standalone module and replaces title.sh with pure-Python title.py, while #5 Multi-Session Chrome Guardrails and Orange UI Status expands the indicator to six colors. If you plan to adopt these configs directly, read those two posts alongside this one.


1. Taking Over the Launch Entry Point with agyr() in ~/.zshrc

Here is the full launch decision flow for agyr—showing when arguments pass straight through, when the picker opens, and when --project gets injected automatically:

1. Reusing an Unlocked Local Desktop Keyring over SSH

Early on, SSHing into my Linux dev box and running agy always forced a fresh OOB auth flow. The root cause turned out to be straightforward:

  • SSH shells lack XDG_RUNTIME_DIR and DBUS_SESSION_BUS_ADDRESS by default, so they cannot reach the already-unlocked local desktop keyring.
  • More subtly, whenever agy sees SSH_CONNECTION, SSH_CLIENT, or SSH_TTY in its environment, it deliberately bypasses the desktop keyring and falls back to remote OOB authentication.

The fix takes two steps: populate the runtime bus paths in ~/.zshrc, and never run unset SSH_* globally in the outer shell (doing so breaks shell prompts, clipboard detection, and other SSH-aware tooling). Instead, strip those three variables only for the agy subprocess:

1
2
3
4
5
6
7
8
9
10
11
12
13
# Reuse the unlocked local desktop Keyring (D-Bus) and display over SSH to avoid repeated agy auth prompts
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

# Trigger auto-compaction at 80% context usage instead of scrambling near the hard limit
export AGY_CLI_AUTO_COMPACT_OVERRIDE="80%"

2. The Complete agyr() Function

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 bypasses the local desktop Keyring when SSH_* vars are set; strip them only for the agy subprocess when the local bus is available
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

# Interactive launch with no args or bare -r/--resume: open the directory/repo-scoped session picker
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

# Pass subcommands and help/version flags straight through without injecting session arguments
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

# Add personal permission presets here if desired; leave empty to use the default sandbox
agyr_defaults=()

# Do not override --project when a project or resume flag was explicitly provided
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

# Auto-derive and lazily create the native Project for the current repo/directory
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. Pitfall: Never Bake --remote-control into agyr

My first draft included --remote-control inside agyr_defaults so I could take over any terminal from a phone or browser. Opening five or six split panes immediately flooded the web UI with randomly named instances, making it impossible to tell which pane was which.

The clean fix is to remove --remote-control from interactive launches completely and run a single persistent daemon via user-level 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

Pair that with "cliRemoteControlHostname": "my-dev-host" in ~/.gemini/config/config.json. You get one stable, predictable remote-control endpoint at boot, while every interactive terminal stays focused on local work without spawning ghost entries in the web UI.


2. Auto-Deriving Projects Without Hardcoding (agy-project.py)

At first I considered writing a case "$PWD" lookup table in .zshrc to assign --project per repository. Two lines in, I scrapped it—updating .zshrc every time you clone a repo is pure maintenance tax.

A better design derives the Project ID from the working directory and lazily creates the Project file only when missing:

  • Run git -C <cwd> rev-parse --show-toplevel first so launching agyr from any subdirectory normalizes to the same Git root.
  • Outside a Git repo, fall back to realpath(cwd).
  • Explicitly exclude /, $HOME, /tmp, and /tmp/* so shared scratch directories never spawn junk Projects.
  • Sanitize the directory basename into a valid slug, falling back to an 8-character SHA-256 hash prefix of the path if it collides with reserved IDs (empty string or default-cli-project).
  • Create ~/.gemini/config/projects/<slug>.json atomically via os.open(..., O_WRONLY | O_CREAT | O_EXCL) so concurrent terminal launches never clobber each other or write truncated JSON.

The implementation lives at ~/.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())

You can also run python3 ~/.gemini/bin/agy-project.py --dry-run in any directory to preview the derived Project ID before writing anything to disk.


3. A Directory-Scoped Session Picker (agy-pick.py)

Project isolation alone is not enough—the native resume picker can still surface conversations from other workspaces. To eliminate cross-project noise completely, I wrote a zero-dependency Python TUI picker (~/.gemini/bin/agy-pick.py) that queries the underlying SQLite index directly and filters strictly to sessions belonging to the current directory or repository.

Core Filtering Logic

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)

# Open via read-only URI so we never contend with agy's SQLite WAL writes
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

Four hard-won details make this picker reliable in day-to-day use:

  1. Read-only mode + .db existence check: conversation_summaries.db runs in WAL mode, so opening it with mode=ro guarantees zero write contention. Checking that conversations/<cid>.db still exists also filters out orphaned index rows left behind after pruning old sessions.
  2. Exclude subagents and empty sessions: step_count > 0 drops abandoned sessions closed immediately after launch, and COALESCE(parent_conversation_id, '') = '' strips background subagent entries, keeping the list clean.
  3. Render the TUI directly against /dev/tty: Because agyr() captures the chosen ID via command substitution (picked="$(python3 agy-pick.py ...)"), stdout is redirected into a shell variable. The interactive TUI reads and draws straight to /dev/tty, writing only the selected conversation_id (or __NEW__) to stdout on exit.
  4. Wide-character alignment + dual default ordering: Truncating titles using unicodedata.east_asian_width prevents CJK characters from wrapping the right-aligned steps / age columns. Bare agyr passes --new-first so + New session sits on row 1 (press Enter to start fresh immediately), whereas agyr -r puts the most recent session first (press Enter to resume immediately).

4. 5-Color Terminal Title + Unfocused Desktop Notifications (hooks.json + title.sh)

agy lets you configure a title command in settings.json to update the terminal title dynamically, but the real-time JSON payload it pipes in only exposes agent_state and tool_confirmation_pending. That covers idle, running, awaiting tool approval, and error—but has no way to distinguish “the Agent called ask_question and is waiting for you to pick an option.”

In practice, ask_question is the #1 silent stall: the window title still shows “running”, you assume the agent is busy writing code, and ten minutes later you tab back to find it has been waiting for you to choose A or B the whole time.

End-to-End State Pipeline

A lightweight flag file in /tmp bridges Hooks and title.sh:

1. Hooks Configuration (~/.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. State Tracking and Anti-Spam Notification Script (ask-question-state.py)

Firing a desktop toast on every single stop gets noisy fast when you are already staring at the terminal. The script adds three anti-spam guardrails:

  • Active-window focus check: Queries xdotool getactivewindow getwindowclassname. If the focused window matches any terminal class in the allowlist (Terminator, Kitty, Alacritty, WezTerm, Ghostty, etc.), it stays silent.
  • 15-second cooldown: Tracks per-session timestamps in notify-<key>.ts so back-to-back Stop events never spam notifications.
  • Escape hatch + non-blocking allow: Set AGY_NO_NOTIFY=1 to mute everything during screen recordings or demos. On PreToolUse, the script must print {"decision": "allow"} so it never blocks the tool call.
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 Awaiting Choice ({label})", "The agent asked a question. Return to the terminal to confirm your choice.")
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 Error ({label})", "The session stopped due to an error. Return to the terminal for details.", "critical")
elif reason == "NO_TOOL_CALL" and fully_idle and not should_throttle(tk):
send_desktop_notification(f"🟢 Antigravity Complete ({label})", "The current task has finished responding.", "low")
print("{}")
return 0

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

3. 5-Color Terminal Title Script (~/.gemini/antigravity-cli/title.sh)

One classic Bash pitfall from writing status bars showed up here too: parsing multiple fields with IFS=$'\t' read collapses consecutive whitespace whenever branch or title is empty, shifting every subsequent variable to the left. Using a single jq call that emits one field per line into mapfile -t eliminates field-shift bugs altogether:

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

# Parse live session status JSON in one jq pass; read line-by-line to prevent IFS whitespace collapsing on empty fields
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

5. Two-Line Powerline Status Bar (agy-powerline) and settings.json Wiring

The window title gives you glanceable status when you tab away or juggle split panes. For the bottom bar of your active terminal, I use the community agy-powerline package—far less maintenance than a hand-rolled shell status bar, with built-in width adaptation and quota pacing meters.

My ~/.agy-powerline/statusline.config.json splits widgets across two rows—location/code status on row 1, resource/quota telemetry on row 2:

Row Enabled Widgets What It Shows
Row 1 cwd(depth:2) · agentState · git(gitLink) · gitFiles · gitChanges · gitStash · gitWorktree · model · contextTokens(warn:65, crit:85) · mode Current repo, working tree state, active model, and context budget pressure
Row 2 title(maxWidth:24) · tasks(alwaysShow) · queue · cacheHit · fiveHourPct · fiveHourReset · weeklyPct · weeklyReset · sessionTime · tokensToday Background tasks and queued prompts, prompt cache hit rate, and remaining 5-hour/weekly quota

Finally, wire both statusLine and title into ~/.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
}
}

If you enable enableTerminalSandbox: true, double-check permissions.deny in settings.json: read_file(...) entries must specify exact directory paths (such as read_file(/home/user/.ssh)), never /** wildcards. Otherwise sandbox validation fails outright and blocks every sandboxed command.


Full Script Inventory

Every piece of this setup lives in user-level directories and leaves project repositories untouched:

File Responsibility
~/.zshrc (agyr) SSH keyring reuse, picker launch on bare/-r invocation, subcommand passthrough, automatic --project injection
~/.gemini/bin/agy-project.py Derives Project ID from Git root and atomically creates ~/.gemini/config/projects/<slug>.json on demand
~/.gemini/bin/agy-pick.py Queries conversation_summaries.db read-only and filters sessions strictly to the current directory/repo
~/.config/systemd/user/antigravity-cli-daemon.service Runs a single persistent agy remote-control serve instance (see Part 12 of the Field Guide for Remote Control internals and loginctl enable-linger)
~/.gemini/config/hooks.json + hooks/ask-question-state.py Tracks ask_question waiting flags and sends unfocused desktop notifications
~/.gemini/antigravity-cli/title.sh Parses live session JSON in a single jq pass and renders the 5-color terminal title
~/.agy-powerline/statusline.config.json Two-line powerline status bar at the bottom of the terminal

Series Navigation