Skip to content

Reason Network: your team's coding agents, talking to each other. The engine behind `reason network`.

feat: deliver Antigravity messages natively with durable receipts (#177)

reason-machines-staging[bot]1e62d6a960f9
diff --git a/Cargo.lock b/Cargo.lock
index 5bce9a5..f494d5f 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2757,7 +2757,7 @@ dependencies = [
[[package]]
name = "reason-network"
-version = "0.12.15"
+version = "0.12.16"
dependencies = [
"anyhow",
"blake3",
diff --git a/Cargo.toml b/Cargo.toml
index 9f16b75..cc391a7 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "reason-network"
-version = "0.12.15"
+version = "0.12.16"
edition = "2024"
description = "Reason Network: the team directory and message bus behind reason network, for coding agents across machines"
license = "MIT OR Apache-2.0"
diff --git a/DESIGN.md b/DESIGN.md
index ca5c967..a83b590 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -344,14 +344,27 @@ The hard part. Each session advertises a **delivery tier** so senders know when
| Reason | push | Its agent runs in Reason's cloud: the daemon lists live sessions (`reason session list --json`, when `reason = true`) and sends with `reason session send`. Replies go through the CLI: `reason-network send <to> --from <its address>`. |
| Amp | push | Plugin: `thread.appendUserMessage(…, {steer:true})`. |
| Cursor | turn | `postToolUse` `additional_context`; `stop` `followup_message`. Idle: background `reason-network wait`. |
-| Gemini CLI | turn | `AfterTool` `additionalContext`; `AfterAgent` block. Idle: experimental background-shell inject. |
+| Gemini CLI | turn | `BeforeAgent` / `AfterTool` `additionalContext`; `AfterAgent` deny continues with mail. Idle waits for the next prompt. |
+| Antigravity | App: push; CLI: turn | Native `conversationId` hooks inject `userMessage` steps before an invocation, or continue a natural Stop with pending mail. The App-managed sidecar subscribes to daemon delivery events and invokes `agentapi send-message` for that existing conversation; acknowledgment follows command acceptance. `session_id` identifies concurrent chats independently of their shared project. |
| Command Code | turn | `SessionStart` context; `PostToolUse` `additionalContext`; `Stop` `decision:block`. The MCP server follows the session registered by its hooks. |
| Copilot CLI | turn | `postToolUse` `additionalContext`; `agentStop` block; `notification` hook. |
| Grok CLI | turn | `PostToolUse` `additionalContext`; `Stop` (`end_turn`) block. SessionStart and prompt-submit output are dropped; subagents' hooks are ignored. |
| DeepSeek Harness | pull | MCP only: `setup` adds our server to `$DSH_HOME/cordis.patch.yml`, which dsh applies to every profile. |
| any MCP client | pull | Tools + unread notice on every tool result + `check_inbox(wait_secs)` long-poll. |
-MCP notifications are not a delivery path: no client passes them to the model (checked Oct 2026).
+MCP notifications are not a delivery path: native adapters hand messages to the agent's supported input mechanism.
+
+`message_status` reads content-free outgoing receipts for seven days. Destination acceptance, queued delivery,
+confirmed local agent handoff and explicit reply are separate observations; a remote handoff stays unobserved until
+there is evidence. Local `send_message` accepts a session-scoped idempotency key: a retry returns the original receipt,
+and conflicting content is refused. The hosted relay uses its durable request id for that key.
+Native local queue acceptance (`codex queue`, Antigravity's `agentapi`) is an input handoff, not proof the model read
+or acted on it. `reason session send` only acknowledges its remote server, so it remains destination acceptance.
+Antigravity App bindings are marked by native hooks on the canonical persisted session rows; its sidecar restores
+them after daemon restarts without relying on the lifetime of a hook-runner process. Explicit native session ids
+are a local-user routing mechanism, not isolation between conversations owned by that same user on the machine.
+The sidecar is authorized by the same local socket permissions. Restoring a binding revalidates every workspace
+reported by its native hook, and an off-folder hook revokes that binding until a new allowed hook registers it.
Gotcha: Cursor, Copilot CLI and Devin load **Claude Code's** hooks from `~/.claude/settings.json`, so
`reason-network hook` must detect which agent is actually calling it.
diff --git a/README.md b/README.md
index b72d1d4..eeb70be 100644
--- a/README.md
+++ b/README.md
@@ -47,13 +47,21 @@ That's it. Ask any agent "who's on the network?", tell it to ask someone's agent
## What you get
-- **Every agent on the team.** Agents get three tools, `list_team`, `send_message` and `ask_user`, plus
+- **Every agent on the team.** Agents get `list_team`, `send_message`, `message_status` and `ask_user`, plus
`check_inbox` where messages can't be pushed, under the MCP server `reason-network`. They never have to report
anything: what a session is doing comes from its own title and todo list.
- **Messages reach each agent on its delivery path.** Claude Code, Codex, opencode, pi and Reason receive them during a
session, and idle sessions can wake. Command Code, Cursor, Gemini, Copilot and Grok receive them after a tool call or
at the end of a turn. DeepSeek Harness gets them when it checks its inbox. Every tool result says if mail is waiting.
Existing Claude sessions join without a restart.
+- **Native Antigravity conversations.** Setup installs its MCP configuration and native hooks. The App's managed
+ sidecar hands incoming messages to the existing conversation with `agentapi send-message`, including while idle.
+ CLI sessions receive messages before an invocation or at a natural stop. Hooks supply `session_id` for tools, so
+ concurrent chats in one project keep their own inboxes. Explicitly disabled sidecars and hooks stay disabled.
+- **Check progress without resending.** `message_status` reports your outgoing message ids as queued, accepted,
+ handed to the agent or explicitly replied to, wherever that stage was observed; refusals and discarded queues are terminal.
+ Remote acceptance does not establish
+ agent handoff. Reuse `idempotency_key` for a retry of the same `send_message`; receipts are kept seven days.
- **ZCode Desktop too.** `setup` adds the MCP server to `~/.zcode/cli/config.json` (or `~/.agents/mcp.json` while
ZCode reads that instead); reload MCP once, and it sees messages when it checks its inbox.
- **Small text files go along.** A message can carry up to 10 text files (markdown, code, JSON, logs, config; 256 KB
@@ -158,6 +166,9 @@ at Reason.
## Usage measurement
The engine keeps optional aggregate usage counters in a separate local SQLite file.
+Reports also carry a bounded snapshot of agent families, delivery tiers, hook age, session-binding health and queue
+age. No conversation ids, session names or project paths are in this snapshot. `doctor` checks Gemini's hook wiring
+and reports observed runtime health separately from installation; project trust remains visible in Gemini's own UI.
When the Reason CLI carries the network, it reports recent daily aggregates about every
five minutes, in bounded background batches: agent families, local or remote routing, verified account relationships,
transport paths, delivery stages, linked replies, size and latency buckets, session
diff --git a/src/agent.rs b/src/agent.rs
index a83b905..2849973 100644
--- a/src/agent.rs
+++ b/src/agent.rs
@@ -55,6 +55,8 @@ pub fn from_client_name(name: &str) -> Option<&'static str> {
"codex"
} else if has("cursor") {
"cursor"
+ } else if has("antigravity") {
+ "antigravity"
} else if has("gemini") {
"gemini"
} else if has("grok") {
@@ -87,7 +89,7 @@ pub fn from_client_name(name: &str) -> Option<&'static str> {
/// Agents that run one MCP server process for many sessions, so the session must come from each call.
pub fn multiplexed(agent: &str) -> bool {
- matches!(agent, "codex" | "opencode" | "cursor")
+ matches!(agent, "codex" | "opencode" | "cursor" | "antigravity")
}
/// The session id an agent exports to its MCP servers, if any. `REASON_NETWORK_SESSION` is set by our own pi extension.
@@ -117,7 +119,7 @@ pub fn env_session_id(agent: &str) -> Option<String> {
/// The session id carried in a tool call's `_meta`. Codex sends `sessionId` (the root thread, the same id its
/// hooks see) and `threadId` (which differs inside subagents); opencode V2 sends `ai.opencode/sessionID`.
pub fn meta_session_id(meta: &serde_json::Map<String, Value>) -> Option<String> {
- ["sessionId", "ai.opencode/sessionID", "threadId"]
+ ["conversationId", "sessionId", "ai.opencode/sessionID", "threadId"]
.iter()
.find_map(|k| meta.get(*k).and_then(Value::as_str))
.filter(|s| !s.is_empty())
diff --git a/src/antigravity.rs b/src/antigravity.rs
new file mode 100644
index 0000000..b486351
--- /dev/null
+++ b/src/antigravity.rs
@@ -0,0 +1,50 @@
+//! The App launches this sidecar with agentapi on PATH. Mail arrives over the existing daemon event stream.
+use crate::{agent, client::Link, proto::*, util};
+use anyhow::{Context, Result};
+use serde_json::Value;
+use std::{process::Stdio, time::Duration};
+use tokio::{sync::mpsc, task::JoinSet};
+
+pub fn app_transcript(path: &str) -> bool {
+ path.replace('\\', "/").contains("/.gemini/antigravity/brain/")
+}
+
+pub async fn run() -> Result<()> {
+ agent::command_for("agentapi").context("Antigravity must launch this sidecar with agentapi on PATH")?;
+ let (tx, mut events) = mpsc::unbounded_channel();
+ let link = Link::new(Some(tx));
+ let mut heartbeat = tokio::time::interval(Duration::from_secs(5));
+ let mut deliveries = JoinSet::new();
+ loop {
+ tokio::select! {
+ _ = heartbeat.tick() => {
+ // Reattaches after daemon restart, discovers newly opened conversations, and retries failed handoffs.
+ if link.call::<Value>(Request::AntigravityAttach).await.is_err() {
+ eprintln!("Reason Network: waiting for the local delivery service");
+ }
+ }
+ Some(Event::Deliver { key, ids, text }) = events.recv() => {
+ let link = link.clone();
+ deliveries.spawn(async move {
+ let Some(id) = key.strip_prefix("antigravity:") else { return };
+ let Some(command) = agent::command_for("agentapi") else {
+ let _ = link.call::<Value>(Request::PushFailed {key,ids}).await;
+ return;
+ };
+ let result = tokio::time::timeout(Duration::from_secs(30),
+ util::no_window(tokio::process::Command::from(command))
+ .args(["send-message", id, &text]).stdin(Stdio::null())
+ .stdout(Stdio::null()).stderr(Stdio::null()).kill_on_drop(true).status()).await;
+ let request = if matches!(result, Ok(Ok(status)) if status.success()) {
+ Request::Delivered { key, ids }
+ } else {
+ eprintln!("Reason Network: Antigravity handoff failed; the same messages remain queued");
+ Request::PushFailed { key, ids }
+ };
+ let _ = link.call::<Value>(request).await;
+ });
+ }
+ Some(_) = deliveries.join_next(), if !deliveries.is_empty() => {}
+ }
+ }
+}
diff --git a/src/daemon/antigravity.rs b/src/daemon/antigravity.rs
new file mode 100644
index 0000000..9ff0123
--- /dev/null
+++ b/src/daemon/antigravity.rs
@@ -0,0 +1,85 @@
+use super::Daemon;
+use crate::{
+ git::GitInfo,
+ proto::{SessionReg, Tier},
+ util,
+};
+use anyhow::Result;
+use std::{sync::Arc, time::Instant};
+
+impl Daemon {
+ pub(super) fn attach_antigravity(self: &Arc<Self>, conn: u64) -> Result<usize> {
+ // Native hooks mark canonical session rows as App conversations. Restore those bindings after restarts
+ // without asking an idle agent to run again; arbitrary MCP registrations cannot create an App binding.
+ let bindings = {
+ let mut g = self.inner.lock().unwrap();
+ self.prune(&mut g);
+ let candidates = g.store.native_app_sessions(util::now_ms() - super::sessions::FORGET_MS)?;
+ let mut allowed = Vec::new();
+ for candidate in candidates {
+ if g.store
+ .native_app_roots(&candidate.0.key)?
+ .is_some_and(|roots| roots.iter().all(|root| !self.cfg.off_in(root)))
+ {
+ allowed.push(candidate);
+ }
+ }
+ allowed
+ };
+ for (known, hook_at) in &bindings {
+ if self.inner.lock().unwrap().live.contains_key(&known.key) {
+ continue;
+ }
+ let Some(id) = known.key.strip_prefix("antigravity:") else { continue };
+ let reg = SessionReg {
+ key: known.key.clone(),
+ agent: "antigravity".into(),
+ cwd: known.cwd.clone(),
+ agent_session_id: Some(id.into()),
+ pid: None,
+ tier: Tier::Push,
+ name: Some(known.name.clone()),
+ };
+ let git = GitInfo { root: None, repo: known.repo.clone(), branch: known.branch.clone() };
+ if self.register(Some(conn), reg, git).is_err() {
+ continue;
+ }
+ if let Some(l) = self.inner.lock().unwrap().live.get_mut(&known.key) {
+ l.last_hook = Some(*hook_at);
+ }
+ }
+ let mut g = self.inner.lock().unwrap();
+ self.prune(&mut g);
+ g.antigravity_conn = Some(conn);
+ let keys: Vec<String> = g
+ .live
+ .iter()
+ .filter(|(_, l)| {
+ // CLI conversations have no verified App binding and retain hook delivery.
+ l.reg.agent == "antigravity"
+ && l.last_hook.is_some()
+ && bindings.iter().any(|(known, _)| known.key == l.reg.key)
+ && l.retry.is_none_or(|(at, _)| Instant::now() >= at)
+ })
+ .map(|(key, _)| key.clone())
+ .collect();
+ let mut changed = false;
+ for key in &keys {
+ let l = g.live.get_mut(key).expect("selected above");
+ changed |= l.conn != Some(conn) || !l.mcp_push || l.reg.tier != Tier::Push || !l.attached;
+ l.conn = Some(conn);
+ l.mcp_push = true;
+ l.reg.tier = Tier::Push;
+ l.attached = true;
+ let address = self.addr(&l.name);
+ let waiting = g.pending(&address)?.into_iter().filter(|m| m.wake).collect::<Vec<_>>();
+ if !waiting.is_empty() {
+ self.deliver(&mut g, key, waiting, true);
+ }
+ }
+ if changed {
+ self.presence_changed();
+ }
+ Ok(keys.len())
+ }
+}
diff --git a/src/daemon/diagnostics.rs b/src/daemon/diagnostics.rs
new file mode 100644
index 0000000..b6c630f
--- /dev/null
+++ b/src/daemon/diagnostics.rs
@@ -0,0 +1,26 @@
+use super::Daemon;
+use crate::util;
+use anyhow::Result;
+use serde_json::{Value, json};
+
+impl Daemon {
+ pub(super) fn diagnostics(&self) -> Result<Value> {
+ let mut g = self.inner.lock().unwrap();
+ self.prune(&mut g);
+ let now = util::now_ms();
+ let mut sessions = Vec::new();
+ for l in g.live.values().take(64) {
+ let (unread, oldest) = g.store.queue_health(&self.addr(&l.name))?;
+ sessions.push(json!({
+ "agent": crate::usage::family(&l.reg.agent), "tier": l.reg.tier,
+ "status": l.status.as_ref().map_or("live", |(s, _)| s.as_str()),
+ "hookAgeMs": l.last_hook.map(|at| now.saturating_sub(at).max(0)),
+ "sessionLinked": l.reg.agent_session_id.as_ref().is_some_and(|id| l.reg.key == format!("{}:{id}", l.reg.agent)),
+ "adapterConnected": l.mcp_push && l.conn.is_some_and(|id| g.conns.contains_key(&id)),
+ "unread": unread, "queueAgeMs": oldest.map(|at| now.saturating_sub(at).max(0)),
+ }));
+ }
+ // These snapshots leave the machine: no names, paths, conversation ids, or message contents.
+ Ok(json!({"observedAt": now, "sessions": sessions, "truncated": g.live.len() > 64}))
+ }
+}
diff --git a/src/daemon/mail.rs b/src/daemon/mail.rs
index 18629b6..8fb5fed 100644
--- a/src/daemon/mail.rs
+++ b/src/daemon/mail.rs
@@ -120,6 +120,28 @@ impl Daemon {
approval: Option<Box<Signed<Approval>>>,
files: Vec<Attachment>,
) -> Result<SendResult> {
+ self.send_idempotent(from, to, body, reply_to, wake, notify, approval, files, None).await
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ pub(super) async fn send_idempotent(
+ self: &Arc<Self>,
+ from: String,
+ to: &str,
+ body: &str,
+ reply_to: Option<String>,
+ wake: bool,
+ notify: bool,
+ approval: Option<Box<Signed<Approval>>>,
+ files: Vec<Attachment>,
+ idempotency_key: Option<String>,
+ ) -> Result<SendResult> {
+ if idempotency_key.as_ref().is_some_and(|key| key.is_empty() || key.len() > 200) {
+ bail!("idempotency key must be 1 to 200 bytes");
+ }
+ if idempotency_key.is_some() && (is_group(to.trim()) || notify && to.trim() == self.person) {
+ bail!("idempotency keys are for one agent session");
+ }
let (body, to) = (body.trim(), to.trim());
if body.is_empty() {
bail!("empty message");
@@ -135,6 +157,8 @@ impl Daemon {
let mut res = SendResult { ids: Vec::new(), recipients: Vec::new() };
let mut remote_jobs = Vec::new();
+ let mut send_key = None;
+ let mut send_nonce = String::new();
{
let mut g = self.inner.lock().unwrap();
self.prune(&mut g);
@@ -154,6 +178,21 @@ impl Daemon {
None => "unknown",
};
let exclude = sender.reg.key.clone();
+ if let Some(key) = &idempotency_key {
+ let key = blake3::hash(serde_json::to_string(&(&self.person, &exclude, key))?.as_bytes())
+ .to_hex()
+ .to_string();
+ let fingerprint =
+ blake3::hash(serde_json::to_string(&(to, body, &reply_to, wake, notify, &files))?.as_bytes())
+ .to_hex()
+ .to_string();
+ let (nonce, receipt) = g.store.begin_send(&key, &fingerprint, now)?;
+ if let Some(receipt) = receipt {
+ return Ok(receipt);
+ }
+ send_nonce = nonce;
+ send_key = Some(key);
+ }
// It talks to teammates: its name stays its own.
self.reached(&mut g, &exclude);
// A person at a terminal may message a group; an agent picks the one session it needs.
@@ -202,8 +241,28 @@ impl Daemon {
}
let targets = if own { Vec::new() } else { self.resolve(&g, &remotes, to, Some(&exclude))? };
for t in targets {
+ // A crash between queuing and saving the receipt retries the same peer id, never a new message.
+ let id = if let Some(key) = &send_key {
+ let generation = if send_nonce.is_empty() { key.clone() } else { format!("{key}:{send_nonce}") };
+ let hash = blake3::hash(format!("{generation}:{}", t.shown_address()).as_bytes());
+ Ulid::from(u128::from_be_bytes(hash.as_bytes()[..16].try_into().expect("16 bytes"))).to_string()
+ } else {
+ Ulid::generate().to_string()
+ };
+ if let Some(old) = g.store.message(&id)? {
+ res.ids.push(id);
+ res.recipients.push(Recipient {
+ address: t.shown_address(),
+ state: "accepted".into(),
+ note: format!(
+ "already accepted for {}; the original message is retained without resending",
+ old.to
+ ),
+ });
+ continue;
+ }
let mut msg = Message {
- id: Ulid::generate().to_string(),
+ id,
from: from_addr.clone(),
from_agent: from_agent.clone(),
from_repo: from_repo.clone(),
@@ -267,6 +326,7 @@ impl Daemon {
let mut attachment_size = dims.clone();
attachment_size.bucket = crate::usage::size(files.iter().map(|f| f.content.len()).sum()).into();
self.usage.count("attachment_bytes", attachment_size, 1);
+ g.store.record_sent(&exclude, &msg, &shown, "queued")?;
let (state, mut note): (String, String) = match t {
_ if !matches!(t, Target::Remote { .. }) && !g.loop_ok(&msg.from, &msg.to) => {
("refused".into(), LOOP_NOTE.into())
@@ -310,6 +370,11 @@ impl Daemon {
note = format!("{note}; {}", self.notify(&msg).1);
}
res.recipients.push(Recipient { address: shown, state, note });
+ let _ = g.store.send_outcome(&msg.id, &res.recipients.last().expect("just added").state);
+ }
+ // The durable outbox now owns remote retries. A lost API response returns this same receipt.
+ if let Some(key) = &send_key {
+ g.store.finish_send(key, &res)?;
}
}
self.arrived.notify_waiters();
@@ -338,6 +403,9 @@ impl Daemon {
}
}
}
+ if let Some(key) = &send_key {
+ self.inner.lock().unwrap().store.finish_send(key, &res)?;
+ }
Ok(res)
}
@@ -391,7 +459,7 @@ impl Daemon {
// These adapters take Deliver events on this connection. Codex and Reason still
// use their native channels below, even when their MCP client registers as push.
(Tier::Push, Some(conn), _)
- if l.mcp_push && matches!(l.reg.agent.as_str(), agent::CLAUDE_CODE | "hermes") =>
+ if l.mcp_push && matches!(l.reg.agent.as_str(), agent::CLAUDE_CODE | "hermes" | "antigravity") =>
{
Channel::ClaudeSocket(conn)
}
@@ -433,10 +501,7 @@ impl Daemon {
for id in ids {
g.in_flight.insert(id, Instant::now());
}
- (
- "pushed".into(),
- "delivered into the session: it reads it between tool calls, or wakes up if idle".into(),
- )
+ ("pushed".into(), "accepted by the delivery adapter; waiting for its handoff acknowledgment".into())
}
Channel::Command(bin, args) => {
for id in &ids {
@@ -515,12 +580,20 @@ impl Daemon {
self.usage.stage(id, "push_failed");
}
let mut g = self.inner.lock().unwrap();
+ let _ = g.store.queue_again(ids);
for id in ids {
g.in_flight.remove(id);
}
if let Some(l) = g.live.get_mut(key) {
l.mcp_push = false;
l.reg.tier = l.reg.tier.max(Tier::Pull);
+ if l.reg.agent == "antigravity" {
+ let wait = l.retry.map_or(Duration::from_secs(10), |(_, wait)| (wait * 2).min(Duration::from_secs(60)));
+ l.retry = Some((Instant::now() + wait, wait));
+ if l.last_hook.is_some() {
+ l.reg.tier = Tier::Turn;
+ }
+ }
}
log(&format!("pushing to {}: its MCP server knows no inbox; left unread", self.logged(&g, key)));
drop(g);
@@ -539,6 +612,7 @@ impl Daemon {
match res {
Ok(Ok(())) => {
let changed = g.store.mark_read(&ids, util::now_ms()).unwrap_or_default();
+ let _ = g.store.handoff(&changed, util::now_ms());
for id in &changed {
this.usage.stage(id, "delivered");
}
@@ -597,8 +671,12 @@ impl Daemon {
match res {
Ok(()) => {
let changed = g.store.mark_read(&ids, util::now_ms()).unwrap_or_default();
- for id in &changed {
- this.usage.stage(id, "delivered");
+ // A local native queue is an agent input handoff; the cloud command only acknowledges its server.
+ if bin != "reason" {
+ let _ = g.store.handoff(&changed, util::now_ms());
+ for id in &changed {
+ this.usage.stage(id, "delivered");
+ }
}
if let Some(l) = g.live.get_mut(&key) {
l.retry = None;
@@ -773,6 +851,7 @@ impl Daemon {
let ids: Vec<String> = messages.iter().map(|m| m.id.clone()).collect();
let changed = g.store.mark_read(&ids, util::now_ms())?;
if g.live.get(&key).is_some_and(|l| l.through_reason == Some(false)) {
+ g.store.handoff(&changed, util::now_ms())?;
for id in &changed {
self.usage.stage(id, "delivered");
}
diff --git a/src/daemon/mod.rs b/src/daemon/mod.rs
index 88a1039..2ca9621 100644
--- a/src/daemon/mod.rs
+++ b/src/daemon/mod.rs
@@ -2,7 +2,9 @@
//! mailboxes. Split by concern: `sessions` (who is running here), `directory` (who is where, and resolving
//! addresses), `mail` (sending, receiving, delivering), `teamops` (membership and the network).
+mod antigravity;
mod ask;
+mod diagnostics;
mod directory;
mod mail;
mod notify;
@@ -149,6 +151,7 @@ struct Inner {
store: Store,
live: HashMap<String, Live>,
conns: HashMap<u64, mpsc::UnboundedSender<String>>,
+ antigravity_conn: Option<u64>,
next_conn: u64,
team: Option<TeamState>,
/// Messages handed to a push channel or a hook and not yet confirmed; hidden from inbox and hooks meanwhile.
@@ -245,6 +248,7 @@ impl Daemon {
store,
live: HashMap::new(),
conns: HashMap::new(),
+ antigravity_conn: None,
next_conn: 0,
team,
in_flight: HashMap::new(),
@@ -357,13 +361,16 @@ impl Daemon {
}
Request::SetStatus { key, doing, name } => json!(self.set_status(&key, doing, name)?),
Request::Who { me, filter, all } => json!(self.who(me, filter, all).await?),
- Request::Send { from, to, body, reply_to, wake, notify, files, purpose } => {
+ Request::Send { from, to, body, reply_to, wake, notify, files, purpose, idempotency_key } => {
let dims = crate::usage::Dimensions {
bucket: purpose.unwrap_or_else(|| "unknown".into()),
..Default::default()
};
self.usage.count("purpose", dims, 1);
- json!(self.send(from, &to, &body, reply_to, wake, notify, None, files).await?)
+ json!(
+ self.send_idempotent(from, &to, &body, reply_to, wake, notify, None, files, idempotency_key)
+ .await?
+ )
}
Request::Inbox { key, wait_secs, peek } => json!(self.inbox(key, wait_secs.min(MAX_WAIT), peek).await?),
Request::Unread { key } => json!(self.unread(&key)?),
@@ -385,6 +392,12 @@ impl Daemon {
for id in &ids {
g.in_flight.remove(id);
}
+ if handed_to_agent {
+ g.store.handoff(&changed, util::now_ms())?;
+ }
+ if let Some(l) = g.live.get_mut(&key) {
+ l.retry = None;
+ }
Value::Null
}
Request::PushFailed { key, ids } => {
@@ -401,7 +414,24 @@ impl Daemon {
Request::Proof { jws } => json!(self.attach_proof(&jws)?),
Request::Invite { me, hours } => json!(self.invite(me, hours).await?),
Request::Team => json!(self.team_info()?),
- Request::Usage => json!(self.usage.snapshot()),
+ Request::Usage => {
+ let mut report = json!(self.usage.snapshot());
+ if report.is_object() {
+ report["health"] = self.diagnostics()?;
+ }
+ report
+ }
+ Request::Diagnostics => self.diagnostics()?,
+ Request::DeliveryStatus { from, ids } => {
+ json!(self.inner.lock().unwrap().store.delivery_status(&from, &ids)?)
+ }
+ Request::AntigravityAttach => json!(self.attach_antigravity(conn)?),
+ Request::AntigravitySession { conversation_id } => {
+ let mut g = self.inner.lock().unwrap();
+ self.prune(&mut g);
+ let key = format!("antigravity:{conversation_id}");
+ json!(g.live.get(&key).filter(|l| l.last_hook.is_some()).map(|_| key))
+ }
Request::Link { new } => json!(self.link(new).await?),
Request::Remove { who } => json!(self.remove(&who)?),
Request::Leave { force } => json!(self.leave(force).await?),
diff --git a/src/daemon/sessions.rs b/src/daemon/sessions.rs
index daf1797..ffecec4 100644
--- a/src/daemon/sessions.rs
+++ b/src/daemon/sessions.rs
@@ -66,6 +66,13 @@ impl Daemon {
let mut g = self.inner.lock().unwrap();
let g = &mut *g;
let key = reg.key.clone();
+ if reg.agent == "antigravity" && conn.is_some() && reg.tier == Tier::Push {
+ let allowed =
+ g.store.native_app_roots(&key)?.is_some_and(|roots| roots.iter().all(|root| !self.cfg.off_in(root)));
+ if !allowed {
+ bail!("Antigravity App binding is unavailable or includes a disabled workspace");
+ }
+ }
// Its hooks said its folder is off (an MCP server several sessions share can't know its folder).
if g.off.contains_key(&key) {
bail!(OFF_HERE);
@@ -328,9 +335,13 @@ impl Daemon {
let (agent, event) = (agent.as_str(), event.as_str());
let key = format!("{agent}:{session_id}");
let now = util::now_ms();
+ let mut native_dirs: Vec<String> = cwd.iter().chain(&dirs).cloned().collect();
// In a folder that is off, by any folder the agent names: never a session here, only noted as off.
if cwd.iter().chain(&dirs).any(|d| self.cfg.off_in(d)) {
let mut g = self.inner.lock().unwrap();
+ if agent == "antigravity" {
+ g.store.remember_native_app(&key, None, &[])?;
+ }
if let Some(l) = g.live.remove(&key) {
let _ = g.store.touch_session(&l.name, now);
self.presence_changed();
@@ -351,8 +362,13 @@ impl Daemon {
self.inner.lock().unwrap().off.remove(&key);
if event == "end" {
let mut g = self.inner.lock().unwrap();
+ if agent == "antigravity" {
+ g.store.remember_native_app(&key, None, &[])?;
+ }
// Gemini's MCP server outlives a conversation (`/clear`): its hooks say when one ends.
- if g.live.get(&key).is_some_and(|l| l.conn.is_none() || agent::session_from_hooks(agent))
+ if g.live
+ .get(&key)
+ .is_some_and(|l| l.conn.is_none() || agent::session_from_hooks(agent) || agent == "antigravity")
&& let Some(l) = g.live.remove(&key)
{
let _ = g.store.touch_session(&l.name, now);
@@ -417,6 +433,15 @@ impl Daemon {
}
let address = self.addr(&l.name);
let agent_kind = l.reg.agent.clone();
+ let native_app = agent == "antigravity"
+ && l.transcript.as_ref().is_some_and(|p| crate::antigravity::app_transcript(&p.to_string_lossy()));
+ if native_app {
+ l.reg.pid = None;
+ if !native_dirs.contains(&l.reg.cwd) {
+ native_dirs.push(l.reg.cwd.clone());
+ }
+ g.store.remember_native_app(&key, Some(now), &native_dirs)?;
+ }
// Mid-turn, only what should interrupt; at a pause, everything.
let msgs: Vec<Message> = if mail {
g.pending(&address)?.into_iter().filter(|m| event != "tool" || m.wake).collect()
@@ -495,12 +520,24 @@ impl Daemon {
let now = util::now_ms();
let mut g = self.inner.lock().unwrap();
g.conns.remove(&conn);
+ if g.antigravity_conn == Some(conn) {
+ g.antigravity_conn = None;
+ }
let mine: Vec<String> = g.live.iter().filter(|(_, l)| l.conn == Some(conn)).map(|(k, _)| k.clone()).collect();
for key in mine {
let l = g.live.get_mut(&key).expect("listed above");
// Hooks still vouch for it: keep it, reachable through them.
- if l.last_hook.is_some() && l.reg.pid.is_some_and(util::pid_alive) {
+ if l.last_hook.is_some()
+ && (l.reg.pid.is_some_and(util::pid_alive)
+ || l.reg.agent == "antigravity"
+ && l.reg.pid.is_none()
+ && l.last_hook.is_some_and(|at| now - at < HOOK_TTL_MS))
+ {
l.conn = None;
+ if l.reg.agent == "antigravity" {
+ l.reg.tier = Tier::Turn;
+ l.mcp_push = false;
+ }
continue;
}
if let Some(l) = g.live.remove(&key) {
diff --git a/src/hook.rs b/src/hook.rs
index 3c618c1..d16902d 100644
--- a/src/hook.rs
+++ b/src/hook.rs
@@ -57,10 +57,12 @@ async fn handle(
let session_id = session
.or_else(|| str_at("session_id"))
.or_else(|| str_at("conversation_id"))
+ .or_else(|| str_at("conversationId"))
.or_else(|| str_at("sessionId"))?;
// Every folder the agent names for the session, the one it works in first.
let mut dirs: Vec<String> = str_at("cwd").into_iter().collect();
dirs.extend(v["workspace_roots"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string));
+ dirs.extend(v["workspacePaths"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string));
dirs.extend(
["CURSOR_PROJECT_DIR", "GEMINI_CWD", "CLAUDE_PROJECT_DIR"]
.iter()
@@ -82,18 +84,22 @@ async fn handle(
("doing", _) => "doing",
_ => return None,
};
- let mail = !off && takes_mail(agent, event);
+ let mail = !off
+ && takes_mail(agent, event)
+ && !(agent == "antigravity" && event == "stop" && v["terminationReason"] != "model_stop");
let key = format!("{agent}:{session_id}");
+ let native_app =
+ agent == "antigravity" && str_at("transcriptPath").as_deref().is_some_and(crate::antigravity::app_transcript);
let req = Request::Hook(HookCall {
through_reason: Some(false),
agent: agent.to_string(),
event: ev.to_string(),
session_id,
cwd,
- pid: agent::hook_agent_pid(),
+ pid: if native_app { None } else { agent::hook_agent_pid() },
mail,
- transcript: str_at("transcript_path"),
+ transcript: str_at("transcript_path").or_else(|| str_at("transcriptPath")),
doing,
name: None,
dirs: dirs.into_iter().skip(1).collect(),
@@ -107,19 +113,31 @@ async fn handle(
let text = match (reply.text, ev, reply.address) {
(Some(t), ..) => t,
// Say who it is on Reason Network once, at session start.
- (None, "start", Some(addr)) => {
+ (None, "start" | "prompt", Some(addr)) if ev == "start" || agent == "antigravity" => {
format!(
"Reason Network: you are {addr}. Teammates' agents can message you; list_team and send_message reach them."
)
}
_ => return None,
};
+ let text = if agent == "antigravity" {
+ format!(
+ "{text}\nFor Reason Network tools, pass session_id: {}. This identifies this conversation even when other chats use the same project.",
+ key.strip_prefix("antigravity:").unwrap_or(&key)
+ )
+ } else {
+ text
+ };
Some((format_for(agent, event, ev, &text), key, ids))
}
/// Prompt-submit hooks in Cursor, Copilot and grok can't add context, grok drops what SessionStart prints, and
/// opencode's status call shows nothing.
fn takes_mail(agent: &str, event: &str) -> bool {
+ // Antigravity consumes injectSteps before invocation, and a continue reason at a natural Stop.
+ if agent == "antigravity" {
+ return matches!(event, "session-start" | "user-prompt-submit" | "stop");
+ }
!matches!(
(agent, event),
("cursor" | "copilot" | "grok", "user-prompt-submit") | ("grok", "session-start") | (_, "status" | "doing")
@@ -137,6 +155,8 @@ fn format_for(agent: &str, event: &str, ev: &str, text: &str) -> String {
let specific = |name: &str| json!({ "hookSpecificOutput": { "hookEventName": name, "additionalContext": text } });
let block = || json!({ "decision": "block", "reason": text });
let out = match (agent, ev) {
+ ("antigravity", "start" | "prompt") => json!({"injectSteps": [{"userMessage": text}]}),
+ ("antigravity", "stop") => json!({"decision":"continue","reason":text}),
("opencode", _) if event == "poll" => return text.to_string(),
("codex" | "cmd", "start") => specific("SessionStart"),
("cmd", "tool") => specific("PostToolUse"),
@@ -147,7 +167,8 @@ fn format_for(agent: &str, event: &str, ev: &str, text: &str) -> String {
("gemini", "start") => specific("SessionStart"),
("gemini", "prompt") => specific("BeforeAgent"),
("gemini", "tool") => specific("AfterTool"),
- ("codex" | "gemini" | "copilot" | "grok", "stop") => block(),
+ ("gemini", "stop") => json!({"decision": "deny", "reason": text}),
+ ("codex" | "copilot" | "grok", "stop") => block(),
("cursor", "stop") => json!({ "followup_message": text }),
("cursor", _) => json!({ "additional_context": text }),
("copilot", _) => json!({ "additionalContext": text }),
diff --git a/src/main.rs b/src/main.rs
index a3845bf..88ee982 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,4 +1,5 @@
mod agent;
+mod antigravity;
mod bridge;
mod claude;
mod client;
@@ -311,6 +312,9 @@ enum Cmd {
Mcp,
/// Local JSON-lines transport for native agent adapters
Bridge,
+ /// Run the App-managed Antigravity delivery sidecar
+ #[command(hide = true)]
+ AntigravitySidecar,
/// The menu bar icon (macOS; the background service starts it)
#[command(hide = true)]
Tray,
@@ -328,6 +332,7 @@ async fn main() -> Result<()> {
r
}
Some(Cmd::Mcp) => mcp::run().await,
+ Some(Cmd::AntigravitySidecar) => antigravity::run().await,
Some(Cmd::Bridge) => bridge::run().await,
// Blocks this (the main) thread with AppKit's event loop; its daemon calls run on the runtime's workers.
Some(Cmd::Tray) => tray::run(),
@@ -460,6 +465,7 @@ async fn cli(cmd: Cmd) -> Result<()> {
// Messages come from agent sessions: `--from`'s, this agent's, or from a plain terminal, `<you>/terminal`.
// An agent shell Reason Network doesn't know (its tools aren't loaded) counts as a terminal.
let send = |from: String| Request::Send {
+ idempotency_key: None,
purpose: purpose.clone(),
from,
to: to.clone(),
@@ -706,7 +712,13 @@ async fn cli(cmd: Cmd) -> Result<()> {
println!("The daemon is not running.");
}
}
- Cmd::Daemon { .. } | Cmd::Mcp | Cmd::Bridge | Cmd::Hook { .. } | Cmd::Tray | Cmd::Endpoint => {
+ Cmd::Daemon { .. }
+ | Cmd::Mcp
+ | Cmd::Bridge
+ | Cmd::AntigravitySidecar
+ | Cmd::Hook { .. }
+ | Cmd::Tray
+ | Cmd::Endpoint => {
unreachable!("handled in main")
}
}
diff --git a/src/mcp.rs b/src/mcp.rs
index 04865fe..8e98ab0 100644
--- a/src/mcp.rs
+++ b/src/mcp.rs
@@ -42,6 +42,9 @@ fn instructions() -> String {
#[derive(Debug, Deserialize, JsonSchema)]
pub struct ListArgs {
+ /// Antigravity: the conversation id supplied by your Reason Network hook. Other agents omit it.
+ #[serde(default)]
+ pub session_id: Option<String>,
/// Only sessions matching this text (person, session, agent, repo, branch, directory or what it's doing).
#[serde(default)]
pub filter: Option<String>,
@@ -52,6 +55,12 @@ pub struct ListArgs {
#[derive(Debug, Deserialize, JsonSchema)]
pub struct SendArgs {
+ /// Antigravity: the conversation id supplied by your Reason Network hook. Other agents omit it.
+ #[serde(default)]
+ pub session_id: Option<String>,
+ /// Reuse this key when retrying the same message after a lost response. A new key sends a new message.
+ #[serde(default)]
+ pub idempotency_key: Option<String>,
/// "person/session@machine" from list_team; a reply goes to the message's from (with notify, `to` may be your
/// user's name).
pub to: String,
@@ -70,8 +79,20 @@ pub struct SendArgs {
pub files: Option<Vec<String>>,
}
+#[derive(Debug, Deserialize, JsonSchema)]
+pub struct DeliveryArgs {
+ /// Antigravity: the conversation id supplied by your Reason Network hook. Other agents omit it.
+ #[serde(default)]
+ pub session_id: Option<String>,
+ /// Message ids returned by send_message. This checks progress without sending again.
+ pub ids: Vec<String>,
+}
+
#[derive(Debug, Deserialize, JsonSchema)]
pub struct AskArgs {
+ /// Antigravity: the conversation id supplied by your Reason Network hook. Other agents omit it.
+ #[serde(default)]
+ pub session_id: Option<String>,
/// What they need to decide: who asks for what, and why.
pub question: String,
/// When it's about a teammate's message, its id (the `id="…"` of their `<reason-message>`): your user sees that
@@ -82,6 +103,9 @@ pub struct AskArgs {
#[derive(Debug, Deserialize, JsonSchema)]
pub struct InboxArgs {
+ /// Antigravity: the conversation id supplied by your Reason Network hook. Other agents omit it.
+ #[serde(default)]
+ pub session_id: Option<String>,
/// If nothing is waiting, wait up to this many seconds for a message (max 600). Default 0.
#[serde(default)]
pub wait_secs: Option<u64>,
@@ -157,6 +181,26 @@ pub async fn run() -> Result<()> {
#[tool_router]
impl ReasonNetworkMcp {
+ #[tool(
+ description = "Check your outgoing messages without resending: queued, accepted, handed_to_agent, replied, rejected or expired. Remote agent handoff may be unobserved; accepted does not mean read. Receipts become unknown after seven days.",
+ annotations(read_only_hint = true, open_world_hint = false)
+ )]
+ async fn message_status(
+ &self,
+ Parameters(a): Parameters<DeliveryArgs>,
+ ctx: RequestContext<RoleServer>,
+ ) -> Result<CallToolResult, McpError> {
+ let key = match self.session_for(&ctx, a.session_id.as_deref()).await {
+ Ok(key) => key,
+ Err(e) => return Ok(failure(e)),
+ };
+ let result = self
+ .link
+ .call::<Value>(Request::DeliveryStatus { from: key.clone(), ids: a.ids })
+ .await
+ .map(|v| v.to_string());
+ Ok(self.finish(&key, result, true).await)
+ }
#[tool(
description = "List your team's live agent sessions: who, which machine and agent, repo@branch, busy/idle, \
and what each is doing. Use it to find the right recipient.",
@@ -167,7 +211,7 @@ impl ReasonNetworkMcp {
Parameters(a): Parameters<ListArgs>,
ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, McpError> {
- let key = match self.session_for(&ctx).await {
+ let key = match self.session_for(&ctx, a.session_id.as_deref()).await {
Ok(k) => k,
Err(e) => return Ok(failure(e)),
};
@@ -182,7 +226,7 @@ impl ReasonNetworkMcp {
Parameters(a): Parameters<SendArgs>,
ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, McpError> {
- let key = match self.session_for(&ctx).await {
+ let key = match self.session_for(&ctx, a.session_id.as_deref()).await {
Ok(k) => k,
Err(e) => return Ok(failure(e)),
};
@@ -192,6 +236,7 @@ impl ReasonNetworkMcp {
Err(e) => return Ok(failure(e)),
};
let req = Request::Send {
+ idempotency_key: a.idempotency_key,
purpose: None,
from: key.clone(),
to: a.to,
@@ -214,7 +259,7 @@ impl ReasonNetworkMcp {
Parameters(a): Parameters<AskArgs>,
ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, McpError> {
- let key = match self.session_for(&ctx).await {
+ let key = match self.session_for(&ctx, a.session_id.as_deref()).await {
Ok(k) => k,
Err(e) => return Ok(failure(e)),
};
@@ -241,7 +286,7 @@ impl ReasonNetworkMcp {
Parameters(a): Parameters<InboxArgs>,
ctx: RequestContext<RoleServer>,
) -> Result<CallToolResult, McpError> {
- let key = match self.session_for(&ctx).await {
+ let key = match self.session_for(&ctx, a.session_id.as_deref()).await {
Ok(k) => k,
Err(e) => return Ok(failure(e)),
};
@@ -319,6 +364,8 @@ impl ReasonNetworkMcp {
.or_else(|| meta?.get("io.modelcontextprotocol/clientInfo")?.get("name")?.as_str().map(str::to_string));
match name.as_deref().and_then(agent::from_client_name) {
Some(a) => {
+ // The explicit Antigravity profile selects its native hook ABI even with a shared Gemini SDK name.
+ let a = if a == "gemini" && self.env_agent == Some("antigravity") { "antigravity" } else { a };
*self.client_agent.lock().unwrap() = Some(a);
a
}
@@ -326,8 +373,16 @@ impl ReasonNetworkMcp {
}
}
- async fn session_for(&self, ctx: &RequestContext<RoleServer>) -> Result<String> {
+ async fn session_for(&self, ctx: &RequestContext<RoleServer>, explicit: Option<&str>) -> Result<String> {
let agent = self.agent(&ctx.peer, Some(&ctx.meta));
+ if agent == "antigravity" {
+ let id = explicit.map(str::to_string).or_else(|| agent::meta_session_id(&ctx.meta));
+ let found: Option<String> = match id {
+ Some(conversation_id) => self.link.call(Request::AntigravitySession { conversation_id }).await?,
+ None => self.link.call(Request::Attach { agent: agent.into(), cwd: agent::cwd() }).await?,
+ };
+ return found.ok_or_else(|| anyhow::anyhow!("Antigravity conversation is not identified. Pass the session_id from this conversation's Reason Network hook; if absent, reload the configured hooks and start a new invocation."));
+ }
self.session(agent, agent::meta_session_id(&ctx.meta)).await
}
diff --git a/src/proto.rs b/src/proto.rs
index 6f7a8bf..3112277 100644
--- a/src/proto.rs
+++ b/src/proto.rs
@@ -112,6 +112,9 @@ pub enum Request {
},
/// From an agent session: its key (or, for agents that reply through the CLI, its address or name).
Send {
+ /// Reuse for the same logical send, including after a lost response. Scoped to the sending session.
+ #[serde(default)]
+ idempotency_key: Option<String>,
/// Local analytics only; never included in the peer message.
#[serde(default, deserialize_with = "crate::usage::purpose")]
purpose: Option<String>,
@@ -208,6 +211,19 @@ pub enum Request {
Team,
/// Local aggregate counters, read only by clients that opt into usage reporting.
Usage,
+ /// App-managed Antigravity sidecar subscribes to native delivery events on this connection.
+ AntigravityAttach,
+ /// Resolve an explicit native conversation only after its hook registered it.
+ AntigravitySession {
+ conversation_id: String,
+ },
+ /// Local delivery health, without message contents.
+ Diagnostics,
+ /// Delivery progress for this session's own outgoing messages; never returns their bodies.
+ DeliveryStatus {
+ from: String,
+ ids: Vec<String>,
+ },
/// The team link, which anyone can use to join; `new` replaces it.
Link {
#[serde(default)]
diff --git a/src/setup.rs b/src/setup.rs
index cd4dc99..407485f 100644
--- a/src/setup.rs
+++ b/src/setup.rs
@@ -14,6 +14,8 @@ use std::{
process::Command,
};
+mod antigravity;
+mod gemini;
mod hermes;
mod zcode;
@@ -1258,7 +1260,7 @@ fn me(exe: &Path) -> String {
s[1..s.len() - 1].to_string()
}
-const AGENTS: [Agent; 13] = [
+const AGENTS: [Agent; 14] = [
Agent {
id: "claude",
name: "Claude Code",
@@ -1330,9 +1332,17 @@ const AGENTS: [Agent; 13] = [
name: "Gemini CLI",
hint: "at its next step; trusted folders only",
installed: || gemini_home().exists() || agent::find_bin("gemini").is_some(),
- wired: |exe| has(gemini_home().join("settings.json"), &me(exe)),
+ wired: gemini::wired,
apply: gemini,
},
+ Agent {
+ id: "antigravity",
+ name: "Antigravity",
+ hint: "native conversation hooks; App sidecar wakes idle conversations",
+ installed: antigravity::installed,
+ wired: antigravity::wired,
+ apply: antigravity::apply,
+ },
Agent {
id: "copilot",
name: "Copilot CLI",
@@ -1572,6 +1582,7 @@ pub async fn doctor() -> Result<()> {
println!("- {}: installed, not on Reason Network (`{CLI} setup`)", f.name);
}
}
+ gemini::doctor(&exe, &link).await;
Ok(())
}
diff --git a/src/setup/antigravity.rs b/src/setup/antigravity.rs
new file mode 100644
index 0000000..a552e58
--- /dev/null
+++ b/src/setup/antigravity.rs
@@ -0,0 +1,67 @@
+//! Native contracts: antigravity.google/docs/{hooks,mcp,sidecars}. PostTool cannot inject messages.
+use super::*;
+
+fn config_dir() -> PathBuf {
+ home().join(".gemini/config")
+}
+pub(super) fn installed() -> bool {
+ config_dir().exists() || agent::find_bin("antigravity").is_some()
+}
+pub(super) fn wired(exe: &Path) -> bool {
+ ["mcp_config.json", "hooks.json"].iter().all(|p| has(config_dir().join(p), &me(exe)))
+}
+
+pub(super) fn apply(exe: &Path, remove: bool, dry: bool) -> Result<Option<Report>> {
+ if !installed() {
+ return Ok(None);
+ }
+ let dir = config_dir();
+ let mut report = Report { agent: "Antigravity", lines: Vec::new(), notes: Vec::new() };
+ let mcp = dir.join("mcp_config.json");
+ let mut value = read_json(&mcp)?;
+ let servers = obj(obj(&mut value)?.entry("mcpServers").or_insert_with(|| json!({})))?;
+ if remove {
+ servers.remove(AGENT_NAME);
+ } else {
+ servers.insert(AGENT_NAME.into(), json!({"command": exe.display().to_string(), "args": ["mcp"], "env": {"REASON_NETWORK_AGENT": "antigravity"}}));
+ }
+ report.lines.push(changed(&mcp, write_json(&mcp, &value, dry)?));
+ let hooks = dir.join("hooks.json");
+ let mut value = read_json(&hooks)?;
+ let definitions = obj(&mut value)?;
+ if remove {
+ definitions.remove(AGENT_NAME);
+ } else {
+ let enabled =
+ definitions.get(AGENT_NAME).and_then(|value| value.get("enabled")).cloned().unwrap_or(json!(true));
+ let handler = |event| json!({"type":"command","command":shell_cmd(exe,&format!("hook antigravity {event}")),"timeout":15});
+ definitions.insert(
+ AGENT_NAME.into(),
+ json!({
+ "enabled":enabled, "SessionStart":[handler("session-start")],
+ "PreInvocation":[handler("user-prompt-submit")],
+ "PostToolUse":[{"matcher":"*","hooks":[handler("post-tool-use")]}],
+ "Stop":[handler("stop")],
+ }),
+ );
+ }
+ report.lines.push(changed(&hooks, write_json(&hooks, &value, dry)?));
+ let sidecar = dir.join("sidecars/reason-network/sidecar.json");
+ let config = dir.join("config.json");
+ let mut value = read_json(&config)?;
+ let sidecars = obj(obj(&mut value)?.entry("sidecars").or_insert_with(|| json!({})))?;
+ if remove {
+ sidecars.remove(AGENT_NAME);
+ if !dry && sidecar.exists() {
+ std::fs::remove_file(&sidecar)?;
+ }
+ } else {
+ let data = json!({"command": exe.display().to_string(), "args": ["antigravity-sidecar"], "restart_policy": "on-failure", "display_name": "Reason Network", "description": "Deliver messages to your existing agent conversations"});
+ report.lines.push(changed(&sidecar, write_json(&sidecar, &data, dry)?));
+ // Preserve an explicit decision to disable this sidecar.
+ sidecars.entry(AGENT_NAME).or_insert_with(|| json!({"enabled": true}));
+ report.notes.push("Reload Antigravity's MCP configuration and start a new conversation. App idle delivery needs the Reason Network sidecar enabled; CLI conversations receive mail at their next invocation.".into());
+ }
+ report.lines.push(changed(&config, write_json(&config, &value, dry)?));
+ Ok(Some(report))
+}
diff --git a/src/setup/gemini.rs b/src/setup/gemini.rs
new file mode 100644
index 0000000..275642b
--- /dev/null
+++ b/src/setup/gemini.rs
@@ -0,0 +1,78 @@
+use super::*;
+
+fn gaps(exe: &Path, value: &Value) -> Vec<String> {
+ let mut gaps = Vec::new();
+ if value["mcpServers"][AGENT_NAME]["command"].as_str() != exe.to_str() {
+ gaps.push("MCP executable is missing or outdated".into());
+ }
+ if value["hooksConfig"]["enabled"] == false || value["hooks"]["enabled"] == false {
+ gaps.push("hooks are disabled".into());
+ }
+ for (event, call) in [
+ ("SessionStart", "session-start"),
+ ("BeforeAgent", "user-prompt-submit"),
+ ("AfterTool", "post-tool-use"),
+ ("AfterAgent", "stop"),
+ ("SessionEnd", "session-end"),
+ ] {
+ let command = shell_cmd(exe, &format!("hook gemini {call}"));
+ let name = format!("{AGENT_NAME}-{call}");
+ let present = value["hooks"][event]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .flat_map(|g| g["hooks"].as_array().into_iter().flatten())
+ .any(|h| h["command"] == command && h["type"] == "command");
+ if !present {
+ gaps.push(format!("{event} hook is missing or outdated"));
+ }
+ if ["hooksConfig", "hooks"].iter().any(|section| {
+ value[section]["disabled"].as_array().into_iter().flatten().any(|v| v == &name || v == &command)
+ }) {
+ gaps.push(format!("{event} hook is disabled"));
+ }
+ }
+ gaps
+}
+
+pub(super) fn wired(exe: &Path) -> bool {
+ read_json(&gemini_home().join("settings.json")).is_ok_and(|v| gaps(exe, &v).is_empty())
+}
+
+pub(super) async fn doctor(exe: &Path, link: &std::sync::Arc<Link>) {
+ if !gemini_home().exists() && agent::find_bin("gemini").is_none() {
+ return;
+ }
+ match read_json(&gemini_home().join("settings.json")) {
+ Ok(value) => {
+ for gap in gaps(exe, &value) {
+ println!("! Gemini CLI: {gap}");
+ }
+ }
+ Err(_) => println!("! Gemini CLI: settings could not be read"),
+ }
+ // Project/system settings and runtime folder trust can override user settings; never claim to have verified them.
+ println!(" Gemini CLI: confirm the project is trusted in /permissions and hooks are enabled in /hooks panel.");
+ println!(" Active sessions receive mail at a tool/turn boundary; idle sessions wait for the next prompt.");
+ if let Ok(health) = link.call::<Value>(Request::Diagnostics).await {
+ let sessions =
+ health["sessions"].as_array().into_iter().flatten().filter(|s| s["agent"] == "gemini").collect::<Vec<_>>();
+ if sessions.is_empty() {
+ println!(" Gemini CLI: no live session observed; hook execution is unverified.");
+ }
+ for session in sessions {
+ println!(
+ " Gemini CLI: {} / {}; session linked: {}; last hook: {}; unread: {}",
+ session["status"].as_str().unwrap_or("unknown"),
+ session["tier"].as_str().unwrap_or("unknown"),
+ session["sessionLinked"],
+ session["hookAgeMs"]
+ .as_i64()
+ .map_or_else(|| "never observed".into(), |age| format!("{}s ago", age / 1000)),
+ session["unread"]
+ );
+ }
+ } else {
+ println!(" Gemini CLI: this daemon cannot report hook health; update/restart Reason Network.");
+ }
+}
diff --git a/src/store.rs b/src/store.rs
index 6019deb..17242a1 100644
--- a/src/store.rs
+++ b/src/store.rs
@@ -43,6 +43,7 @@ const COUNTS_TO: &str = "+1 day";
/// Days of counts kept: the last ones started, in the order they started rather than by date, so a clock that jumps
/// doesn't push out the real ones.
const COUNTS_KEPT: i64 = 8;
+const RECEIPT_KEEP_MS: i64 = 7 * 86_400_000;
/// A held message that can't be approved now, and why (it stays held).
pub type Unsaved = (String, String);
@@ -101,6 +102,18 @@ CREATE TABLE IF NOT EXISTS kv (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
+CREATE TABLE IF NOT EXISTS send_keys (
+ key TEXT PRIMARY KEY,
+ fingerprint TEXT NOT NULL,
+ receipt TEXT,
+ created_at INTEGER NOT NULL
+);
+CREATE TABLE IF NOT EXISTS sent_receipts (
+ id TEXT PRIMARY KEY, sender_key TEXT NOT NULL, sender TEXT NOT NULL, recipient TEXT NOT NULL,
+ stage TEXT NOT NULL, sent_at INTEGER NOT NULL, updated_at INTEGER NOT NULL
+);
+CREATE INDEX IF NOT EXISTS send_keys_created_at ON send_keys(created_at);
+CREATE INDEX IF NOT EXISTS sent_receipts_sent_at ON sent_receipts(sent_at);
CREATE TABLE IF NOT EXISTS sessions (
name TEXT PRIMARY KEY,
key TEXT NOT NULL,
@@ -127,6 +140,101 @@ const MESSAGE_COLS: &str =
const SESSION_COLS: &str = "name, key, agent, cwd, repo, branch, doing, tier, last_seen, attached, mailbox";
impl Store {
+ pub fn record_sent(&self, key: &str, message: &Message, recipient: &str, state: &str) -> Result<()> {
+ let stage = match state {
+ "refused" => "rejected",
+ "held" => "held",
+ "queued" => "queued",
+ _ => "accepted",
+ };
+ self.prune_receipts(crate::util::now_ms())?;
+ self.db.execute(
+ "INSERT OR IGNORE INTO sent_receipts VALUES (?1,?2,?3,?4,?5,?6,?6)",
+ params![message.id, key, message.from, recipient, stage, message.sent_at],
+ )?;
+ Ok(())
+ }
+ pub fn handoff(&self, ids: &[String], now: i64) -> Result<()> {
+ for id in ids {
+ self.db.execute(
+ "UPDATE sent_receipts SET stage='handed_to_agent',updated_at=?2 WHERE id=?1 AND stage <> 'replied'",
+ params![id, now],
+ )?;
+ }
+ Ok(())
+ }
+
+ pub fn send_outcome(&self, id: &str, state: &str) -> Result<()> {
+ let stage = match state {
+ "refused" => "rejected",
+ "held" => "held",
+ "queued" => "queued",
+ _ => "accepted",
+ };
+ self.db.execute("UPDATE sent_receipts SET stage=?2,updated_at=?3 WHERE id=?1 AND stage NOT IN ('handed_to_agent','replied')", params![id,stage,crate::util::now_ms()])?;
+ Ok(())
+ }
+
+ pub fn queue_again(&self, ids: &[String]) -> Result<()> {
+ for id in ids {
+ self.db.execute("UPDATE sent_receipts SET stage='queued',updated_at=?2 WHERE id=?1 AND stage NOT IN ('handed_to_agent','replied')", params![id,crate::util::now_ms()])?;
+ }
+ Ok(())
+ }
+ pub fn delivery_status(&self, key: &str, ids: &[String]) -> Result<Vec<serde_json::Value>> {
+ anyhow::ensure!(ids.len() <= 100, "request at most 100 delivery receipts");
+ let mut out = Vec::new();
+ for id in ids {
+ let found = self.db.query_row("SELECT recipient,stage,sent_at,updated_at FROM sent_receipts WHERE id=?1 AND sender_key=?2 AND sent_at>=?3", params![id,key,crate::util::now_ms()-RECEIPT_KEEP_MS], |r| Ok(serde_json::json!({"id":id,"recipient":r.get::<_,String>(0)?,"stage":r.get::<_,String>(1)?,"sentAt":r.get::<_,i64>(2)?,"updatedAt":r.get::<_,i64>(3)?}))).optional()?;
+ out.push(found.unwrap_or_else(|| serde_json::json!({"id":id,"stage":"unknown"})));
+ }
+ Ok(out)
+ }
+ pub fn begin_send(
+ &self,
+ key: &str,
+ fingerprint: &str,
+ now: i64,
+ ) -> Result<(String, Option<crate::proto::SendResult>)> {
+ self.prune_receipts(now)?;
+ self.db.execute(
+ "INSERT OR IGNORE INTO send_keys(key,fingerprint,created_at,nonce) VALUES(?1,?2,?3,?4)",
+ params![key, fingerprint, now, ulid::Ulid::generate().to_string()],
+ )?;
+ let (old, receipt, nonce): (String, Option<String>, String) =
+ self.db.query_row("SELECT fingerprint,receipt,nonce FROM send_keys WHERE key=?1", [key], |r| {
+ Ok((r.get(0)?, r.get(1)?, r.get(2)?))
+ })?;
+ anyhow::ensure!(
+ old == fingerprint,
+ "idempotency key already used for a different message; use a new key for a corrected or different message"
+ );
+ Ok((nonce, receipt.map(|v| serde_json::from_str(&v)).transpose()?))
+ }
+
+ pub fn finish_send(&self, key: &str, receipt: &crate::proto::SendResult) -> Result<()> {
+ self.db
+ .execute("UPDATE send_keys SET receipt=?2 WHERE key=?1", params![key, serde_json::to_string(receipt)?])?;
+ Ok(())
+ }
+
+ fn prune_receipts(&self, now: i64) -> Result<()> {
+ self.db.execute("DELETE FROM sent_receipts WHERE sent_at < ?1", [now - RECEIPT_KEEP_MS])?;
+ self.db.execute("DELETE FROM send_keys WHERE created_at < ?1", [now - RECEIPT_KEEP_MS])?;
+ Ok(())
+ }
+
+ fn discard_receipt(&self, id: &str, stage: &str, now: i64) -> Result<()> {
+ self.db.execute("UPDATE sent_receipts SET stage=?2,updated_at=?3 WHERE id=?1 AND stage NOT IN ('handed_to_agent','replied')",params![id,stage,now])?;
+ Ok(())
+ }
+ pub fn queue_health(&self, address: &str) -> Result<(u32, Option<i64>)> {
+ Ok(self.db.query_row(
+ "SELECT count(*), min(sent_at) FROM messages WHERE recipient=?1 AND read_at IS NULL AND held=0",
+ [address],
+ |r| Ok((r.get(0)?, r.get(1)?)),
+ )?)
+ }
/// The database at `path`, and the folder `inbox` that messages' files are saved in.
pub fn open(path: &Path, inbox: PathBuf) -> Result<Self> {
let db = Connection::open(path)?;
@@ -171,6 +279,19 @@ impl Store {
)?;
tx.commit()?;
}
+ for (column, definition) in [
+ ("native_app", "INTEGER NOT NULL DEFAULT 0"),
+ ("native_hook_at", "INTEGER"),
+ ("native_dirs", "TEXT NOT NULL DEFAULT '[]'"),
+ ] {
+ if !db.prepare("SELECT 1 FROM pragma_table_info('sessions') WHERE name=?1")?.exists([column])? {
+ db.execute(&format!("ALTER TABLE sessions ADD COLUMN {column} {definition}"), [])?;
+ }
+ }
+ if !db.prepare("SELECT 1 FROM pragma_table_info('send_keys') WHERE name='nonce'")?.exists([])? {
+ // Empty preserves the identity derivation of an unfinished send from an earlier engine. New keys get a nonce.
+ db.execute("ALTER TABLE send_keys ADD COLUMN nonce TEXT NOT NULL DEFAULT ''", [])?;
+ }
Ok(Store { db, inbox })
}
@@ -225,6 +346,9 @@ impl Store {
held
],
);
+ if n.as_ref().is_ok_and(|n| *n == 1) && !held {
+ let _ = self.observe_reply(m);
+ }
match (n, saved, kept) {
(Ok(n), Some(dir), Some(k)) => {
m.files = files::located(&dir, &k.files);
@@ -245,6 +369,13 @@ impl Store {
Ok(self.db.query_row(&sql, [id], |r| self.row(r)).optional()?)
}
+ fn observe_reply(&self, message: &Message) -> Result<()> {
+ if let Some(reply) = &message.reply_to {
+ self.db.execute("UPDATE sent_receipts SET stage='replied',updated_at=?4 WHERE id=?1 AND recipient=?2 AND sender=?3 AND stage <> 'replied'", params![reply,message.from,message.to,crate::util::now_ms()])?;
+ }
+ Ok(())
+ }
+
pub fn has(&self, id: &str) -> Result<bool> {
Ok(self.db.query_row("SELECT 1 FROM messages WHERE id = ?1", [id], |_| Ok(())).optional()?.is_some())
}
@@ -301,6 +432,7 @@ impl Store {
/// without them), and a message held a week with files goes altogether. Then deletes every folder in the inbox
/// folder that no kept message names.
pub fn sweep_files(&self, now: i64) -> Result<()> {
+ self.prune_receipts(now)?;
let mut st = self.db.prepare("SELECT id, files, read_at, held FROM messages WHERE files IS NOT NULL")?;
let rows: Vec<(String, String, Option<i64>, bool)> =
st.query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)))?.collect::<rusqlite::Result<_>>()?;
@@ -312,6 +444,7 @@ impl Store {
let fresh = came.is_some_and(|t| t > now - files::KEEP_UNREAD_MS);
if held {
if !fresh {
+ self.discard_receipt(&id, "expired", now)?;
self.db.execute("DELETE FROM messages WHERE id = ?1", [&id])?;
}
} else if (read_at.is_none() && fresh) || read_at.is_some_and(|t| t > now - files::KEEP_MS) {
@@ -340,7 +473,10 @@ impl Store {
let (mut done, mut unsaved) = (Vec::new(), Vec::new());
for mut m in picked {
if !release {
+ let transaction = self.db.unchecked_transaction()?;
+ self.discard_receipt(&m.id, "rejected", crate::util::now_ms())?;
self.db.execute("DELETE FROM messages WHERE id = ?1", [&m.id])?;
+ transaction.commit()?;
done.push(m);
continue;
}
@@ -371,6 +507,7 @@ impl Store {
return Err(e.into());
}
let _ = self.count(crate::util::now_ms(), Counted::Received);
+ let _ = self.observe_reply(&m);
done.push(m);
}
Ok((done, unsaved))
@@ -395,10 +532,18 @@ impl Store {
/// The receiving machine answered for a message: it leaves the outbox, and counts as sent if that machine took it
/// (once, however many answers come).
pub fn outbox_done(&self, id: &str, taken: bool) -> Result<bool> {
+ let transaction = self.db.unchecked_transaction()?;
let removed = self.db.execute("DELETE FROM outbox WHERE id = ?1", [id])? == 1;
- if removed && taken {
- let _ = self.count(crate::util::now_ms(), Counted::Sent);
+ if removed {
+ self.db.execute(
+ "UPDATE sent_receipts SET stage=?3,updated_at=?2 WHERE id=?1 AND stage NOT IN ('handed_to_agent','replied')",
+ params![id, crate::util::now_ms(), if taken {"accepted"} else {"rejected"}],
+ )?;
+ if taken {
+ let _ = self.count(crate::util::now_ms(), Counted::Sent);
+ }
}
+ transaction.commit()?;
Ok(removed)
}
@@ -502,7 +647,10 @@ impl Store {
ON CONFLICT (name) DO UPDATE SET key = ?2, agent = ?3, cwd = ?4, repo = ?5, branch = ?6,
doing = ?7, tier = ?8, last_seen = ?9,
attached = CASE WHEN key = ?2 THEN max(attached, ?10) ELSE ?10 END,
- mailbox = CASE WHEN key = ?2 THEN max(mailbox, ?11) ELSE ?11 END"
+ mailbox = CASE WHEN key = ?2 THEN max(mailbox, ?11) ELSE ?11 END,
+ native_app = CASE WHEN key = ?2 THEN native_app ELSE 0 END,
+ native_hook_at = CASE WHEN key = ?2 THEN native_hook_at ELSE NULL END,
+ native_dirs = CASE WHEN key = ?2 THEN native_dirs ELSE '[]' END"
),
params![
s.name,
@@ -543,6 +691,7 @@ impl Store {
/// the name was kept for the session: it was that conversation's, never the next one's. Otherwise it stays the
/// person's to settle, for whoever has the name.
pub fn forget_session(&self, r: &Remembered, person: &str) -> Result<()> {
+ let transaction = self.db.unchecked_transaction()?;
let unread = if r.kept() {
"FROM messages WHERE recipient = ?1 AND read_at IS NULL"
} else {
@@ -552,13 +701,15 @@ impl Store {
let to = format!("{person}/{name}");
let mut cols = self.db.prepare_cached(&format!("SELECT files {unread} AND files IS NOT NULL"))?;
let cols: Vec<String> = cols.query_map([&to], |r| r.get(0))?.collect::<rusqlite::Result<_>>()?;
+ self.db.execute(&format!("UPDATE sent_receipts SET stage='expired',updated_at=?2 WHERE id IN (SELECT id {unread}) AND stage NOT IN ('handed_to_agent','replied')"),params![to,crate::util::now_ms()])?;
self.db.execute(&format!("DELETE {unread}"), [&to])?;
+ self.db.execute("DELETE FROM sessions WHERE name = ?1", [name])?;
+ transaction.commit()?;
for kept in cols.iter().filter_map(|c| serde_json::from_str::<Kept>(c).ok()) {
if let Some(dir) = self.dir(&kept) {
let _ = std::fs::remove_dir_all(dir);
}
}
- self.db.execute("DELETE FROM sessions WHERE name = ?1", [name])?;
Ok(())
}
@@ -577,6 +728,33 @@ impl Store {
let rows = st.query_map([], remembered)?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
+
+ pub fn remember_native_app(&self, key: &str, hook_at: Option<i64>, dirs: &[String]) -> Result<()> {
+ self.db.execute(
+ "UPDATE sessions SET native_app=?2,native_hook_at=?3,native_dirs=?4 WHERE key=?1 AND agent='antigravity'",
+ params![key, hook_at.is_some(), hook_at, serde_json::to_string(dirs)?],
+ )?;
+ Ok(())
+ }
+
+ pub fn native_app_roots(&self, key: &str) -> Result<Option<Vec<String>>> {
+ let roots: Option<String> = self
+ .db
+ .query_row(
+ "SELECT native_dirs FROM sessions WHERE key=?1 AND agent='antigravity' AND native_app=1",
+ [key],
+ |row| row.get(0),
+ )
+ .optional()?;
+ Ok(roots.map(|value| serde_json::from_str::<Vec<String>>(&value)).transpose()?.filter(|dirs| !dirs.is_empty()))
+ }
+
+ pub fn native_app_sessions(&self, since: i64) -> Result<Vec<(Remembered, i64)>> {
+ let mut statement=self.db.prepare(&format!("SELECT {SESSION_COLS},native_hook_at FROM sessions WHERE native_app=1 AND agent='antigravity' AND last_seen>=?1 AND native_hook_at IS NOT NULL"))?;
+ Ok(statement
+ .query_map([since], |row| Ok((remembered(row)?, row.get(11)?)))?
+ .collect::<rusqlite::Result<_>>()?)
+ }
}
impl Store {
@@ -870,6 +1048,83 @@ mod tests {
}
}
+ #[test]
+ fn receipts_track_remote_refusal_and_only_the_approved_matching_terminal_reply() {
+ let store = Store::open(Path::new(":memory:"), temp_inbox()).unwrap();
+ let mut outgoing = message("refused", "bob/terminal");
+ outgoing.sent_at = crate::util::now_ms();
+ store.record_sent("sender", &outgoing, "bob/terminal@laptop", "queued").unwrap();
+ store.outbox_add("peer", &outgoing).unwrap();
+ store.outbox_done("refused", false).unwrap();
+ assert_eq!(store.delivery_status("sender", &["refused".into()]).unwrap()[0]["stage"], "rejected");
+ outgoing.id = "accepted".into();
+ store.record_sent("sender", &outgoing, "bob/terminal@laptop", "queued").unwrap();
+ store.outbox_add("peer", &outgoing).unwrap();
+ store.outbox_done("accepted", true).unwrap();
+ let stage = || store.delivery_status("sender", &["accepted".into()]).unwrap()[0]["stage"].clone();
+ let mut reply = message("wrong-machine", &outgoing.from);
+ reply.from = "bob/terminal@desktop".into();
+ reply.reply_to = Some(outgoing.id.clone());
+ store.insert(&mut reply, false).unwrap();
+ assert_eq!(stage(), "accepted");
+ reply.id = "held-reply".into();
+ reply.from = "bob/terminal@laptop".into();
+ store.insert(&mut reply, true).unwrap();
+ assert_eq!(stage(), "accepted");
+ store.settle_held(&[reply.id], true).unwrap();
+ assert_eq!(stage(), "replied");
+ assert_eq!(store.delivery_status("other-session", &["accepted".into()]).unwrap()[0]["stage"], "unknown");
+ }
+
+ #[test]
+ fn an_expired_idempotency_key_gets_a_new_generation() {
+ let store = Store::open(Path::new(":memory:"), temp_inbox()).unwrap();
+ let now = crate::util::now_ms();
+ let (first, _) = store.begin_send("key", "original", now).unwrap();
+ assert!(!first.is_empty());
+ assert_eq!(store.begin_send("key", "original", now + 1000).unwrap().0, first);
+ assert!(store.begin_send("key", "different", now + 1000).is_err());
+ let (next, receipt) = store.begin_send("key", "different", now + 8 * 86_400_000).unwrap();
+ assert_ne!(next, first);
+ assert!(receipt.is_none());
+ }
+
+ #[test]
+ fn discarded_queues_and_retention_do_not_remain_pending() {
+ let store = Store::open(Path::new(":memory:"), temp_inbox()).unwrap();
+ let now = crate::util::now_ms();
+ let mut pending = message("pending", "sven/recipient");
+ pending.sent_at = now;
+ store.record_sent("sender", &pending, "sven/recipient", "queued").unwrap();
+ store.insert(&mut pending, false).unwrap();
+ let recipient = Remembered {
+ name: "recipient".into(),
+ key: "agent:recipient".into(),
+ agent: "agent".into(),
+ cwd: "/work".into(),
+ repo: None,
+ branch: None,
+ doing: None,
+ tier: Tier::Pull,
+ last_seen: now - 2 * 86_400_000,
+ attached: true,
+ mailbox: false,
+ };
+ store.upsert_session(&recipient, "sven").unwrap();
+ store.forget_session(&recipient, "sven").unwrap();
+ assert!(store.message("pending").unwrap().is_none());
+ assert_eq!(store.delivery_status("sender", &["pending".into()]).unwrap()[0]["stage"], "expired");
+ pending.id = "old".into();
+ pending.sent_at = now - 8 * 86_400_000;
+ store.record_sent("sender", &pending, "sven/recipient", "queued").unwrap();
+ assert_eq!(store.delivery_status("sender", &["old".into()]).unwrap()[0]["stage"], "unknown");
+ assert!(store.db.prepare("SELECT 1 FROM sent_receipts WHERE id='old'").unwrap().exists([]).unwrap());
+ store.begin_send("old-key", "body", now - 8 * 86_400_000).unwrap();
+ store.sweep_files(now).unwrap();
+ assert!(!store.db.prepare("SELECT 1 FROM sent_receipts WHERE id='old'").unwrap().exists([]).unwrap());
+ assert!(!store.db.prepare("SELECT 1 FROM send_keys WHERE key='old-key'").unwrap().exists([]).unwrap());
+ }
+
#[test]
fn a_store_from_before_keeps_the_persons_mailboxes_but_not_the_clis_ask_sessions() {
let dir = std::env::temp_dir().join(format!("reason-network-mailbox-{}", ulid::Ulid::generate()));
diff --git a/tests/e2e/antigravity.py b/tests/e2e/antigravity.py
new file mode 100644
index 0000000..85e3c09
--- /dev/null
+++ b/tests/e2e/antigravity.py
@@ -0,0 +1,143 @@
+"""Native hook and sidecar contracts against an isolated real daemon, with an agentapi fixture.
+Run: cargo build && python3 tests/e2e/antigravity.py
+This verifies the documented adapter interface; it does not launch Google's App or a model.
+"""
+import json, os, pathlib, select, socket, subprocess, tempfile, time
+
+ROOT = pathlib.Path(__file__).resolve().parents[2]
+BIN = ROOT / 'target/debug/reason-network'
+
+def main():
+ with tempfile.TemporaryDirectory(prefix='rn-antigravity-', dir='/tmp') as directory:
+ root = pathlib.Path(directory)
+ project = root / 'project'; project.mkdir()
+ state = root / 'network'; executables = root / 'bin'; executables.mkdir()
+ log = root / 'calls.jsonl'; fail = root / 'refuse'
+ env = {k:v for k,v in os.environ.items() if not k.startswith(('CLAUDE','CODEX','GEMINI','REASON_NETWORK','TINCAN'))}
+ env.update(REASON_NETWORK_HOME=str(state),REASON_NETWORK_NO_SERVICE='1',REASON_NETWORK_NO_UPDATE='1',REASON_NETWORK_NO_TRAY='1',REASON_NETWORK_NO_MDNS='1',REASON_NETWORK_MACHINE='fixture',PATH=str(executables)+os.pathsep+env.get('PATH',''),ANTIGRAVITY_PROBE_LOG=str(log),ANTIGRAVITY_PROBE_FAIL=str(fail))
+ api = executables / 'agentapi'
+ api.write_text('#!/usr/bin/env python3\nimport os,sys,json\nif os.path.exists(os.environ["ANTIGRAVITY_PROBE_FAIL"]): sys.exit(1)\nwith open(os.environ["ANTIGRAVITY_PROBE_LOG"],"a") as f: print(json.dumps(sys.argv[1:]),file=f)\n')
+ api.chmod(0o700)
+ def cli(*args,payload=None):
+ result=subprocess.run([str(BIN),*args],input=json.dumps(payload) if payload is not None else None,capture_output=True,text=True,env=env,cwd=project,timeout=30)
+ assert result.returncode == 0, result.stderr
+ return result.stdout
+ def call(op,**fields):
+ with socket.socket(socket.AF_UNIX) as connection:
+ connection.settimeout(10);connection.connect(str(state/'network.sock'))
+ connection.sendall((json.dumps(dict(id=1,op=op,**fields))+'\n').encode())
+ response=json.loads(connection.makefile().readline())
+ return response
+ def wait(predicate,timeout=20):
+ end=time.monotonic()+timeout
+ while time.monotonic()<end:
+ try: result=predicate()
+ except (OSError,ValueError,KeyError): result=False
+ if result:return result
+ time.sleep(.1)
+ raise AssertionError('condition did not become true')
+ def hooks(sid,event,workspaces=None):
+ return cli('hook','antigravity',event,payload=dict(conversationId=sid,workspacePaths=workspaces or [str(project)],transcriptPath=str(root/'.gemini/antigravity/brain'/sid/'transcript.jsonl'),invocationNum=0,initialNumSteps=0))
+ def sessions():return call('who')['result']['sessions']
+ def receipt(ids):return call('delivery_status',**{'from':'cli:sender','ids':ids})['result']
+ def sent(to,body,key):
+ response=call('send',**{'from':'cli:sender','to':to,'body':body,'idempotency_key':key})
+ assert response['ok'],response
+ return response['result']['ids']
+ sidecar=mcp=None
+ try:
+ cli('init','fixture','--as','alice','--no-setup')
+ call('hook',agent='cli',event='stop',session_id='sender',name='sender',cwd=str(project),pid=os.getpid(),mail=False,through_reason=False)
+ first='b984f9b8-e5c6-44f0-85e6-9529cf7d4f77';second='3c4edbfc-5442-486d-a53e-faeecb3f892f'
+ intro=json.loads(hooks(first,'user-prompt-submit'))
+ assert first in intro['injectSteps'][0]['userMessage']
+ recipient=next(s['address'] for s in sessions() if s['agent']=='antigravity')
+ ids=sent(recipient,'Receive at the next invocation','hook-message')
+ assert hooks(first,'post-tool-use') == ''
+ assert receipt(ids)[0]['stage']=='queued'
+ injected=json.loads(hooks(first,'user-prompt-submit'))
+ assert 'Receive at the next invocation' in injected['injectSteps'][0]['userMessage']
+ assert receipt(ids)[0]['stage']=='handed_to_agent'
+ print('PASS native PreInvocation injects; PostTool leaves mail unread')
+ hooks(second,'user-prompt-submit')
+ mcp=subprocess.Popen([str(BIN),'mcp'],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True,env=dict(env,REASON_NETWORK_AGENT='antigravity'),cwd=project)
+ def rpc(i,method,params):
+ mcp.stdin.write(json.dumps(dict(jsonrpc='2.0',id=i,method=method,params=params))+'\n');mcp.stdin.flush()
+ if not select.select([mcp.stdout],[],[],10)[0]:
+ mcp.terminate(); _,error=mcp.communicate(timeout=5)
+ raise AssertionError('MCP timeout: '+error)
+ return json.loads(mcp.stdout.readline())
+ rpc(1,'initialize',dict(protocolVersion='2025-06-18',capabilities={},clientInfo=dict(name='gemini-cli-mcp-client',version='fixture')))
+ mcp.stdin.write(json.dumps(dict(jsonrpc='2.0',method='notifications/initialized'))+'\n');mcp.stdin.flush()
+ for i,sid in enumerate([first,second],2):
+ response=rpc(i,'tools/call',dict(name='list_team',arguments=dict(session_id=sid)))
+ assert not response['result'].get('isError'),response
+ rejected=rpc(4,'tools/call',dict(name='list_team',arguments=dict(session_id='unknown')))
+ assert rejected['result']['isError']
+ assert len([s for s in sessions() if s['agent']=='antigravity'])==2
+ print('PASS concurrent chats bind to known native conversations; unknown identity is refused')
+ sidecar=subprocess.Popen([str(BIN),'antigravity-sidecar'],env=env,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
+ wait(lambda:all(s['tier']=='push' for s in sessions() if s['agent']=='antigravity'))
+ ids=sent(recipient,'Wake this idle conversation','idle-message')
+ wait(lambda:receipt(ids)[0]['stage']=='handed_to_agent')
+ assert sent(recipient,'Wake this idle conversation','idle-message')==ids
+ assert not call('send',**{'from':'cli:sender','to':recipient,'body':'Different content','idempotency_key':'idle-message'})['ok']
+ lines=[json.loads(line) for line in log.read_text().splitlines()]
+ assert len(lines)==1 and lines[0][0:2]==['send-message',first] and ids[0] in lines[0][2],lines
+ print('PASS idle sidecar hands off once; retry preserves id and different-content reuse is refused')
+ fail.touch();ids=sent(recipient,'Retry the failed handoff','failure-message')
+ wait(lambda:any(s['address']==recipient and s['tier']=='turn' for s in sessions()))
+ assert next(s['unread'] for s in sessions() if s['address']==recipient)==1
+ fail.unlink()
+ wait(lambda:receipt(ids)[0]['stage']=='handed_to_agent',30)
+ lines=[json.loads(line) for line in log.read_text().splitlines()]
+ assert len(lines)==2 and ids[0] in lines[-1][2]
+ print('PASS refused handoff remains unread and retries with the original message id')
+ cli('stop')
+ wait(lambda:len([s for s in sessions() if s['agent']=='antigravity' and s['tier']=='push'])==2)
+ call('hook',agent='cli',event='stop',session_id='sender',name='sender',cwd=str(project),pid=os.getpid(),mail=False,through_reason=False)
+ ids=sent(recipient,'Still reachable after a daemon restart','restart-message')
+ wait(lambda:receipt(ids)[0]['stage']=='handed_to_agent')
+ assert not rpc(5,'tools/call',dict(name='list_team',arguments=dict(session_id=first)))['result'].get('isError')
+ print('PASS idle App bindings and MCP identity recover after a daemon restart without another hook')
+ sidecar.terminate();sidecar.wait(timeout=5)
+ sidecar=subprocess.Popen([str(BIN),'antigravity-sidecar'],env=env,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
+ wait(lambda:len([s for s in sessions() if s['agent']=='antigravity' and s['tier']=='push'])==2)
+ ids=sent(recipient,'Still reachable after a sidecar restart','sidecar-restart-message')
+ wait(lambda:receipt(ids)[0]['stage']=='handed_to_agent')
+ print('PASS sidecar restart preserves native conversation identity')
+ cloud_command=executables/'reason'
+ cloud_command.write_text('#!/bin/sh\nexit 0\n');cloud_command.chmod(0o700)
+ registered=call('hook',agent='reason',event='stop',session_id='cloud-check',name='cloud-check',cwd=str(project),mail=False,through_reason=True)
+ cloud=registered['result']['address']
+ ids=sent(cloud,'Only a cloud server acknowledgment','cloud-acceptance')
+ wait(lambda:next(s['unread'] for s in sessions() if s['address']==cloud)==0)
+ assert receipt(ids)[0]['stage']=='accepted',receipt(ids)
+ print('PASS Reason cloud server acceptance is not claimed as agent handoff')
+ health=call('diagnostics')['result'];serialized=json.dumps(health)
+ assert first not in serialized and str(project) not in serialized and 'Retry the failed handoff' not in serialized
+ assert any(s['agent']=='antigravity' and s['adapterConnected'] for s in health['sessions'])
+ print('PASS health reports capabilities without content, conversation ids or project paths')
+ blocked=root/'disabled-project';blocked.mkdir()
+ cli('folder',str(blocked),'off')
+ assert hooks(first,'user-prompt-submit',[str(project),str(blocked)])==''
+ cli('stop')
+ wait(lambda:len([s for s in sessions() if s['agent']=='antigravity' and s['tier']=='push'])==1)
+ assert not any(s['address']==recipient for s in sessions())
+ print('PASS a hook with a disabled secondary workspace revokes its persistent App binding')
+ cli('folder',str(blocked),'on')
+ hooks(first,'user-prompt-submit',[str(project),str(blocked)])
+ wait(lambda:len([s for s in sessions() if s['agent']=='antigravity' and s['tier']=='push'])==2)
+ cli('folder',str(blocked),'off')
+ wait(lambda:len([s for s in sessions() if s['agent']=='antigravity' and s['tier']=='push'])==1)
+ assert not any(s['address']==recipient for s in sessions())
+ print('PASS restoration revalidates all saved workspaces even without a new hook')
+ finally:
+ for process in [mcp,sidecar]:
+ if process is not None:
+ process.terminate()
+ try:process.wait(timeout=5)
+ except subprocess.TimeoutExpired:process.kill();process.wait()
+ cli('stop')
+
+if __name__=='__main__': main()