Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
326 changes: 326 additions & 0 deletions crates/agentkeys-cli/src/hook.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,326 @@
//! `agentkeys hook ...` — runtime lifecycle hook helpers.
//!
//! Invoked BY the hook scripts that `agentkeys wire` drops into a Task
//! Host's config (Hermes `~/.hermes/config.yaml`, Claude Code
//! `~/.claude/settings.json`, Codex `~/.codex/hooks.json`, …). Each
//! subcommand:
//! 1. reads the host's JSON hook payload from stdin,
//! 2. calls an AgentKeys MCP tool over HTTP (`tools/call`),
//! 3. writes the host's expected JSON decision to stdout.
//!
//! Wire protocol (Hermes / Claude-Code compatible — see
//! `docs/wiki/agent-iam-guarantee-glossary.md` §3 + the plan
//! `docs/spec/plans/phase-1-fresh-user-wire-onboarding.md` §5.2):
//!
//! ```text
//! stdin: {hook_event_name, tool_name, tool_input, session_id, cwd, extra}
//! stdout block: {"decision":"block","reason":"..."}
//! stdout context: {"context":"..."}
//! stdout no-op: {}
//! ```
//!
//! The three guarantees these deliver (issue #133):
//! - `check` → PreToolUse permission gate (fails CLOSED)
//! - `audit` → PostToolUse audit append (never blocks)
//! - `memory-inject` → pre_llm_call context injection (never blocks)

use std::io::Read;

use anyhow::{Context, Result};
use serde_json::{json, Value};

/// Connection + identity config for talking to the AgentKeys MCP server.
///
/// All four fields are baked into the wire-generated hook scripts at
/// `agentkeys wire` time, so the hook invocation stays a single `exec`
/// line. Flags override env; env overrides built-in demo defaults.
pub struct HookClient {
mcp_url: String,
vendor_token: String,
actor: String,
operator: String,
http: reqwest::Client,
}

impl HookClient {
pub fn resolve(
mcp_url: Option<String>,
vendor_token: Option<String>,
actor: Option<String>,
operator: Option<String>,
) -> Self {
let mcp_url = mcp_url
.or_else(|| std::env::var("AGENTKEYS_MCP_URL").ok())
.unwrap_or_else(|| "http://localhost:8088/mcp".to_string());
let vendor_token = vendor_token
.or_else(|| std::env::var("AGENTKEYS_MCP_VENDOR_TOKEN").ok())
.unwrap_or_else(|| "demo-tok".to_string());
let actor = actor
.or_else(|| std::env::var("AGENTKEYS_ACTOR_OMNI").ok())
.unwrap_or_default();
let operator = operator
.or_else(|| std::env::var("AGENTKEYS_OPERATOR_OMNI").ok())
.unwrap_or_default();
Self {
mcp_url,
vendor_token,
actor,
operator,
http: reqwest::Client::new(),
}
}

/// Call an MCP tool over HTTP, return the tool's `structuredContent`.
async fn call_tool(&self, tool: &str, arguments: Value) -> Result<Value> {
let body = json!({
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {"name": tool, "arguments": arguments}
});
let mut req = self
.http
.post(&self.mcp_url)
.header("authorization", format!("Bearer {}", self.vendor_token))
.json(&body);
if !self.actor.is_empty() {
req = req.header("x-agentkeys-actor", &self.actor);
}
let resp = req.send().await.context("POST /mcp")?;
let status = resp.status();
let parsed: Value = resp.json().await.context("parse MCP JSON-RPC response")?;
if let Some(err) = parsed.get("error") {
anyhow::bail!("MCP error (http {status}): {err}");
}
parsed
.get("result")
.and_then(|r| r.get("structuredContent"))
.cloned()
.ok_or_else(|| anyhow::anyhow!("MCP response missing result.structuredContent"))
}
}

fn read_stdin_payload() -> Value {
let mut buf = String::new();
let _ = std::io::stdin().read_to_string(&mut buf);
serde_json::from_str(&buf).unwrap_or_else(|_| json!({}))
}

fn emit(value: Value) {
println!("{value}");
}

/// Map a `permission.check` Decision to the host's hook-output JSON.
/// Pure function — unit-tested without a server.
pub fn decision_to_hook_output(decision: &Value) -> Value {
let verdict = decision
.get("verdict")
.and_then(|v| v.as_str())
.unwrap_or("deny");
if verdict == "accept" {
json!({})
} else {
let reason = decision
.get("reason")
.and_then(|v| v.as_str())
.unwrap_or("denied");
let explanation = decision
.get("explanation")
.and_then(|v| v.as_str())
.unwrap_or("");
let msg = if explanation.is_empty() {
reason.to_string()
} else {
format!("{reason}: {explanation}")
};
json!({"decision": "block", "reason": msg})
}
}

/// `agentkeys hook check --scope <scope>` — PreToolUse permission gate.
///
/// Reads the host payload, extracts the tool_input as the policy params,
/// calls `agentkeys.permission.check(scope, params)`, and blocks the
/// tool call when the verdict is not `accept`. **Fails CLOSED**: if the
/// MCP server is unreachable, the tool call is blocked (this matcher is
/// only wired to high-risk tools, so failing closed is correct).
pub async fn check(
scope: &str,
mcp_url: Option<String>,
vendor_token: Option<String>,
actor: Option<String>,
operator: Option<String>,
) -> Result<String> {
let payload = read_stdin_payload();
let params = payload
.get("tool_input")
.cloned()
.unwrap_or_else(|| json!({}));
let client = HookClient::resolve(mcp_url, vendor_token, actor, operator);

let mut args = json!({"scope": scope, "params": params});
if !client.actor.is_empty() {
args["actor"] = json!(client.actor);
}

match client.call_tool("agentkeys.permission.check", args).await {
Ok(decision) => emit(decision_to_hook_output(&decision)),
Err(e) => {
eprintln!("[agentkeys hook check] MCP unreachable — failing CLOSED: {e}");
emit(json!({
"decision": "block",
"reason": format!("agentkeys_unreachable: {e}")
}));
}
}
Ok(String::new())
}

/// `agentkeys hook audit` — PostToolUse audit append. Never blocks; on
/// error it logs to stderr and emits `{}` so the agent loop continues.
pub async fn audit(
mcp_url: Option<String>,
vendor_token: Option<String>,
actor: Option<String>,
operator: Option<String>,
) -> Result<String> {
let payload = read_stdin_payload();
let tool_name = payload
.get("tool_name")
.and_then(|v| v.as_str())
.unwrap_or("unknown");
let tool_input = payload
.get("tool_input")
.cloned()
.unwrap_or_else(|| json!({}));
let client = HookClient::resolve(mcp_url, vendor_token, actor, operator);

// op_kind 1 = generic tool-use (placeholder; the audit envelope's
// op_kind taxonomy is owned by arch.md §15.3a). op_body carries the
// tool name + input so the off-chain feed shows what ran.
let event = json!({
"operator_omni": client.operator,
"op_kind": 1,
"result": 0,
"op_body": {"tool_name": tool_name, "tool_input": tool_input},
});
let args = json!({"actor": client.actor, "event": event});

if let Err(e) = client.call_tool("agentkeys.audit.append", args).await {
eprintln!("[agentkeys hook audit] audit append failed (non-fatal): {e}");
}
emit(json!({}));
Ok(String::new())
}

/// `agentkeys hook memory-inject --namespaces <ns,ns>` — pre_llm_call
/// context injection. Pulls the named memory namespaces via
/// `agentkeys.memory.get`, base64-decodes them, and returns a `{context}`
/// blob the host prepends to the next LLM turn. Never blocks; a namespace
/// that errors is skipped.
pub async fn memory_inject(
namespaces: &str,
mcp_url: Option<String>,
vendor_token: Option<String>,
actor: Option<String>,
operator: Option<String>,
) -> Result<String> {
let _payload = read_stdin_payload(); // discarded — we inject regardless
let client = HookClient::resolve(mcp_url, vendor_token, actor, operator);

let mut chunks = Vec::new();
for ns in namespaces
.split(',')
.map(|s| s.trim())
.filter(|s| !s.is_empty())
{
match client
.call_tool("agentkeys.memory.get", json!({"namespace": ns}))
.await
{
Ok(result) => {
if let Some(text) = extract_memory_content(&result) {
chunks.push(format!("## Memory: {ns}\n{text}"));
}
}
Err(e) => {
eprintln!("[agentkeys hook memory-inject] memory.get({ns}) failed (skipping): {e}");
}
}
}

if chunks.is_empty() {
emit(json!({}));
} else {
emit(json!({"context": chunks.join("\n\n")}));
}
Ok(String::new())
}

/// Extract the `content` field of an `agentkeys.memory.get` result. The
/// MCP tool layer already base64-decodes the worker's `plaintext_b64`
/// into a UTF-8 `content` string (see
/// `agentkeys-mcp-server/src/tools/memory.rs::get`), so the hook reads it
/// directly. Pure helper, unit-tested.
pub fn extract_memory_content(result: &Value) -> Option<String> {
result
.get("content")
.and_then(|v| v.as_str())
.map(|s| s.to_string())
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn accept_verdict_emits_empty_object() {
let decision = json!({"verdict": "accept", "scope": "memory.read", "reason": "ok"});
assert_eq!(decision_to_hook_output(&decision), json!({}));
}

#[test]
fn deny_verdict_emits_block_with_reason_and_explanation() {
let decision = json!({
"verdict": "deny",
"scope": "payment.spend",
"reason": "daily_spend_cap_exceeded",
"explanation": "cap=500, requested=600, period=daily"
});
let out = decision_to_hook_output(&decision);
assert_eq!(out["decision"], "block");
assert_eq!(
out["reason"],
"daily_spend_cap_exceeded: cap=500, requested=600, period=daily"
);
}

#[test]
fn ask_parent_verdict_blocks() {
let decision = json!({"verdict": "ask_parent", "reason": "needs_approval"});
let out = decision_to_hook_output(&decision);
assert_eq!(out["decision"], "block");
assert_eq!(out["reason"], "needs_approval");
}

#[test]
fn missing_verdict_defaults_to_block() {
let out = decision_to_hook_output(&json!({}));
assert_eq!(out["decision"], "block");
}

#[test]
fn extract_memory_content_reads_content_field() {
let result =
json!({"ok": true, "content": "Chengdu trip — Apr 12 to 16", "namespace": "travel"});
assert_eq!(
extract_memory_content(&result).as_deref(),
Some("Chengdu trip — Apr 12 to 16")
);
}

#[test]
fn extract_memory_content_missing_field_is_none() {
assert_eq!(extract_memory_content(&json!({"ok": true})), None);
}
}
2 changes: 2 additions & 0 deletions crates/agentkeys-cli/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
use std::collections::HashMap;
use std::sync::Arc;

pub mod hook;
pub mod k11;
pub mod k11_intent;
pub mod k11_webauthn;
pub mod wire;

use agentkeys_core::actor_omni::actor_omni_hex;
use agentkeys_core::backend::{BackendError, CredentialBackend};
Expand Down
Loading
Loading