Kanji
・Cloud engineer / freelance ・Born in 1993 ・From Ehime / Living in Shibuya, Tokyo ・5 years AWS experience Profile details
How I used Antigravity Hooks, Python, and Codex CLI to synchronize session titles across four states, including endpoint and authentication mistakes, daemon discovery, manual rename protection, input hashes, contextual classification at Stop, and security caveats.
Table of Contents
Running several agent sessions in parallel made the session list an operational bottleneck: I could identify each conversation, but I still had to open it to determine whether work was continuing, a login or approval was required, or the turn had reached a stopping point. Overlooking a session that required human action left both the agent and me waiting.
Based on Antigravity 2.38.0 , OpenAI Codex CLI 0.171.0 , and gpt-6.1-sol in my tested environment, I built automatic session-title synchronization using Hooks, Python, and codex exec . The title combines the next required action with the project and task names:
2.38.0
0.171.0
gpt-6.1-sol
codex exec
{➡️|🖐️|👀|🎉} [project name] task name
The task name identifies the conversation, while the emoji makes the next action visible without reopening it. Hook events launch Python to organize the state and update the title through Antigravity’s ConversationService; Codex CLI classifies context only when explicit rules are insufficient.
The main implementation work was in connection discovery, conflicts with existing titles, and stale-state handling. This article follows those boundaries and explains the checks needed to keep title synchronization consistent.
The initial design had five states, including 📢 for announcements. In practice, announcements already belonged to either 👀 when review was required or 🎉 when work had reached a stopping point. Removing 📢 kept the list focused on the next action and left four operational states:
📢
👀
🎉
PreInvocation
PostToolUse
Stop
human_todo
ask_question
ask_permission
PreToolUse
ai_confirming
ai_done
Both 🖐️ and 👀 wait for a person, but the required action differs:
🖐️
This distinction lets me anticipate the required action before opening a session. ➡️ includes waiting for background results as well as active processing, because work on the agent’s side is still ongoing. Similarly, 🎉 includes a normally completed turn at a temporary stopping point and does not imply completion of the entire project.
➡️
State classification depends on who needs to act next, as well as on the last event. Keeping those meanings consistent makes the display useful without adding more notification categories.
Hook events and session states have different boundaries: Stop can occur while approval is pending or background work is still running. I therefore use events as triggers and assign state management, contextual classification, and title updates to separate components:
hooks.json
annotations.title
PreInvocation starts with ➡️ . An ask_question or ask_permission at PreToolUse produces 👀 . Ongoing PostToolUse normally uses ➡️ .
When explicit states such as a task tracker’s human_todo or ai_confirming are available, I use them as evidence. There is no need to infer everything from natural language.
Stop is where contextual classification becomes particularly useful. The decision flow is:
The code below isolates the essentials of connection detection, hash comparison, and process cleanup. These are implementation examples, not a complete drop-in replacement for the entire Hook.
The first connection attempt used /ConversationService/ and the CSRF header x-codeium-csrf-token , resulting in 404/401 responses. In the tested environment, title updates required the fully qualified service path:
/ConversationService/
x-codeium-csrf-token
http://$ANTIGRAVITY_LS_ADDRESS/product.v1.ConversationService/UpdateConversation
It also required these two headers:
Connect-Protocol-Version: 1 x-antigravity-csrf-token: <value of ANTIGRAVITY_CSRF_TOKEN>
The service name requires the product.v1. prefix, and authentication uses x-antigravity-csrf-token . These failures occur before title-generation logic becomes relevant, so the response code determines the first diagnostic step:
product.v1.
x-antigravity-csrf-token
Both the path and the header needed correction before synchronization succeeded. These details were verified with Antigravity 2.38.0 ; because this is an internal API dependency, compatibility with other versions requires separate verification.
Correcting the API request still did not update new sessions. A manual invocation through run_command could read the following connection variables, which initially obscured the difference between the execution environments:
run_command
ANTIGRAVITY_LS_ADDRESS ANTIGRAVITY_CSRF_TOKEN
The Hook process did not inherit either variable, even though both were available to run_command . Processes launched by the same Antigravity instance can receive different environments depending on their execution path, so a successful manual invocation does not establish that Hook connection discovery will succeed.
I found connection information stored here:
~/.gemini/antigravity/daemon/hub_*.json
The files contained at least these fields:
pid
httpPort
csrfToken
The revised implementation uses the environment variables when both are present and otherwise discovers the connection through hub files. Because stale daemon files can remain and the files contain authentication tokens, discovery applies the following checks before selecting a candidate:
os.kill(pid, 0)
mtime
O_NOFOLLOW
The essential code is:
import json import os import stat from pathlib import Path def resolve_connection(): address = os.environ.get("ANTIGRAVITY_LS_ADDRESS") token = os.environ.get("ANTIGRAVITY_CSRF_TOKEN") if address and token: return address, token directory = Path.home() / ".gemini/antigravity/daemon" candidates = [] for path in directory.glob("hub_*.json"): try: fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) with os.fdopen(fd, "r", encoding="utf-8") as stream: file_stat = os.fstat(stream.fileno()) if file_stat.st_uid != os.getuid(): continue if not stat.S_ISREG(file_stat.st_mode): continue hub = json.load(stream) pid = hub["pid"] port = hub["httpPort"] csrf_token = hub["csrfToken"] if type(pid) is not int or pid <= 0: continue if type(port) is not int or not 1 <= port <= 65535: continue if not isinstance(csrf_token, str) or not csrf_token: continue os.kill(pid, 0) candidates.append( ( file_stat.st_mtime_ns, f"127.0.0.1:{port}", csrf_token, ) ) except (OSError, ValueError, TypeError, KeyError): continue if not candidates: raise RuntimeError("No valid Antigravity daemon found") _, address, token = max(candidates, key=lambda item: item[0]) return address, token
The UID check uses the opened file descriptor so that ownership validation applies to the file actually read. This fallback lets the Hook obtain connection information without inherited environment variables, while avoiding full hub-file logging that could expose CSRF tokens.
The checks have specific limits: os.kill(pid, 0) establishes process liveness without proving API health, and O_NOFOLLOW rejects symlinks only at the final path component rather than validating every parent directory. API failures therefore still require separate handling after discovery.
Once connection discovery worked, the initial manual-rename protection rule blocked every update. I had treated any existing title as a user edit, but Antigravity automatically sets annotations.title immediately after a session starts. The Hook therefore always encountered an existing title and skipped synchronization.
Protection needs synchronization history to distinguish the initial automatic title from a later external edit. I record two fields in the state file:
lastSyncedTitle
pendingTitle
When neither field exists, the first synchronization replaces Antigravity’s initial title. After synchronization begins, the current title is compared with lastSyncedTitle and pendingTitle ; a title matching neither is protected as an external change, such as a manual rename. The resulting rules are:
Manual rename protection starts only after the first synchronization.
This boundary cannot distinguish a manual rename made before the first synchronization from Antigravity’s initial automatic title. I accepted that limitation because the intended protection applies to titles explicitly changed after synchronization starts. pendingTitle also represents an attempted update rather than confirmed success, so lastSyncedTitle is finalized only after the API update succeeds.
With connection discovery and title protection working, the remaining classification errors came from stale completion state and ambiguous review requests. These require separate handling: input identity establishes whether saved state still applies, while contextual interpretation determines whether the current message blocks progress.
A saved ai_done state persists after completion. If it retains priority when a follow-up instruction arrives, the title stays at 🎉 even though new work has started. I added doneInputHash to associate completion with a specific input, using its SHA-256 hash for comparison with the current instruction:
doneInputHash
import hashlib def input_hash(user_input: str) -> str: return hashlib.sha256(user_input.encode("utf-8")).hexdigest()
The rules are:
A changed hash invalidates the old 🎉 rather than automatically selecting ➡️ ; the current instruction still needs evaluation for human operation, review, or ongoing work. The hash source must also remain stable, since a modification timestamp or current title would change the hash without a new instruction.
Hashing input text alone treats identical resubmissions as the same input. If each submission needs its own completion boundary, the identity definition must include an input identifier or equivalent evidence.
Input hashes address state freshness, but keyword matching cannot reliably distinguish a closing review request from approval that blocks further work. The following messages illustrate the difference:
Example A: Implementation and tests are complete. Please review. Example B: May I apply this change? I will proceed after approval.
Example A may be a polite closing after completed work, while Example B explicitly makes approval a prerequisite for execution. Matching “review,” “approval,” or “please review” cannot establish that dependency; classification needs to determine whether an answer or approval is actually required before progress can continue.
For ambiguous context at Stop , I use codex exec with constrained input and structured output. The invocation below shows the relevant options; the schema path is illustrative:
codex exec \ --ephemeral \ --skip-git-repo-check \ -s read-only \ -C /tmp \ -c 'model_reasoning_effort="low"' \ -c 'mcp_servers={}' \ -c 'features.shell_tool=false' \ --output-schema /path/to/stop-status.schema.json
The tested classifier uses Codex CLI 0.171.0 with gpt-6.1-sol . Since it only interprets supplied text, I set the working directory to /tmp , select a read-only sandbox, provide an empty MCP server configuration, and disable the shell tool.
/tmp
--output-schema constrains the result to fixed values, avoiding another regular expression to interpret free-form output. The following schema defines the four classification results:
--output-schema
{ "type": "object", "properties": { "status": { "type": "string", "enum": [ "running", "human_action", "needs_review", "done" ] } }, "required": ["status"], "additionalProperties": false }
This is an example output schema. Python fixes the mapping from classification values to emojis:
running
human_action
needs_review
done
The classifier evaluates the dependencies that determine the next action:
Quoted text and content being worked on must not be treated as instructions to the classifier itself.
Classification took about 7.13 seconds in my measurement, with latency dependent on the individual request. I run codex exec outside the state-file lock so that waiting for the external model does not block other state updates for the duration of classification.
This creates a separate consistency requirement: a new instruction or Hook event can arrive before classification finishes. Before applying the result, the input hash or state generation must be checked again so that an older result cannot overwrite newer state.
The classifier has a 20-second timeout. Because terminating only the parent can leave child processes running, I launch Codex CLI in its own process group and clean up the group with os.killpg(..., signal.SIGKILL) when the timeout expires. The essential process-management code is:
os.killpg(..., signal.SIGKILL)
import os import signal import subprocess def classify_with_codex(prompt: str, schema_path: str) -> str | None: command = [ "codex", "exec", "--ephemeral", "--skip-git-repo-check", "-s", "read-only", "-C", "/tmp", "-c", 'model_reasoning_effort="low"', "-c", "mcp_servers={}", "-c", "features.shell_tool=false", "--output-schema", schema_path, ] process = subprocess.Popen( command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, start_new_session=True, ) try: stdout, _stderr = process.communicate( input=prompt, timeout=20, ) except subprocess.TimeoutExpired: try: os.killpg(process.pid, signal.SIGKILL) except ProcessLookupError: pass process.communicate() return None if process.returncode != 0: return None return stdout
start_new_session=True allows cleanup to include descendant processes that remain in the same process group. On success, stdout is parsed as JSON and the classification is checked against the allowed values before application; it is never used directly as a title.
start_new_session=True
A timeout or classification failure is not evidence of completion. The normal Stop default of 🎉 and the classifier failure policy are separate decisions. On failure, possible policies include updating only what explicit state supports, or preserving the current title when the state cannot be determined.
This mechanism uses the title as a status display as well as a conversation name. That requires keeping the surrounding assumptions consistent.
Read-only mode and a disabled shell tool restrict local operations, but supplied text is still sent to the model. Classification input should therefore be limited to the current instruction, recent response, unresolved operations or approvals, and background-work status. CSRF tokens, hub-file contents, and unrelated credentials are outside that scope.
ai_done represents task state, doneInputHash identifies the input to which completion applies, and lastSyncedTitle records a successful title update. Keeping them separate avoids conflating task completion with input freshness or synchronization success.
The decision rules evaluate four independent properties: whether the task is complete, whether completion applies to the current input, whether the title update succeeded, and whether the title changed outside synchronization. That separation makes follow-up instructions and manual renames easier to handle consistently.
A title that remains unchanged can indicate failure at several different stages. I check each boundary separately:
Logs should make these stages visible without indiscriminately recording tokens or entire conversations.
A useful session list makes the next required action visible without requiring a detailed view of the agent’s internal state. The four prefixes provide that operational distinction:
Reliable synchronization depends on consistent evidence and a clear validity boundary for each state. Correct endpoint and header handling establish connectivity, hub-file discovery handles missing Hook environment variables, synchronization history protects manual renames, and input hashes prevent stale completion from carrying over to new instructions.
With those deterministic checks in Python, Codex CLI handles the remaining ambiguity in language at Stop . The version-specific internal API and classifier latency remain operational dependencies, so they need to be rechecked when the environment changes.
Real-time AI quant analysis of earnings reports, corporate filings, and momentum indicators for global equities and Japanese stocks.
Master conversation skills with realistic AI phone training and 5-axis feedback. Includes 16-lesson interactive academy and studio AI portraits.
Effortlessly snap receipts for instant AI itemization. Integrated with LINE for seamless group expense tracking and pain-free settlement.
Interactive AI personas (Fortune Teller, Butler, Bartender) host real-time games, challenges, and conversation starters for unforgettable gatherings.
Unbiased healthcare database featuring zero-additive filters and active ingredient cost performance metrics.