Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

28q: a held push's "Blocked before push" lands on its own call (#809)

Oleksandr Ivanchenkoc0fb334fc73a
diff --git a/src/drivers/activity.rs b/src/drivers/activity.rs
index 990215b6..1961945d 100644
--- a/src/drivers/activity.rs
+++ b/src/drivers/activity.rs
@@ -95,10 +95,24 @@ pub struct ActivityLog {
/// so one Deny ends one tool step `declined`, and of `stopped` ones paired with the denied
/// step whose wait they ended (28k).
paired: HashSet<usize>,
- /// Calls kwnt refused on its own this turn, before the engine heard (28k), oldest first: the
- /// tool's name and the words its step shows instead of what the bot was told. Each one is
- /// used by one failed step of that tool.
- refused: Vec<(String, &'static str)>,
+ /// Calls kwnt refused on its own this turn, before the engine heard (28k), oldest first. Each
+ /// one is used by one failed step: its own call's (28q), see [`ActivityLog::refusal_for`].
+ refused: Vec<Refusal>,
+ /// The arguments of each open tool step (index in `steps`), as the engine sent them, so a
+ /// refusal noted without the engine's id finds its own call (28q).
+ open_args: HashMap<usize, Value>,
+}
+
+/// A call kwnt refused on its own (28k), and which call that was (28q).
+#[derive(Debug)]
+struct Refusal {
+ tool: String,
+ /// The engine's id for the call, which its tool step carries, when kwnt was told it.
+ call: Option<String>,
+ /// The call's arguments, when kwnt knows them.
+ args: Option<Value>,
+ /// What the step shows instead of the text the bot was told.
+ words: &'static str,
}
fn now() -> String {
@@ -207,12 +221,14 @@ impl ActivityLog {
self.steps[i].tool = Some(name.clone());
self.steps[i].detail = detail.map(|d| cut(&self.redact(&d), MAX_DETAIL));
self.tools.insert(id.clone(), i);
+ self.open_args.insert(i, args.clone());
changed.push(self.steps[i].clone());
}
}
RuntimeEvent::ToolCallCompleted { id, result } => {
changed.extend(self.close_thinking());
if let Some(i) = self.tools.remove(id) {
+ let args = self.open_args.remove(&i);
let (status, why) = step_end(result);
let card = self.declined_card_for(i, status, why.as_deref());
if let Some(why) = why.as_deref() {
@@ -232,7 +248,7 @@ impl ActivityLog {
"declined"
}
None => {
- if let Some(words) = self.blocked_detail(i, status, why.as_deref()) {
+ if let Some(words) = self.blocked_detail(i, id, args.as_ref(), status, why.as_deref()) {
self.steps[i].detail = Some(words.to_string());
}
status
@@ -247,14 +263,14 @@ impl ActivityLog {
}
/// The person's Deny behind tool step `i`, which [`step_end`] ended `status` with reason `why`
- /// (28b): when the step failed with the CLI's denial ([`denial_shown`]) and this
+ /// (28b): when the step failed with the CLI's denial ([`crate::mcp::DENIED_TEXT`]) and this
/// turn has a `declined` approval step for the same tool not yet paired with a tool step, that
/// approval step's index. The card settles before the denial reaches the engine, but the tool
/// step usually started first, so step order isn't read. A denial with no declined card (kwnt
/// refused a call that names its own secret files, or a ticket couldn't be stored) wasn't the
/// person's no: `None`, and the step stays `failed`.
fn declined_card_for(&self, i: usize, status: &str, why: Option<&str>) -> Option<usize> {
- if status != "failed" || !why.is_some_and(|w| w.starts_with(denial_shown())) {
+ if status != "failed" || !the_cli_denied(why) {
return None;
}
let tool = self.steps[i].tool.as_deref()?;
@@ -267,31 +283,69 @@ impl ActivityLog {
})
}
- /// kwnt refused a call to `tool` on its own, before the engine heard (28k): the next failed
- /// step of that tool shows `words`, not the text the bot was told.
+ /// kwnt refused a call to `tool` on its own, before the engine heard (28k), and doesn't know
+ /// which call: a failed step of that tool shows `words`, not the text the bot was told, once
+ /// it is the only step of that tool still open (28q).
pub fn refused(&mut self, tool: &str, words: &'static str) {
- self.refused.push((tool.to_string(), words));
+ self.refused_call(tool, None, None, words);
+ }
+
+ /// kwnt refused one call to `tool` on its own, before the engine heard (28k): the failed step
+ /// of that call shows `words`, not the text the bot was told. `call` is the engine's id for it
+ /// (its step's id) and `args` its arguments, when kwnt knows them, so a neighbouring call of
+ /// the same tool that fails for its own reason keeps that reason (28q).
+ pub fn refused_call(&mut self, tool: &str, call: Option<&str>, args: Option<&Value>, words: &'static str) {
+ self.refused.push(Refusal {
+ tool: tool.to_string(),
+ call: call.filter(|c| !c.is_empty()).map(str::to_string),
+ args: args.cloned(),
+ words,
+ });
+ }
+
+ /// The refusal that belongs to the tool step with engine id `id`, of tool `tool` and with
+ /// arguments `args`, which just ended (28q), oldest first:
+ /// - one noted with that same id;
+ /// - else one of that tool with the same arguments;
+ /// - else, only when no other step of that tool is still open, one of that tool.
+ ///
+ /// A refusal whose id names another step still open waits for that step.
+ fn refusal_for(&self, id: &str, tool: Option<&str>, args: Option<&Value>) -> Option<usize> {
+ if let Some(k) = self.refused.iter().position(|r| r.call.as_deref() == Some(id)) {
+ return Some(k);
+ }
+ let tool = tool?;
+ let free = |r: &Refusal| r.tool == tool && r.call.as_ref().is_none_or(|c| !self.tools.contains_key(c));
+ if let Some(k) = self.refused.iter().position(|r| free(r) && r.args.is_some() && r.args.as_ref() == args) {
+ return Some(k);
+ }
+ let alone = !self.tools.values().any(|&j| self.steps[j].tool.as_deref() == Some(tool));
+ if alone {
+ self.refused.iter().position(free)
+ } else {
+ None
+ }
}
/// What tool step `i`, which [`step_end`] ended `status` with reason `why` and no declined card
/// of its own, shows instead of the bot's text (28k). Nobody pressed Deny, so it never says the
/// person did:
- /// - the words of a refusal kwnt noted for its tool ([`refused`](Self::refused)), such as the
- /// pre-push gate's;
- /// - when it failed with the CLI's denial ([`denial_shown`]) and the turn has a `stopped` approval
+ /// - the words of a refusal kwnt noted for its own call ([`refused_call`](Self::refused_call),
+ /// matched by [`refusal_for`](Self::refusal_for)), such as the pre-push gate's;
+ /// - when it failed with [`crate::mcp::DENIED_TEXT`] and the turn has a `stopped` approval
/// step of the same tool not yet paired (its card stopped waiting with no answer),
/// [`crate::mcp::NOBODY_ANSWERED_STEP_DETAIL`], and that card is paired with it;
- /// - else, with that denial, [`crate::mcp::BLOCKED_STEP_DETAIL`] (kwnt's
+ /// - else, with [`crate::mcp::DENIED_TEXT`], [`crate::mcp::BLOCKED_STEP_DETAIL`] (kwnt's
/// secret files, a ticket it couldn't store).
- fn blocked_detail(&mut self, i: usize, status: &str, why: Option<&str>) -> Option<&'static str> {
+ fn blocked_detail(&mut self, i: usize, id: &str, args: Option<&Value>, status: &str, why: Option<&str>) -> Option<&'static str> {
if status != "failed" {
return None;
}
let tool = self.steps[i].tool.clone();
- if let Some(k) = self.refused.iter().position(|(t, _)| Some(t) == tool.as_ref()) {
- return Some(self.refused.remove(k).1);
+ if let Some(k) = self.refusal_for(id, tool.as_deref(), args) {
+ return Some(self.refused.remove(k).words);
}
- if !why.is_some_and(|w| w.starts_with(denial_shown())) {
+ if !the_cli_denied(why) {
return None;
}
let stopped = (0..self.steps.len()).find(|j| {
@@ -342,6 +396,7 @@ impl ActivityLog {
pub fn finish(&mut self) -> Vec<Step> {
let mut changed: Vec<Step> = self.close_thinking().into_iter().collect();
self.tools.clear();
+ self.open_args.clear();
for i in 0..self.steps.len() {
if self.steps[i].is_open() {
changed.push(self.end(i, "stopped"));
@@ -647,15 +702,6 @@ pub fn with_page_title(mut result: Value, tool: &str, text: &str) -> Value {
result
}
-/// The part of [`crate::mcp::DENIED_TEXT`] a failed step shows, the CLI's own denial: [`step_end`]
-/// leaves out [`crate::mcp::NOT_ANOTHER_WAY_TEXT`] (27b), so a Deny is matched on what's left (28b).
-fn denial_shown() -> &'static str {
- crate::mcp::DENIED_TEXT
- .strip_suffix(crate::mcp::NOT_ANOTHER_WAY_TEXT)
- .unwrap_or(crate::mcp::DENIED_TEXT)
- .trim_end()
-}
-
/// A finished tool call's result: `None` when it went fine, `Some(why)` when its step is
/// `failed` (error, failed, denied or cancelled), with the reason it gave, trimmed, if any. The
/// one rule for "a tool failed", shared with the chat's failure line (`server::tool_failures`).
@@ -673,6 +719,14 @@ pub fn failed_reason(result: &Value) -> Option<Option<&str>> {
)
}
+/// Whether a failed step's reason `why`, as [`step_end`] left it, is the CLI's denial
+/// ([`crate::mcp::DENIED_TEXT`]). `step_end` drops that text's last sentence (27b,
+/// [`crate::mcp::NOT_ANOTHER_WAY_TEXT`]), so only its first sentence is read.
+fn the_cli_denied(why: Option<&str>) -> bool {
+ let first = crate::mcp::DENIED_TEXT.split_inclusive('.').next().unwrap_or(crate::mcp::DENIED_TEXT);
+ why.is_some_and(|w| w.starts_with(first))
+}
+
/// How a finished tool call's step ends, and the detail it shows (26b). A call nobody approved
/// in time is `unanswered` and a dry-run call `rehearsed`, never "ok": by the result's status
/// (kwnt's own tools) or by the refusal kwnt gave the engine (the claude CLI reports both as an
@@ -1770,7 +1824,6 @@ mod tests {
(ended[0].status, ended[0].detail.as_deref()),
("failed", Some(crate::mcp::BLOCKED_STEP_DETAIL))
);
- assert_eq!(denial_shown(), "The user denied this tool call.");
log.wait("approval", "t1", "Waiting for your approval: Fetching", Some("WebFetch"));
log.settle("t1", "declined");
log.wait("approval", "t2", "Waiting for your approval: Running `ls`", Some("Bash"));
@@ -1878,6 +1931,118 @@ mod tests {
assert_eq!(ended[0].detail.as_deref(), Some(crate::mcp::PREPUSH_BLOCKED_STEP_DETAIL));
}
+ /// 28q (Rigel's 28k QA note 1): two overlapping calls of one tool in one turn, one failing
+ /// for its own reason and one the pre-push gate held. The held one shows "Blocked before push;
+ /// nothing ran" and the other keeps its own reason, whichever ends first and whether or not the
+ /// gate's note arrives before the other one fails; keyed by the engine's id when kwnt was told
+ /// it (Claude Code's tool-use id, the API driver's call id), else by the call's arguments.
+ #[test]
+ fn a_held_push_keeps_its_words_next_to_a_call_that_failed_on_its_own() {
+ const TOOL: &str = "mcp__github__create_or_update_file";
+ let gate = "kwant is checking this push of main before it goes (pre-push card pp1). Nothing was pushed.";
+ let own = "409 Conflict: README.md changed on the branch";
+ let other_args = json!({"owner": "o", "repo": "r", "branch": "lin-x", "path": "README.md"});
+ let held_args = json!({"owner": "o", "repo": "r", "branch": "main", "path": "src/lib.rs"});
+ let failed = |id: &str, error: &str| RuntimeEvent::ToolCallCompleted {
+ id: id.into(),
+ result: json!({"status": "error", "error": error}),
+ };
+ let words_of = |log: &mut ActivityLog, ev: RuntimeEvent| {
+ let ended = log.observe(&ev);
+ (ended[0].status, ended[0].detail.clone().unwrap_or_default())
+ };
+ let own_reason = ("failed", own.to_string());
+ let blocked = ("failed", crate::mcp::PREPUSH_BLOCKED_STEP_DETAIL.to_string());
+
+ // How kwnt knows the held call: the engine's id, the arguments only (an engine that sends
+ // no id), or an id from another namespace that no step carries (arguments still match)
+ type Note = fn(&mut ActivityLog, &Value);
+ let notes: [(&str, Note); 3] = [
+ ("engine id", |log, args| log.refused_call(TOOL, Some("held"), Some(args), crate::mcp::PREPUSH_BLOCKED_STEP_DETAIL)),
+ ("arguments", |log, args| log.refused_call(TOOL, None, Some(args), crate::mcp::PREPUSH_BLOCKED_STEP_DETAIL)),
+ ("foreign id", |log, args| log.refused_call(TOOL, Some("gw_1"), Some(args), crate::mcp::PREPUSH_BLOCKED_STEP_DETAIL)),
+ ];
+ for (how, note) in notes {
+ let open = || {
+ let mut log = ActivityLog::default();
+ log.observe(&pending("other", TOOL, other_args.clone()));
+ log.observe(&pending("held", TOOL, held_args.clone()));
+ log
+ };
+ // The gate's note, then the other call fails on its own, then the held one ends
+ let mut log = open();
+ note(&mut log, &held_args);
+ assert_eq!(words_of(&mut log, failed("other", own)), own_reason, "{how}: note first, other ends first");
+ assert_eq!(words_of(&mut log, failed("held", gate)), blocked, "{how}: note first, other ends first");
+ // The held one ends first, then the other
+ let mut log = open();
+ note(&mut log, &held_args);
+ assert_eq!(words_of(&mut log, failed("held", gate)), blocked, "{how}: held ends first");
+ assert_eq!(words_of(&mut log, failed("other", own)), own_reason, "{how}: held ends first");
+ // The other call fails before the gate's note arrives
+ let mut log = open();
+ assert_eq!(words_of(&mut log, failed("other", own)), own_reason, "{how}: other fails before the note");
+ note(&mut log, &held_args);
+ assert_eq!(words_of(&mut log, failed("held", gate)), blocked, "{how}: other fails before the note");
+ // A gate denial reaches the engine as "denied" too
+ let mut log = open();
+ note(&mut log, &held_args);
+ assert_eq!(words_of(&mut log, failed("other", own)), own_reason, "{how}: denied status");
+ let denied_held = RuntimeEvent::ToolCallCompleted { id: "held".into(), result: json!({"status": "denied", "error": gate}) };
+ assert_eq!(words_of(&mut log, denied_held), blocked, "{how}: denied status");
+ }
+
+ // Shown arguments that don't match (the Claude CLI cuts long ones) and no id: by name only
+ // once it is the one step of that tool still open, never a guess between two
+ let mut log = ActivityLog::default();
+ log.observe(&pending("other", TOOL, other_args.clone()));
+ log.observe(&pending("held", TOOL, json!("{\"content\": \"…")));
+ log.refused_call(TOOL, None, Some(&held_args), crate::mcp::PREPUSH_BLOCKED_STEP_DETAIL);
+ assert_eq!(words_of(&mut log, failed("other", own)), own_reason, "two open: no guess");
+ assert_eq!(words_of(&mut log, failed("held", gate)), blocked, "the one left open");
+
+ // A note keyed to a call still open waits for it, even when its arguments repeat another
+ let mut log = ActivityLog::default();
+ log.observe(&pending("other", TOOL, held_args.clone()));
+ log.observe(&pending("held", TOOL, held_args.clone()));
+ log.refused_call(TOOL, Some("held"), Some(&held_args), crate::mcp::PREPUSH_BLOCKED_STEP_DETAIL);
+ assert_eq!(words_of(&mut log, failed("other", own)), own_reason, "same arguments, other id");
+ assert_eq!(words_of(&mut log, failed("held", gate)), blocked, "same arguments, own id");
+
+ // Each held call of two keeps its own note; the bot's text is never touched
+ let mut log = ActivityLog::default();
+ log.observe(&pending("a", TOOL, other_args.clone()));
+ log.observe(&pending("b", TOOL, held_args.clone()));
+ log.refused_call(TOOL, Some("b"), Some(&held_args), crate::mcp::PREPUSH_BLOCKED_STEP_DETAIL);
+ log.refused_call(TOOL, Some("a"), Some(&other_args), crate::mcp::PREPUSH_BLOCKED_STEP_DETAIL);
+ let held_b = failed("b", gate);
+ assert_eq!(words_of(&mut log, held_b.clone()), blocked);
+ assert_eq!(words_of(&mut log, failed("a", gate)), blocked);
+ let RuntimeEvent::ToolCallCompleted { result, .. } = &held_b else { unreachable!() };
+ assert_eq!(result["error"], gate);
+ // Both notes are used up: a later failure keeps its own reason
+ log.observe(&pending("c", TOOL, held_args.clone()));
+ assert_eq!(words_of(&mut log, failed("c", own)), own_reason);
+
+ // Through kwnt's gateway the step is named mcp__kwnt__<server>__<tool> while the gate notes
+ // mcp__<server>__<tool> (Rigel's 28q QA finding 2): the engine's id still finds its own
+ // step, whichever of the two ends first, and never the neighbour's
+ const STEP_TOOL: &str = "mcp__kwnt__github__create_or_update_file";
+ for held_first in [false, true] {
+ let mut log = ActivityLog::default();
+ log.observe(&pending("toolu_other", STEP_TOOL, other_args.clone()));
+ log.observe(&pending("toolu_held", STEP_TOOL, held_args.clone()));
+ log.refused_call(TOOL, Some("toolu_held"), Some(&held_args), crate::mcp::PREPUSH_BLOCKED_STEP_DETAIL);
+ if held_first {
+ assert_eq!(words_of(&mut log, failed("toolu_held", gate)), blocked, "gateway name, held ends first");
+ assert_eq!(words_of(&mut log, failed("toolu_other", own)), own_reason, "gateway name, held ends first");
+ } else {
+ assert_eq!(words_of(&mut log, failed("toolu_other", own)), own_reason, "gateway name, other ends first");
+ assert_eq!(words_of(&mut log, failed("toolu_held", gate)), blocked, "gateway name, other ends first");
+ }
+ }
+ }
+
/// 28k: a denial whose card stopped waiting with no answer (it couldn't stay open, or it was
/// withdrawn) reads "Nobody answered in time", once per card; a Deny still reads as a no.
#[test]
diff --git a/src/mcp/session.rs b/src/mcp/session.rs
index 6f19f730..d924bdd7 100644
--- a/src/mcp/session.rs
+++ b/src/mcp/session.rs
@@ -244,8 +244,22 @@ impl McpToolSession {
}
/// Runs one model-requested call: approval first, then the MCP call. The record is also
- /// appended to the turn's `tool_calls`.
+ /// appended to the turn's `tool_calls`. `call_id` is also the engine's id for the call, the one
+ /// its activity step carries (the API driver's).
pub async fn call(&self, caller: &Caller, call_id: &str, name: &str, raw_arguments: &str) -> CallOutcome {
+ self.call_step(caller, call_id, Some(call_id), name, raw_arguments).await
+ }
+
+ /// [`call`](Self::call) for a call whose engine id, `step_id`, differs from kwnt's `call_id`
+ /// (the gateway's), or is unknown: a refusal kwnt notes on its activity step is keyed to it (28q).
+ pub async fn call_step(
+ &self,
+ caller: &Caller,
+ call_id: &str,
+ step_id: Option<&str>,
+ name: &str,
+ raw_arguments: &str,
+ ) -> CallOutcome {
let start = Instant::now();
let arguments: Value = if raw_arguments.trim().is_empty() {
json!({})
@@ -302,8 +316,10 @@ impl McpToolSession {
};
// B2: a write to a GitHub branch waits for its pre-push card before any card or rule
// 28k: a push the gate holds shows "Blocked before push" on its step; the bot
- // gets the gate's own text
- let held = || crate::server::activity::refused(&caller.turn_id, name, super::PREPUSH_BLOCKED_STEP_DETAIL);
+ // gets the gate's own text. 28q: on its own step, never on another call of the tool
+ let held = || {
+ crate::server::activity::refused(&caller.turn_id, name, step_id, &arguments, super::PREPUSH_BLOCKED_STEP_DETAIL)
+ };
match self.ctx.approver.prepush_gate(&req).await {
Err(why) => {
held();
diff --git a/src/server/activity.rs b/src/server/activity.rs
index 840abdcf..46421735 100644
--- a/src/server/activity.rs
+++ b/src/server/activity.rs
@@ -231,11 +231,13 @@ pub fn approval_waiting(turn_id: &str, ticket: &str, tool_name: &str) {
}
/// kwnt refused a call to `tool_name` in turn `turn_id` on its own, before the engine heard (28k):
-/// that tool's next failed step shows `words` (as [`crate::mcp::PREPUSH_BLOCKED_STEP_DETAIL`]),
-/// not the text the bot was told. Nobody pressed Deny, so it never reads as the person's no.
-pub fn refused(turn_id: &str, tool_name: &str, words: &'static str) {
+/// that call's failed step shows `words` (as [`crate::mcp::PREPUSH_BLOCKED_STEP_DETAIL`]), not the
+/// text the bot was told. Nobody pressed Deny, so it never reads as the person's no. `call` is the
+/// engine's id for the call when kwnt was told it, and `arguments` its arguments, so the words land
+/// on that call's step and not on another call of the same tool (28q).
+pub fn refused(turn_id: &str, tool_name: &str, call: Option<&str>, arguments: &Value, words: &'static str) {
if let Some(turn) = TurnActivity::find(turn_id) {
- turn.with_log(|log| log.refused(tool_name, words));
+ turn.with_log(|log| log.refused_call(tool_name, call, Some(arguments), words));
}
}
@@ -569,8 +571,10 @@ mod tests {
let tag = TurnTag { turn_id: "turn-prepush-held".into(), kwant_id: "k".into(), context_id: "c".into(), thread_id: None };
let turn = TurnActivity::start(tx, tag);
turn.observe(&RuntimeEvent::ToolCallPending { id: "1".into(), name: "Bash".into(), args: json!({"command": "git push origin lin-x"}) });
- refused("turn-prepush-held", "Bash", crate::mcp::PREPUSH_BLOCKED_STEP_DETAIL);
- refused("no-such-turn", "Bash", crate::mcp::PREPUSH_BLOCKED_STEP_DETAIL);
+ // 28q: keyed to the held call's own id and arguments
+ let push = json!({"command": "git push origin lin-x"});
+ refused("turn-prepush-held", "Bash", Some("1"), &push, crate::mcp::PREPUSH_BLOCKED_STEP_DETAIL);
+ refused("no-such-turn", "Bash", None, &push, crate::mcp::PREPUSH_BLOCKED_STEP_DETAIL);
turn.observe(&RuntimeEvent::ToolCallCompleted {
id: "1".into(),
result: json!({"status": "error", "error": "kwant checks one branch at a time before a push: push the branch by name."}),
diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rs
index b86fd41e..424da07f 100644
--- a/src/server/mcp_runtime.rs
+++ b/src/server/mcp_runtime.rs
@@ -572,7 +572,9 @@ impl BrokerApprover {
self.broker.allow_for_session(&req.kwant_id, &self.conversation, &req.tool_name).await;
ApprovalOutcome::Allowed
}
- // 27b: only the person's own no is remembered, not a dropped card
+ // 27b: only the person's own no is remembered, not a dropped card. A card that was
+ // withdrawn or whose channel dropped (28k) runs nothing either, but it wasn't the
+ // person's no, so its step settled `stopped` above
Ok(Ok(ApprovalDecision::Deny)) => {
self.broker.declined.record(&req.kwant_id, &self.conversation, &families, &ticket);
ApprovalOutcome::Denied
@@ -1537,8 +1539,11 @@ pub async fn permission_endpoint(
None => Ok(Default::default()),
},
};
- // 28k: the gate's refusal is its own text to the bot, and "Blocked before push" on the step
- let held = || super::activity::refused(&session.turn_id, tool_name, mcp::PREPUSH_BLOCKED_STEP_DETAIL);
+ // 28k: the gate's refusal is its own text to the bot, and "Blocked before push" on the step.
+ // 28q: keyed to this call's own tool-use id (the id claude puts on the step), so a
+ // neighbouring call of the same tool that failed on its own keeps its own reason
+ let call = args["tool_use_id"].as_str();
+ let held = || super::activity::refused(&session.turn_id, tool_name, call, &args["input"], mcp::PREPUSH_BLOCKED_STEP_DETAIL);
let decision = match prepush {
Err(why) => {
held();
@@ -1629,6 +1634,12 @@ pub async fn gateway_grok_endpoint(
gateway_rpc(&state, &headers, msg, GatewayNaming::Grok).await
}
+/// The engine's own id for a gateway `tools/call` (28q): Claude Code sends its tool-use id, which
+/// its activity step carries, as `_meta["claudecode/toolUseId"]`. `None` when the engine sends none.
+fn engine_call_id(msg: &Value) -> Option<&str> {
+ msg["params"]["_meta"]["claudecode/toolUseId"].as_str().map(str::trim).filter(|id| !id.is_empty())
+}
+
async fn gateway_rpc(
state: &AppState,
headers: &HeaderMap,
@@ -1665,6 +1676,7 @@ async fn gateway_rpc(
};
let arguments = msg["params"].get("arguments").cloned().unwrap_or_else(|| json!({}));
let call_id = format!("gw_{}", uuid::Uuid::new_v4().simple());
+ let step_id = engine_call_id(&msg);
let Some(tools) = session.tool_session().await else {
return StatusCode::UNAUTHORIZED.into_response();
};
@@ -1675,7 +1687,7 @@ async fn gateway_rpc(
// Dropping the call withdraws its card (or stops the forwarded call) when the turn ends
let (caller, raw_arguments) = (session.caller(), arguments.to_string());
let outcome = tokio::select! {
- outcome = tools.call(&caller, &call_id, &tool_name, &raw_arguments) => outcome,
+ outcome = tools.call_step(&caller, &call_id, step_id, &tool_name, &raw_arguments) => outcome,
_ = session.ended.cancelled() => {
let (server, tool) = mcp::split_tool_name(&tool_name).unwrap_or(("", name));
session.ctx.record(cancelled_record(&call_id, &tool_name, server, tool, &arguments));
@@ -1729,6 +1741,23 @@ mod expired_tests {
}
}
+#[cfg(test)]
+mod engine_call_id_tests {
+ use super::*;
+
+ /// 28q: the gateway keys a held push's step note to Claude Code's tool-use id, which it sends
+ /// on `tools/call` as `_meta["claudecode/toolUseId"]`; an engine that sends none gives `None`.
+ #[test]
+ fn the_gateway_reads_the_engines_own_call_id() {
+ let call = |meta: Value| json!({"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "github__push", "arguments": {}, "_meta": meta}});
+ assert_eq!(engine_call_id(&call(json!({"claudecode/toolUseId": "toolu_01AbC"}))), Some("toolu_01AbC"));
+ assert_eq!(engine_call_id(&call(json!({"progressToken": 1}))), None);
+ assert_eq!(engine_call_id(&call(json!({"claudecode/toolUseId": " "}))), None);
+ assert_eq!(engine_call_id(&call(json!({"claudecode/toolUseId": 7}))), None);
+ assert_eq!(engine_call_id(&json!({"method": "tools/call", "params": {"name": "github__push"}})), None);
+ }
+}
+
/// 27b: after the person declines a card, a call of the same family in that chat is refused
/// without a card until they write there again.
#[cfg(test)]