deny_unknown_fields on every config struct. [enforcement] mode, EnforcementMode and mask-entire-file are gone, and on_parse_error defaults to allow. New settings on_unparsed_read and on_mask_write, default deny, read by later blocks. SecretsConfig::load stays strict for the channel filter. load_or_default skips only the layers that fail, so a typo keeps the other layers and the default list. Hooks note the broken layer and any skipped() secret file beside output that shows text, not beside every Write (shows_text). Under deny the refusal is unchanged. fermata check exits 2 with the line number. A non-UTF-8 layer counts as a failed layer; a layer whose bytes cannot be read stays silent, as pinned.
505 lines
22 KiB
Rust
505 lines
22 KiB
Rust
//! Claude Code hook adapter (PreToolUse + PostToolUse).
|
|
//!
|
|
//! Wire format: stdin is one JSON object with `tool_name` and `tool_input`
|
|
//! (and optionally `tool_response` for PostToolUse).
|
|
//! Stdout is `{"hookSpecificOutput": {...}}` with exit code 0; the JSON
|
|
//! carries the verdict / updated output.
|
|
|
|
use super::{AdapterError, HarnessAdapter, OutputEdit, PathKind, PostToolUsePayload, ToolCall, ToolOp};
|
|
use crate::core::secrets::Redactor;
|
|
use crate::core::Decision;
|
|
use serde_json::{json, Map, Value};
|
|
use std::path::PathBuf;
|
|
|
|
pub struct ClaudeAdapter;
|
|
|
|
impl HarnessAdapter for ClaudeAdapter {
|
|
fn name(&self) -> &'static str {
|
|
"claude"
|
|
}
|
|
|
|
// -- PreToolUse --------------------------------------------------------
|
|
|
|
fn parse_request(&self, input: &[u8]) -> Result<ToolCall, AdapterError> {
|
|
let v: Value = serde_json::from_slice(input)?;
|
|
let tool_name = v
|
|
.get("tool_name")
|
|
.and_then(|x| x.as_str())
|
|
.ok_or_else(|| AdapterError::Parse("missing tool_name".into()))?
|
|
.to_string();
|
|
let tool_input = v.get("tool_input").cloned().unwrap_or(Value::Null);
|
|
|
|
let op = match tool_name.as_str() {
|
|
"Read" => path_op(&tool_input, PathKind::Read)?,
|
|
"Write" | "Edit" | "MultiEdit" => path_op(&tool_input, PathKind::Write)?,
|
|
// The three that run a command line. Monitor's lines reach the model with
|
|
// no hook between them, so `[policy.bash]` is the only check its command gets.
|
|
"Bash" | "PowerShell" | "Monitor" => command_op(&tool_input)?,
|
|
other => return Err(AdapterError::UnsupportedTool(other.to_string())),
|
|
};
|
|
|
|
Ok(ToolCall {
|
|
tool_name,
|
|
op,
|
|
raw: v,
|
|
})
|
|
}
|
|
|
|
fn render_decision(
|
|
&self,
|
|
_call: &ToolCall,
|
|
decision: &Decision,
|
|
) -> Result<Vec<u8>, AdapterError> {
|
|
// No rule stopped the call: say nothing, and Claude Code's own permission
|
|
// handling goes on as if there were no hook. `"allow"` would skip its prompt,
|
|
// and fermata approves nothing.
|
|
let (verdict, reason) = match decision {
|
|
Decision::Allow => return Ok(b"{}".to_vec()),
|
|
Decision::Ask(r) => ("ask", r.message.clone()),
|
|
Decision::Deny(r) => ("deny", r.message.clone()),
|
|
};
|
|
let out = json!({
|
|
"hookSpecificOutput": {
|
|
"hookEventName": "PreToolUse",
|
|
"permissionDecision": verdict,
|
|
"permissionDecisionReason": reason,
|
|
}
|
|
});
|
|
Ok(serde_json::to_vec(&out)?)
|
|
}
|
|
|
|
// -- PostToolUse -------------------------------------------------------
|
|
|
|
fn parse_post_tool_use(&self, input: &[u8]) -> Result<PostToolUsePayload, AdapterError> {
|
|
let v: Value = serde_json::from_slice(input)?;
|
|
let tool_name = v
|
|
.get("tool_name")
|
|
.and_then(|x| x.as_str())
|
|
.ok_or_else(|| AdapterError::Parse("missing tool_name".into()))?
|
|
.to_string();
|
|
let tool_input = v.get("tool_input").cloned().unwrap_or(Value::Null);
|
|
let tool_response = v.get("tool_response").cloned().unwrap_or(Value::Null);
|
|
Ok(PostToolUsePayload { tool_name, tool_input, tool_response })
|
|
}
|
|
|
|
fn redact_output(&self, payload: &PostToolUsePayload, redactor: &Redactor) -> OutputEdit {
|
|
let mut walk = RedactWalk { redactor, tool: &payload.tool_name, mcp: is_mcp(payload), redactions: 0, unmaskable: Vec::new() };
|
|
let output = walk.value(&payload.tool_response, None, None, Place::Top);
|
|
if !walk.unmaskable.is_empty() {
|
|
walk.unmaskable.sort();
|
|
walk.unmaskable.dedup();
|
|
return OutputEdit::Unmaskable { keys: walk.unmaskable };
|
|
}
|
|
if walk.redactions == 0 {
|
|
return OutputEdit::Unchanged;
|
|
}
|
|
OutputEdit::Replaced { output, redactions: walk.redactions }
|
|
}
|
|
|
|
fn output_text<'a>(&self, payload: &PostToolUsePayload, output: &'a Value) -> Vec<&'a str> {
|
|
let mut text = Vec::new();
|
|
collect_text(output, None, None, Place::Top, is_mcp(payload), &mut text);
|
|
text
|
|
}
|
|
|
|
fn shows_text(&self, payload: &PostToolUsePayload) -> bool {
|
|
is_mcp(payload) || matches!(payload.tool_name.as_str(), "Read" | "Bash" | "PowerShell" | "Grep")
|
|
}
|
|
|
|
fn render_post_tool_use(
|
|
&self,
|
|
_payload: &PostToolUsePayload,
|
|
updated_output: Option<&Value>,
|
|
context: Option<&str>,
|
|
) -> Result<Vec<u8>, AdapterError> {
|
|
// When there are no changes, return `{}` — Claude Code interprets
|
|
// an empty object as "use original output, no modifications".
|
|
if updated_output.is_none() && context.is_none() {
|
|
return Ok(b"{}".to_vec());
|
|
}
|
|
let mut specific = json!({ "hookEventName": "PostToolUse" });
|
|
if let Some(output) = updated_output {
|
|
specific["updatedToolOutput"] = output.clone();
|
|
}
|
|
if let Some(context) = context {
|
|
specific["additionalContext"] = json!(context);
|
|
}
|
|
Ok(serde_json::to_vec(&json!({ "hookSpecificOutput": specific }))?)
|
|
}
|
|
|
|
/// Claude Code ignores an `updatedToolOutput` that does not match a built-in
|
|
/// tool's output schema and uses the original, so a built-in tool gets a
|
|
/// replacement its schema takes: see [`withheld_output`]. MCP output is not
|
|
/// validated and takes the refusal as it is. `additionalContext` says the same
|
|
/// beside the result, because a shape can hide the text from the reader.
|
|
fn render_post_tool_use_withheld(
|
|
&self,
|
|
payload: &PostToolUsePayload,
|
|
refusal: &str,
|
|
) -> Result<Vec<u8>, AdapterError> {
|
|
let out = json!({
|
|
"hookSpecificOutput": {
|
|
"hookEventName": "PostToolUse",
|
|
"updatedToolOutput": withheld_output(payload, refusal),
|
|
"additionalContext": refusal,
|
|
}
|
|
});
|
|
Ok(serde_json::to_vec(&out)?)
|
|
}
|
|
}
|
|
|
|
fn is_mcp(payload: &PostToolUsePayload) -> bool {
|
|
payload.tool_name.starts_with("mcp__")
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// What Claude Code's output schemas fix
|
|
// ---------------------------------------------------------------------------
|
|
|
|
/// The enum and literal string values of Claude Code's built-in tool outputs, by
|
|
/// field name, read from the 87 `outputSchema` getters of v2.1.314 and the helpers they
|
|
/// use. `type` also holds the MCP content block types, which are no secret either.
|
|
/// Flag-gated tools count: a list too long costs nothing.
|
|
///
|
|
/// A built-in's replacement that changes such a value fails `safeParse`, and Claude
|
|
/// Code then uses the original output: the whole output would leak. An exact listed
|
|
/// value says nothing about a secret, so it stays. Anything else under these names
|
|
/// is treated as text.
|
|
const SCHEMA_VALUES: &[(&str, &[&str])] = &[
|
|
("type", &[
|
|
"text", "image", "notebook", "pdf", "parts", "file_unchanged", "create", "update",
|
|
"image/jpeg", "image/png", "image/gif", "image/webp",
|
|
"audio", "resource", "resource_link", "base64", "document",
|
|
]),
|
|
("mediaType", &["image/jpeg", "image/png", "image/gif", "image/webp"]),
|
|
("media_type", &["image/jpeg", "image/png", "image/gif", "image/webp", "application/pdf"]),
|
|
("mode", &["content", "files_with_matches", "count", "new", "existing"]),
|
|
("source", &["seeded"]),
|
|
("status", &[
|
|
"completed", "async_launched", "remote_launched", "teammate_spawned", "inline", "forked",
|
|
"working", "failed", "cancelled", "modified", "added", "created", "updated", "deleted",
|
|
"has_existing", "unavailable", "refreshed", "error", "not_connected", "pending", "in_progress",
|
|
"delivered", "already_delivered", "nothing_read", "no_run", "uploaded", "not_attempted",
|
|
]),
|
|
("kind", &["committed", "amended", "cherry-picked", "choice", "text", "number"]),
|
|
("action", &[
|
|
"merged", "rebased", "created", "edited", "commented", "closed", "reopened", "ready", "draft",
|
|
"auto-merge-enabled", "auto-merge-disabled", "keep", "remove", "pin", "unpin",
|
|
]),
|
|
("cell_type", &["code", "markdown"]),
|
|
("outcome", &[
|
|
"ok", "conflict", "missing", "refused", "failed", "not_found", "connected", "not_now",
|
|
"no_attempt_yet", "fixed", "skipped", "no_change_needed",
|
|
]),
|
|
("store_kind", &["personal", "project"]),
|
|
("op", &["created", "updated", "batch"]),
|
|
("operation", &[
|
|
"goToDefinition", "findReferences", "hover", "documentSymbol", "workspaceSymbol",
|
|
"goToImplementation", "prepareCallHierarchy", "incomingCalls", "outgoingCalls",
|
|
]),
|
|
("level", &["low", "medium", "high", "xhigh", "max"]),
|
|
("verdict", &["CONFIRMED", "PLAUSIBLE"]),
|
|
("handback", &["send", "flagged", "withheld"]),
|
|
("unanswered", &["skipped", "replied_in_chat", "dismissed"]),
|
|
("stagedWording", &["true"]),
|
|
("trigger", &["user_asked", "proactive"]),
|
|
("authority", &["human-principal", "human-other", "peer-agent", "world-event"]),
|
|
("method", &[
|
|
"project_info", "project_read", "project_search", "project_write", "project_delete",
|
|
"project_memory_list", "project_memory_read",
|
|
"list_projects", "get_project", "list_files", "get_file", "finalize_plan", "write_files",
|
|
"delete_files", "register_assets", "unregister_assets", "create_project", "report_validate",
|
|
]),
|
|
("display", &["render", "attach"]),
|
|
("state", &["published", "in-review", "publishing", "on-shelf", "refused"]),
|
|
("disabledReason", &["config_off", "user_present", "no_transport"]),
|
|
("message", &["sent", "uncertain", "not_sent"]),
|
|
("taskType", &["local_workflow", "remote_agent"]),
|
|
("fallback", &["sequential"]),
|
|
("rail", &["durable_wake", "live_stopped"]),
|
|
("working_copy", &["bound", "left"]),
|
|
("verb", &["put", "retract", "read", "script"]),
|
|
("scope", &["shared", "all"]),
|
|
("editsNotWritten", &["write_failed", "not_writable", "changed_during_publish", "hard_linked"]),
|
|
("auto_open", &["at_create", "after_first_write"]),
|
|
("files_error_kind", &["type_owned_path"]),
|
|
("unread", &["withheld", "not_listed", "not_text", "too_large", "unavailable", "result_full"]),
|
|
];
|
|
|
|
/// Listed names that are also a free-text field in other tools: a secret among their
|
|
/// text takes a mask. `source` is a notebook cell's text in the same Read output,
|
|
/// `message` a plain string in most tools that have one.
|
|
const SCHEMA_VALUES_ALSO_TEXT: &[&str] = &["source", "message"];
|
|
|
|
/// String fields with a maximum length in those schemas (ReportFindings).
|
|
const SCHEMA_MAX_LEN: &[(&str, usize)] = &[("short_summary", 60), ("category", 40)];
|
|
|
|
/// The built-in outputs whose object keys are free text (AskUserQuestion's
|
|
/// question -> answer records, and the records of the tools that report under names
|
|
/// of their own). Every other key in those schemas is a fixed name.
|
|
const RECORD_FIELDS: &[&str] = &[
|
|
"answers", "annotations", "fields", "content", "config", "pool", "sessions", "runners", "secrets", "health",
|
|
"gauges",
|
|
];
|
|
|
|
/// Fields of the Artifact tool's schema with a pattern or an enum this file cannot
|
|
/// list: `reason` draws on a list built at run time, the others are regular
|
|
/// expressions over hashes, ids, versions and addresses. No list of exact values can
|
|
/// say what stays, so a secret found there refuses the output instead of taking a mask
|
|
/// that the schema would reject.
|
|
const ARTIFACT_PATTERN_FIELDS: &[&str] = &[
|
|
"id", "from_id", "artifact_id", "seededThread", "url", "ver", "version", "base", "live", "next", "sha256",
|
|
"content_type", "reason",
|
|
];
|
|
|
|
/// Whether this field name holds an enum in some schema, and the values it allows.
|
|
fn schema_values(key: Option<&str>) -> Option<&'static [&'static str]> {
|
|
let key = key?;
|
|
SCHEMA_VALUES.iter().find(|(name, _)| *name == key).map(|(_, values)| *values)
|
|
}
|
|
|
|
fn is_schema_value(key: Option<&str>, value: &str) -> bool {
|
|
schema_values(key).is_some_and(|values| values.contains(&value))
|
|
}
|
|
|
|
/// `text` cut to the length the schema allows for this field, if it limits one.
|
|
fn fit_schema(key: Option<&str>, text: String) -> String {
|
|
match key.and_then(|k| SCHEMA_MAX_LEN.iter().find(|(name, _)| *name == k)) {
|
|
Some((_, max)) if text.chars().count() > *max => text.chars().take(*max).collect(),
|
|
_ => text,
|
|
}
|
|
}
|
|
|
|
fn is_base64(s: &str) -> bool {
|
|
s.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'/' | b'=' | b'-' | b'_' | b'\r' | b'\n'))
|
|
}
|
|
|
|
/// Where a value sits in a tool response, as far as a content block goes.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
enum Place {
|
|
/// The response itself, which can be a single block.
|
|
Top,
|
|
/// The `content` list of the response.
|
|
Content,
|
|
/// A block in that list or in a top-level list, or its `source`.
|
|
Block,
|
|
/// A field of a block, or of the response.
|
|
BlockField,
|
|
/// Anywhere else: a result's own data, however much it looks like a block.
|
|
Inside,
|
|
}
|
|
|
|
impl Place {
|
|
fn item(self) -> Self {
|
|
match self {
|
|
Self::Top | Self::Content => Self::Block,
|
|
_ => Self::Inside,
|
|
}
|
|
}
|
|
|
|
fn field(self, key: &str) -> Self {
|
|
match (self, key) {
|
|
(Self::Top, "content") => Self::Content,
|
|
(Self::Block, "source") => Self::Block,
|
|
(Self::Top | Self::Block, _) => Self::BlockField,
|
|
_ => Self::Inside,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Image and document bytes are not text. A short secret can match inside base64
|
|
/// by chance, and masking it there breaks the image and with it the next API
|
|
/// request, so these stay:
|
|
/// - `base64` of a built-in tool (Read of an image or a PDF).
|
|
/// - `data` beside `type: image|audio|base64` in a top-level content block, at least
|
|
/// 64 characters of base64, so that a token named `data` is still text. The same
|
|
/// object deeper down is the result's own data, which a server can shape to look
|
|
/// like a block, and is read as text.
|
|
/// - Bash's `stdout` under `isImage: true` that holds a base64 data URL.
|
|
fn is_binary(key: Option<&str>, parent: Option<&Map<String, Value>>, place: Place, value: &str, mcp: bool) -> bool {
|
|
match key {
|
|
Some("base64") => !mcp && is_base64(value),
|
|
Some("data") => {
|
|
place == Place::BlockField
|
|
&& value.len() >= 64
|
|
&& is_base64(value)
|
|
&& parent
|
|
.and_then(|p| p.get("type"))
|
|
.and_then(Value::as_str)
|
|
.is_some_and(|t| matches!(t, "image" | "audio" | "base64"))
|
|
}
|
|
Some("stdout") => {
|
|
!mcp && parent.and_then(|p| p.get("isImage")) == Some(&Value::Bool(true))
|
|
&& value.strip_prefix("data:image/").and_then(|rest| rest.split_once(";base64,")).is_some_and(|(_, data)| is_base64(data))
|
|
}
|
|
_ => false,
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Redacting a response in its own shape
|
|
// ---------------------------------------------------------------------------
|
|
|
|
/// Walks a tool response and redacts every string, keeping the structure, numbers
|
|
/// and booleans.
|
|
struct RedactWalk<'a> {
|
|
redactor: &'a Redactor,
|
|
tool: &'a str,
|
|
mcp: bool,
|
|
redactions: usize,
|
|
/// Keys of the secrets found where a built-in's schema cannot take a mask.
|
|
unmaskable: Vec<String>,
|
|
}
|
|
|
|
impl RedactWalk<'_> {
|
|
fn value(&mut self, value: &Value, key: Option<&str>, parent: Option<&Map<String, Value>>, place: Place) -> Value {
|
|
match value {
|
|
Value::String(s) => Value::String(self.string(s, key, parent, place)),
|
|
Value::Array(items) => Value::Array(items.iter().map(|v| self.value(v, None, None, place.item())).collect()),
|
|
Value::Object(map) => {
|
|
let free_keys = self.mcp || key.is_some_and(|k| RECORD_FIELDS.contains(&k));
|
|
let mut out = Map::with_capacity(map.len());
|
|
for (k, v) in map {
|
|
let walked = self.value(v, Some(k), Some(map), place.field(k));
|
|
out.insert(self.object_key(k, free_keys, &out), walked);
|
|
}
|
|
Value::Object(out)
|
|
}
|
|
other => other.clone(),
|
|
}
|
|
}
|
|
|
|
fn string(&mut self, s: &str, key: Option<&str>, parent: Option<&Map<String, Value>>, place: Place) -> String {
|
|
if is_binary(key, parent, place, s, self.mcp) {
|
|
return s.to_string();
|
|
}
|
|
let redacted = self.redactor.redact(s);
|
|
if !redacted.was_redacted() {
|
|
return s.to_string();
|
|
}
|
|
if self.tool == "Artifact" && key.is_some_and(|k| ARTIFACT_PATTERN_FIELDS.contains(&k)) {
|
|
self.unmaskable.extend(redacted.redactions.iter().map(|r| r.key.clone()));
|
|
return s.to_string();
|
|
}
|
|
// MCP output has no schema: only a content block's `type` is structure.
|
|
if is_schema_value(key, s) && (!self.mcp || key == Some("type")) {
|
|
return s.to_string();
|
|
}
|
|
let also_text = key.is_some_and(|k| SCHEMA_VALUES_ALSO_TEXT.contains(&k));
|
|
if !self.mcp && schema_values(key).is_some() && !also_text {
|
|
self.unmaskable.extend(redacted.redactions.iter().map(|r| r.key.clone()));
|
|
}
|
|
self.redactions += redacted.redactions.len();
|
|
fit_schema(key, redacted.text)
|
|
}
|
|
|
|
/// An MCP result and a built-in's record ([`RECORD_FIELDS`]) take a masked key.
|
|
/// Any other key of a built-in is its schema's name, so a secret there cannot
|
|
/// be masked without failing the schema, which would let the original through.
|
|
fn object_key(&mut self, key: &str, free: bool, taken: &Map<String, Value>) -> String {
|
|
let redacted = self.redactor.redact(key);
|
|
if !redacted.was_redacted() {
|
|
return key.to_string();
|
|
}
|
|
if !free {
|
|
self.unmaskable.extend(redacted.redactions.iter().map(|r| r.key.clone()));
|
|
return key.to_string();
|
|
}
|
|
self.redactions += redacted.redactions.len();
|
|
let mut masked = redacted.text.clone();
|
|
let mut n = 1;
|
|
while taken.contains_key(&masked) {
|
|
n += 1;
|
|
masked = format!("{}#{n}", redacted.text);
|
|
}
|
|
masked
|
|
}
|
|
}
|
|
|
|
/// Every string a scanner should read: not binary data, not fixed schema values.
|
|
fn collect_text<'a>(
|
|
value: &'a Value,
|
|
key: Option<&str>,
|
|
parent: Option<&Map<String, Value>>,
|
|
place: Place,
|
|
mcp: bool,
|
|
text: &mut Vec<&'a str>,
|
|
) {
|
|
match value {
|
|
Value::String(s) if !is_binary(key, parent, place, s, mcp) && !is_schema_value(key, s) => text.push(s),
|
|
Value::Array(items) => items.iter().for_each(|v| collect_text(v, None, None, place.item(), mcp, text)),
|
|
Value::Object(map) => {
|
|
for (k, v) in map {
|
|
text.push(k);
|
|
collect_text(v, Some(k), Some(map), place.field(k), mcp, text);
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Replacing a response with a refusal
|
|
// ---------------------------------------------------------------------------
|
|
|
|
/// A replacement for the whole response that holds only `refusal`.
|
|
///
|
|
/// Bash, Read and Artifact do not reuse the response at all. Their replacement is the
|
|
/// smallest form their schema accepts, so no optional field of the original can
|
|
/// make it fail (Bash's `gitOperation`, Artifact's patterns), and no image flag makes
|
|
/// the mapper send the refusal to the API as image data (`isImage`, Read's `image` and
|
|
/// `pdf`). Other built-ins keep their shape: see [`withheld_shape`].
|
|
fn withheld_output(payload: &PostToolUsePayload, refusal: &str) -> Value {
|
|
let response = &payload.tool_response;
|
|
if is_mcp(payload) || !(response.is_object() || response.is_array()) {
|
|
return Value::String(refusal.to_string());
|
|
}
|
|
match payload.tool_name.as_str() {
|
|
"Bash" => json!({"stdout": refusal, "stderr": "", "interrupted": false, "isImage": false}),
|
|
"Read" => json!({
|
|
"type": "text",
|
|
"file": {"filePath": "[fermata]", "content": refusal, "numLines": 1, "startLine": 1, "totalLines": 1},
|
|
}),
|
|
"Artifact" => json!({
|
|
"read": {"url": "[fermata]", "bytes": 0, "code": 0, "codeText": "", "result": refusal, "durationMs": 0},
|
|
}),
|
|
_ => withheld_shape(response, None, refusal),
|
|
}
|
|
}
|
|
|
|
/// `value` with every string replaced by `refusal` and every array cut to its
|
|
/// first item. Numbers and booleans stay: they are counts and flags the schema
|
|
/// requires. So do exact schema values ([`SCHEMA_VALUES`]). Records keyed by free
|
|
/// text ([`RECORD_FIELDS`]) are emptied, because their keys are text too.
|
|
fn withheld_shape(value: &Value, key: Option<&str>, refusal: &str) -> Value {
|
|
match value {
|
|
Value::String(s) if is_schema_value(key, s) => value.clone(),
|
|
Value::String(_) => Value::String(fit_schema(key, refusal.to_string())),
|
|
Value::Array(items) => Value::Array(items.iter().take(1).map(|v| withheld_shape(v, None, refusal)).collect()),
|
|
Value::Object(_) if key.is_some_and(|k| RECORD_FIELDS.contains(&k)) => json!({}),
|
|
Value::Object(map) => Value::Object(
|
|
map.iter().map(|(k, v)| (k.clone(), withheld_shape(v, Some(k), refusal))).collect(),
|
|
),
|
|
other => other.clone(),
|
|
}
|
|
}
|
|
|
|
fn path_op(tool_input: &Value, kind: PathKind) -> Result<ToolOp, AdapterError> {
|
|
let p = tool_input
|
|
.get("file_path")
|
|
.and_then(|x| x.as_str())
|
|
.ok_or_else(|| AdapterError::Parse("missing tool_input.file_path".into()))?;
|
|
Ok(ToolOp::Path {
|
|
path: PathBuf::from(p),
|
|
kind,
|
|
})
|
|
}
|
|
|
|
fn command_op(tool_input: &Value) -> Result<ToolOp, AdapterError> {
|
|
let c = tool_input
|
|
.get("command")
|
|
.and_then(|x| x.as_str())
|
|
.ok_or_else(|| AdapterError::Parse("missing tool_input.command".into()))?;
|
|
Ok(ToolOp::Command { text: c.to_string() })
|
|
}
|