Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

feat(hooks): give Grok the handoff after the first tool

Giovanni Coutinho25955c1c2e3e
diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rs
index b6f09e0b..c0f07359 100644
--- a/crates/ai-memory-cli/src/commands/hook.rs
+++ b/crates/ai-memory-cli/src/commands/hook.rs
@@ -459,6 +459,39 @@ fn write_success_response<W: std::io::Write>(
}
}
+const GROK_ADDITIONAL_CONTEXT_CHARS: usize = 10_000;
+
+fn grok_post_tool_handoff_envelope(handoff: &str) -> serde_json::Value {
+ serde_json::json!({
+ "hookSpecificOutput": {
+ "hookEventName": "PostToolUse",
+ "additionalContext": clip_chars(handoff, GROK_ADDITIONAL_CONTEXT_CHARS),
+ }
+ })
+}
+
+fn clip_chars(text: &str, max_chars: usize) -> String {
+ if text.chars().count() <= max_chars {
+ return text.to_string();
+ }
+ let keep = max_chars.saturating_sub(12);
+ let mut out: String = text.chars().take(keep).collect();
+ out.push_str("\n[truncated]");
+ out
+}
+
+fn handoff_shown_path(
+ data_dir: &Path,
+ agent: &str,
+ session_id: Option<&str>,
+ cwd: Option<&str>,
+) -> PathBuf {
+ let key = briefed_marker_path(data_dir, agent, session_id, cwd);
+ data_dir
+ .join("handoff-shown")
+ .join(key.file_name().unwrap_or_default())
+}
+
fn session_start_handoff_envelope(agent: AgentKind, handoff: String) -> serde_json::Value {
if agent == AgentKind::AntigravityCli {
serde_json::json!({
@@ -840,6 +873,43 @@ where
return Ok(());
}
+ // post-tool-use: Grok shows hookSpecificOutput.additionalContext to the
+ // model after the tool result. SessionStart and UserPromptSubmit stdout
+ // are discarded, so this is the event that can carry a handoff without
+ // burning it. One fetch per session. A session that never calls a tool
+ // leaves the handoff open for memory_handoff_accept.
+ if HookEvent::parse(&args.event) == HookEvent::PostToolUse
+ && AgentKind::from_wire(&args.agent).post_tool_injects_handoff()
+ {
+ let shown = handoff_shown_path(
+ &dd,
+ &args.agent,
+ canonical_session_id.as_deref(),
+ policy_cwd.as_deref(),
+ );
+ if !shown.is_file() {
+ let client = build_client();
+ let bearer = hook_spool::resolve_bearer(&client, &dd, effective_token).await;
+ let native_session_qs = canonical_session_id
+ .as_deref()
+ .map_or_else(String::new, |session_id| {
+ format!("&session_id={}", url_encode(session_id))
+ });
+ let handoff_url = format!(
+ "{base}/handoff?agent={}{qs}{managed_qs}{native_session_qs}",
+ args.agent
+ );
+ let handoff =
+ get_handoff(&client, &handoff_url, bearer.as_deref(), handoff_timeout()).await;
+ mark_briefed(&shown);
+ if let Some(handoff) = handoff {
+ let envelope = grok_post_tool_handoff_envelope(&handoff);
+ writeln!(stdout, "{envelope}")?;
+ return Ok(());
+ }
+ }
+ }
+
// Boundary drain trigger: enqueue first, then ask a detached native drainer
// to flush the shared spool. `session-end` remains the primary close path,
// but `stop` and `pre-compact` also trigger the helper so delivery does not
@@ -3003,6 +3073,129 @@ mod tests {
}
}
+ #[tokio::test]
+ async fn grok_post_tool_prints_additional_context_once() {
+ let tmp = tempfile::tempdir().unwrap();
+ let data_dir = tmp.path().join("data");
+ let (base, mut requests) = serve_requests("200 OK", "AMWS-HANDOFF-DELTA").await;
+ let payload = serde_json::json!({
+ "session_id": "grok-session",
+ "cwd": tmp.path(),
+ "tool_name": "read_file"
+ })
+ .to_string();
+
+ let mut stdout = Vec::new();
+ run_with_payload(
+ Some(data_dir.clone()),
+ grok_hook_args("post-tool-use", &base),
+ payload.clone(),
+ &mut stdout,
+ |_, _| Ok(()),
+ )
+ .await
+ .unwrap();
+ let envelope: serde_json::Value = serde_json::from_slice(stdout.trim_ascii()).unwrap();
+ assert_eq!(
+ envelope["hookSpecificOutput"]["hookEventName"],
+ "PostToolUse"
+ );
+ assert_eq!(
+ envelope["hookSpecificOutput"]["additionalContext"],
+ "AMWS-HANDOFF-DELTA"
+ );
+ let first = first_request(&mut requests).await.unwrap();
+ assert!(first.starts_with("GET /handoff?"), "{first}");
+ assert!(first.contains("agent=grok"), "{first}");
+ assert!(first.contains("session_id=grok-session"), "{first}");
+ assert!(
+ data_dir
+ .join("handoff-shown")
+ .join("grok-session")
+ .is_file(),
+ "shown marker missing"
+ );
+
+ let mut stdout = Vec::new();
+ run_with_payload(
+ Some(data_dir),
+ grok_hook_args("post-tool-use", &base),
+ payload,
+ &mut stdout,
+ |_, _| Ok(()),
+ )
+ .await
+ .unwrap();
+ assert_eq!(stdout, b"{}\n");
+ assert!(
+ first_request(&mut requests).await.is_none(),
+ "second post-tool must not fetch again"
+ );
+ }
+
+ #[tokio::test]
+ async fn grok_post_tool_includes_briefing_when_the_marker_opts_in() {
+ let tmp = tempfile::tempdir().unwrap();
+ let data_dir = tmp.path().join("data");
+ let cwd = tmp.path().join("repo");
+ std::fs::create_dir(&cwd).unwrap();
+ write_briefing_marker(&cwd);
+ let (base, mut requests) = serve_requests("200 OK", "AMWS-HANDOFF-DELTA").await;
+ let mut stdout = Vec::new();
+ run_with_payload(
+ Some(data_dir),
+ grok_hook_args("post-tool-use", &base),
+ serde_json::json!({
+ "session_id": "grok-session",
+ "cwd": cwd,
+ "tool_name": "read_file"
+ })
+ .to_string(),
+ &mut stdout,
+ |_, _| Ok(()),
+ )
+ .await
+ .unwrap();
+ let request = first_request(&mut requests).await.unwrap();
+ assert!(request.contains("&briefing=true"), "{request}");
+ assert!(request.contains("&briefing_budget=6000"), "{request}");
+ let envelope: serde_json::Value = serde_json::from_slice(stdout.trim_ascii()).unwrap();
+ assert_eq!(
+ envelope["hookSpecificOutput"]["additionalContext"],
+ "AMWS-HANDOFF-DELTA"
+ );
+ }
+
+ #[tokio::test]
+ async fn grok_post_tool_without_handoff_prints_empty_object() {
+ let tmp = tempfile::tempdir().unwrap();
+ let (base, mut requests) = serve_requests("404 Not Found", "").await;
+ let mut stdout = Vec::new();
+ run_with_payload(
+ Some(tmp.path().join("data")),
+ grok_hook_args("post-tool-use", &base),
+ serde_json::json!({"session_id": "grok-session", "cwd": tmp.path()}).to_string(),
+ &mut stdout,
+ |_, _| Ok(()),
+ )
+ .await
+ .unwrap();
+ assert_eq!(stdout, b"{}\n");
+ let request = first_request(&mut requests).await.unwrap();
+ assert!(request.starts_with("GET /handoff?"), "{request}");
+ }
+
+ #[test]
+ fn grok_additional_context_is_clipped_to_the_model_cap() {
+ let long = "x".repeat(GROK_ADDITIONAL_CONTEXT_CHARS + 50);
+ let envelope = grok_post_tool_handoff_envelope(&long);
+ let note = envelope["hookSpecificOutput"]["additionalContext"]
+ .as_str()
+ .unwrap();
+ assert!(note.ends_with("\n[truncated]"));
+ assert!(note.chars().count() <= GROK_ADDITIONAL_CONTEXT_CHARS);
+ }
+
#[test]
fn briefed_markers_are_bounded_and_keep_current() {
let tmp = tempfile::tempdir().unwrap();