agy CLI를 일상 주력 도구로 한동안 쓰다 보면 정작 불편함을 느끼는 부분은 모델의 코드 작성 정확도보다 주변 워크플로우의 자잘한 네 가지 문제입니다.

  1. SSH 접속 시 반복되는 인증 요구: 로컬 데스크톱에서는 이미 로그인해 두었는데, SSH로 접속해 agy를 실행하면 OOB 로그인 링크가 다시 뜹니다.
  2. 멀티 저장소 환경에서의 세션 혼선: 로컬에서 서너 개 저장소를 동시에 띄워 놓고 작업하다 보면 네이티브 목록에서 자칫 옆 프로젝트의 오래된 세션을 열어 컨텍스트가 오염되거나 엉뚱한 디렉터리를 수정하게 됩니다.
  3. 프로젝트 매핑 하드코딩 부담: 저장소마다 Project를 분리하고 싶지만, 새 저장소를 추가할 때마다 ~/.zshrc를 수정하는 것은 번거롭습니다.
  4. 분할 창 전환 시 상태 파악 불가: Terminator에서 여러 세션을 동시에 돌리다가 잠시 브라우저로 문서를 확인하고 오면, 어느 창이 완료되었고 어느 창에서 오류가 났으며 어느 창이 ask_question에서 선택을 기다리는지 알 수 없습니다.

이 글에서는 제 로컬 환경에서 실제로 운영 중인 전체 구성을 단계별로 풀어 설명합니다. 전체 파이프라인은 Python 표준 라이브러리, jq, xdotool, notify-send에만 의존하며, 아래에 수록한 스크립트와 설정은 모두 로컬 실제 파일에서 사용자 이름과 호스트 이름만 마스킹하여 가져왔습니다.

agyr 런처, 디렉터리별 세션 격리 및 터미널 상태 연동 아키텍처


최종 사용 경험은 어떠한가

개선 작업을 마친 뒤 매일 실제로 마주하는 세 가지 인터페이스—디렉터리별 세션 선택기, Terminator 5색 창 제목 표시줄, 하단 2줄 캡슐 상태 표시줄—를 먼저 살펴봅니다.

agy-pick 세션 선택기, title.sh 5색 창 제목 및 agy-powerline 상태 표시줄 미리보기

평소에는 어느 저장소에 들어가든 agyr 명령어 하나만 입력하면 로그인 재사용, 세션 필터링, Project 바인딩, 창 제목 상태 갱신, 백그라운드 알림까지 모두 자동으로 처리됩니다.

진화 안내: 이 글은 Linux 초기 구현 아키텍처(~/.zshrc 인라인 agyr() + title.sh 5색 제목)를 기록한 것입니다. 이후 크로스 플랫폼 재사용(macOS + Linux)과 병렬 실행 시각화를 위해 #4 크로스 플랫폼 백업과 원클릭 초기화에서 독립 모듈 agyr.zsh를 분리하고 title.sh를 순수 Python title.py로 대체했으며, #5 멀티 세션 Chrome 가드레일과 주황색 UI 상태에서 6색 상태 표시줄로 한 단계 더 확장했습니다. 설정을 그대로 도입할 계획이라면 뒤의 두 편도 함께 참고하시기 바랍니다.


1. ~/.zshrc의 agyr()로 실행 진입점 통합하기

먼저 agyr 실행 시의 전체 분기 로직을 살펴보겠습니다. 어떤 경우에 인자를 그대로 전달(pass-through)하고, 어떤 경우에 선택기를 띄우거나 --project를 자동 주입하는지 한눈에 확인할 수 있습니다.

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 흐름으로 전환한다는 사실입니다.

해결책은 두 단계입니다. ~/.zshrc에서 런타임 버스 경로를 채워 주되, 외부 셸에서 전역적으로 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을 넣어 두었습니다. 그런데 분할 창을 대여섯 개 열자 웹 UI에 무작위 인스턴스 이름이 우르르 생겨나 어느 창이 어느 세션인지 전혀 구분할 수 없게 되었습니다.

올바른 방법은 터미널 실행 인자에서 원격 제어를 완전히 제거하고, 사용자 레벨 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" 설정을 결합하면 부팅 시 고정 이름의 인스턴스 하나만 자동 실행되며, 새로 여는 각 터미널 창은 작업에만 집중할 수 있어 웹 쪽에 유령 인스턴스가 쌓이지 않습니다.


2. 하드코딩 없는 자동 Project 파생 (agy-project.py)

처음에는 .zshrc에 case "$PWD" 매핑 테이블을 작성해 자주 쓰는 저장소마다 --project를 지정할까 고민했습니다. 하지만 두 줄 적고 바로 접었습니다. 새 저장소를 클론할 때마다 .zshrc를 고치는 것은 순전히 불필요한 유지보수 부담이기 때문입니다.

더 나은 방식은 스크립트가 현재 디렉터리에서 Project ID를 자동 파생하고, 해당 Project 파일이 없을 때만 지연 생성(lazy creation)하도록 만드는 것입니다.

  • 먼저 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로 매핑되는지 미리 확인한 뒤 실제 파일을 생성할 수 있습니다.


3. 현재 디렉터리만 엄격히 필터링하는 세션 선택기 (agy-pick.py)

Project 격리만으로는 충분하지 않습니다. 네이티브 재개(resume) 선택기에서는 종종 다른 워크스페이스의 이전 기록이 섞여 나오곤 합니다. 그래서 외부 의존성 없는 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)

# 읽기 전용 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. 서브 에이전트 및 빈 세션 제외: step_count > 0으로 열자마자 닫은 빈 세션을 제거하고, COALESCE(parent_conversation_id, '') = ''로 백그라운드 Subagent 기록을 제외하면 목록이 훨씬 깔끔해집니다.
  3. /dev/tty 직접 연결로 TUI 렌더링: agyr()가 picked="$(python3 agy-pick.py ...)" 명령 치환으로 선택 결과를 캡처하므로 stdout은 변수로 리다이렉트됩니다. 따라서 대화형 UI는 /dev/tty를 직접 읽고 써야 하며, 마지막에 선택된 conversation_id(또는 __NEW__)만 stdout으로 출력합니다.
  4. 전각 문자 폭 정렬 + 두 가지 기본 정렬: unicodedata.east_asian_width로 표시 너비를 계산해 제목을 자름으로써 한글·CJK 제목이 오른쪽 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만 들어 있어 ‘유휴 / 실행 중 / 도구 승인 대기 / 오류’는 구분할 수 있지만, 유독 “에이전트가 ask_question을 호출해 사용자의 선택을 기다리는 상태”만 구분하지 못합니다.

실제 업무 흐름에서 ask_question은 사람을 가장 자주 방치하게 만드는 지점입니다. 창 제목은 여전히 “실행 중”으로 떠 있어서 코드를 짜는 줄 알고 10분 뒤 돌아와 보면, 사실은 한참 전에 멈춰서 A안과 B안 중 고르기를 기다리고 있는 경우가 허다합니다.

전체 상태 연동 흐름

아주 가벼운 로컬 플래그 파일 하나로 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 알림은 세션 키별로 타임스탬프 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. 5색 창 제목 스크립트 (~/.gemini/antigravity-cli/title.sh)

title.sh를 작성할 때 과거 Claude Code 상태 표시줄을 만들면서 겪었던 것과 똑같은 함정을 다시 마주쳤습니다. 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

5. 2줄 캡슐 상태 표시줄 (agy-powerline)과 settings.json 연동

창 제목 표시줄은 “다른 앱으로 전환했거나 분할 창이 여러 개일 때 상태를 한눈에 보는” 용도이고, 현재 명령을 입력 중인 터미널 하단에는 커뮤니티 도구인 agy-powerline을 그대로 사용합니다(직접 셸 상태 표시줄을 짜는 것보다 훨씬 간편하며 너비 자동 조절과 쿼터 게이지까지 기본 제공합니다).

제 ~/.agy-powerline/statusline.config.json은 “위치/코드 상태”와 “리소스/쿼터 상태”로 역할을 나누어 두 줄로 구성했습니다.

줄 활성화한 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 루트 기준으로 ~/.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 파싱으로 실시간 상태를 읽어 5색 원형 상태등 창 제목 출력
~/.agy-powerline/statusline.config.json 하단 2줄 캡슐 상태 표시줄 설정

시리즈 내비게이션