use crate::streaming::stringify_ndjson_line;
use serde_json::{json, Value};
pub const ASK_SUPPORTED_TOOLS: &[&str] = &["agent", "claude"];
pub const ASK_DECISIONS: &[&str] = &["once", "always", "reject"];
pub fn ask_scope(tool: &str) -> Option<&'static str> {
match tool {
"agent" => Some("session"),
"claude" => Some("tool-input"),
_ => None,
}
}
pub fn supports_ask(tool: &str) -> bool {
ASK_SUPPORTED_TOOLS.contains(&tool)
}
pub fn ask_unsupported_error(tool: &str) -> String {
format!(
"Tool \"{}\" does not support enforceable per-command approval (ask mode). Choose one of: {}; or run without --approve-each.",
tool,
ASK_SUPPORTED_TOOLS.join(", ")
)
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Debug, Clone, PartialEq)]
pub struct NormalizedPermissionRequest {
pub r#type: String,
pub tool: String,
pub id: Option<String>,
pub session_id: Option<String>,
pub call_id: Option<String>,
pub tool_name: Option<String>,
pub title: Option<String>,
pub command: Option<String>,
pub pattern: Option<String>,
pub scope: String,
pub input: Option<Value>,
pub raw: Value,
}
fn value_str(message: &Value, key: &str) -> Option<String> {
message
.get(key)
.and_then(|v| v.as_str())
.map(|s| s.to_string())
}
fn derive_claude_command(tool_name: Option<&str>, input: Option<&Value>) -> Option<String> {
if let Some(input) = input {
for key in ["command", "file_path", "path", "url"] {
if let Some(value) = input.get(key).and_then(|v| v.as_str()) {
return Some(value.to_string());
}
}
}
tool_name.map(|s| s.to_string())
}
pub fn normalize_permission_request(
tool: &str,
message: &Value,
) -> Option<NormalizedPermissionRequest> {
if !message.is_object() {
return None;
}
if tool == "agent" {
if message.get("type").and_then(|v| v.as_str()) != Some("permission_request") {
return None;
}
let id = value_str(message, "permissionID").or_else(|| value_str(message, "permission_id"));
let metadata = message.get("metadata").filter(|v| v.is_object());
let title = value_str(message, "title");
let command = metadata
.and_then(|m| m.get("command"))
.and_then(|v| v.as_str())
.map(|s| s.to_string())
.or_else(|| title.clone());
let pattern = value_str(message, "pattern").or_else(|| {
metadata
.and_then(|m| m.get("patterns"))
.and_then(|v| v.as_str())
.map(|s| s.to_string())
});
return Some(NormalizedPermissionRequest {
r#type: "permission_request".to_string(),
tool: "agent".to_string(),
id,
session_id: value_str(message, "sessionID")
.or_else(|| value_str(message, "session_id")),
call_id: value_str(message, "callID").or_else(|| value_str(message, "call_id")),
tool_name: value_str(message, "tool"),
title,
command,
pattern,
scope: ask_scope("agent").unwrap().to_string(),
input: None,
raw: message.clone(),
});
}
if tool == "claude" {
let request = message.get("request");
let is_can_use_tool = message.get("type").and_then(|v| v.as_str())
== Some("control_request")
&& request
.and_then(|r| r.get("subtype"))
.and_then(|v| v.as_str())
== Some("can_use_tool");
if !is_can_use_tool {
return None;
}
let request = request.unwrap();
let tool_name = request
.get("tool_name")
.and_then(|v| v.as_str())
.map(|s| s.to_string());
let input = request.get("input").filter(|v| v.is_object()).cloned();
return Some(NormalizedPermissionRequest {
r#type: "permission_request".to_string(),
tool: "claude".to_string(),
id: value_str(message, "request_id"),
session_id: value_str(message, "session_id"),
call_id: request
.get("tool_use_id")
.and_then(|v| v.as_str())
.map(|s| s.to_string()),
tool_name: tool_name.clone(),
title: tool_name.clone(),
command: derive_claude_command(tool_name.as_deref(), input.as_ref()),
pattern: None,
scope: ask_scope("claude").unwrap().to_string(),
input,
raw: message.clone(),
});
}
None
}
pub fn build_permission_response(
tool: &str,
request: &NormalizedPermissionRequest,
decision: &str,
) -> Result<Value, String> {
if !ASK_DECISIONS.contains(&decision) {
return Err(format!(
"Invalid permission decision \"{}\". Expected one of: once, always, reject.",
decision
));
}
let id = request.id.clone().unwrap_or_default();
if tool == "agent" {
return Ok(json!({
"type": "permission_response",
"permissionID": id,
"response": decision,
}));
}
if tool == "claude" {
if decision == "reject" {
return Ok(json!({
"type": "control_response",
"response": {
"subtype": "success",
"request_id": id,
"response": {
"behavior": "deny",
"message": "Denied by consumer (ask mode).",
},
},
}));
}
let updated_input = request.input.clone().unwrap_or_else(|| json!({}));
return Ok(json!({
"type": "control_response",
"response": {
"subtype": "success",
"request_id": id,
"response": {
"behavior": "allow",
"updatedInput": updated_input,
},
},
}));
}
Err(ask_unsupported_error(tool))
}
#[derive(Debug, Clone)]
pub struct PermissionParityRow {
pub tool: &'static str,
pub native_mechanism: &'static str,
pub scope: &'static str,
pub relay: bool,
pub notes: &'static str,
}
pub fn permission_parity() -> Vec<PermissionParityRow> {
vec![
PermissionParityRow {
tool: "agent",
native_mechanism: "--permission-mode ask (+ --input-format stream-json)",
scope: "session",
relay: true,
notes: "Native JSON permission_request/permission_response protocol; once | always | reject map 1:1.",
},
PermissionParityRow {
tool: "claude",
native_mechanism: "--permission-mode default (stream-json can_use_tool)",
scope: "tool-input",
relay: true,
notes: "control_request/control_response handshake; no session-wide always, so once and always both allow this call.",
},
PermissionParityRow {
tool: "codex",
native_mechanism: "--ask-for-approval (coupled with --sandbox)",
scope: "sandbox-coupled",
relay: false,
notes: "Approval is coupled with the sandbox policy and not exposed as a tool-agnostic JSON request/response stream.",
},
PermissionParityRow {
tool: "qwen",
native_mechanism: "--approval-mode default",
scope: "interactive-only",
relay: false,
notes: "Headless mode has no relayable per-command JSON approval handshake.",
},
PermissionParityRow {
tool: "gemini",
native_mechanism: "--approval-mode default",
scope: "interactive-only",
relay: false,
notes: "No JSON stdin channel (prompt is passed via -p), so approvals cannot be relayed.",
},
PermissionParityRow {
tool: "opencode",
native_mechanism: "OPENCODE_PERMISSION (static {edit,bash,task} policy)",
scope: "static-policy",
relay: false,
notes: "Only a static up-front policy is available; there is no per-command request/response relay.",
},
]
}
pub struct PermissionRelay<'a> {
tool: String,
on_request: Box<dyn FnMut(&NormalizedPermissionRequest) -> String + 'a>,
write: Box<dyn FnMut(&str) + 'a>,
compact: bool,
handled: Vec<(NormalizedPermissionRequest, String, Value)>,
}
impl<'a> PermissionRelay<'a> {
pub fn new<F, W>(tool: &str, on_request: F, write: W) -> Self
where
F: FnMut(&NormalizedPermissionRequest) -> String + 'a,
W: FnMut(&str) + 'a,
{
Self {
tool: tool.to_string(),
on_request: Box::new(on_request),
write: Box::new(write),
compact: true,
handled: Vec::new(),
}
}
pub fn handle_message(
&mut self,
message: &Value,
) -> Option<(NormalizedPermissionRequest, String)> {
let request = normalize_permission_request(&self.tool, message)?;
let mut decision = (self.on_request)(&request);
if !ASK_DECISIONS.contains(&decision.as_str()) {
decision = "reject".to_string();
}
let frame = build_permission_response(&self.tool, &request, &decision)
.expect("relayable tool with validated decision");
(self.write)(&stringify_ndjson_line(&frame, self.compact));
self.handled
.push((request.clone(), decision.clone(), frame));
Some((request, decision))
}
pub fn get_handled(&self) -> &[(NormalizedPermissionRequest, String, Value)] {
&self.handled
}
}