Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
fix: stop a chat's delegates with it, and rename orx mcp-gate to `o…
…rx mcp`

The user's Stop now stops the chat's delegates too, as an agent's
`cancel` already did; otherwise their answers woke the chat the user had
just stopped. A `send` retry is keyed by the calling chat and request
alone, so it still matches after a restart, and a message cited from
another project opens there.

`orx mcp-gate` stopped being only Claude's approval gate once every
harness spawned it for the orchestration tools. `mcp-gate` stays a hidden
alias: an `orx up` running from before an update still writes configs
that launch it from the updated binary.

Assisted-by: claude-opus-5.5
  • Loading branch information
small-angel committed Nov 4, 2026
commit 5bc0015a285e8284da853c07745f97a95e555ff2
8 changes: 4 additions & 4 deletions arc/agents.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ depends on the agent:
- Agents that ask their client (Codex's app server, OpenCode's server, ACP)
hold the request on the live connection until the user answers.
- Claude Code in headless mode cannot prompt. For approvals mid-turn, orx
makes the `approve` tool of its own MCP server, `orx mcp-gate`, Claude's
makes the `approve` tool of its own MCP server, `orx mcp`, Claude's
permission tool. It forwards each decision to the owning dashboard over
loopback and blocks until the user answers. The dashboard accepts it only with the per-chat
token the child was spawned with, a new token for each respawn, because the
Expand Down Expand Up @@ -174,7 +174,7 @@ forever.
## Sub-agents and new chats

Every agent whose harness takes an MCP server gets orx's own, `orx
mcp-gate`. It speaks stdio, the one transport every harness accepts (ACP
mcp`. It speaks stdio, the one transport every harness accepts (ACP
requires it), and relays to the owning dashboard, which knows the calling
chat by a token derived from a key that lives only in that dashboard's
process. Through it an agent delegates. It names a versioned model, and orx
Expand All @@ -187,8 +187,8 @@ on a canonical id derived from each spelling.
same worktree, unless it asks for a worktree of its own and stands as an
ordinary chat. It starts with only the task it was given, runs with a
permission mode no broader than its delegator's, and records who delegated to
it, which is how its depth is counted. Stopping a delegate stops every delegate
below it. An agent can also start a chat it does not hear from: that chat is
it, which is how its depth is counted. Stopping a chat, by the user's Stop or
an agent's `cancel`, stops every delegate below it. An agent can also start a chat it does not hear from: that chat is
no delegate and stands as the user's, as a delegate the user kept does. A
retry of the same request finds the chat the first attempt started, by an id
derived from the request.
Expand Down
2 changes: 1 addition & 1 deletion src/commands/mcp_gate.rs → src/commands/mcp.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! `orx mcp-gate` — the orx MCP server every agent harness is given.
//! `orx mcp` — the orx MCP server every agent harness is given.
//!
//! Hidden from `--help`: it's not a user command, it's the stdio MCP server a
//! harness spawns from orx's config — Claude via `--mcp-config`, Codex through
Expand Down
2 changes: 1 addition & 1 deletion src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ pub mod library;
pub mod login;
pub mod logout;
pub mod logs;
pub mod mcp_gate;
pub mod mcp;
pub mod metrics;
pub mod orgs;
pub mod paper;
Expand Down
12 changes: 8 additions & 4 deletions src/commands/up.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ pub async fn run(args: UpArgs) -> Result<()> {
restart: Arc::new(tokio::sync::Notify::new()),
trackio: Arc::default(),
};
// Plan-mode turns hand this port to the `orx mcp-gate` permission bridge.
// Plan-mode turns hand this port to the `orx mcp` permission bridge.
state.chat.set_up_port(actual_port);
state.chat.resume_persisted_queues();
{
Expand Down Expand Up @@ -847,11 +847,11 @@ fn router(state: AppState, remote_auth: Option<RemoteAuth>) -> Router {
axum::routing::delete(cancel_queued_chat).post(retry_queued_chat),
)
.route("/api/chat/sessions/{id}/respond", post(respond_chat))
// Internal: the `orx mcp-gate` permission bridge's long-poll (plan
// Internal: the `orx mcp` permission bridge's long-poll (plan
// mode). Token-authenticated in the handler; blocks until the surfaced
// card is answered.
.route("/api/internal/permissions", post(bridge_permission))
// Internal: the orchestration tools `orx mcp-gate` relays for an agent,
// Internal: the orchestration tools `orx mcp` relays for an agent,
// authenticated in the handler by that chat's agent token.
.route("/api/internal/mcp", post(agent_tools::agent_tools))
.route("/api/chat/attachments/{name}", get(chat_attachment))
Expand Down Expand Up @@ -8640,7 +8640,11 @@ async fn cited_chat_message(Path(cited): Path<String>) -> ApiResult {
.map(|session| session.harness);
let preview =
local::chat::delegation::preview(&local::chat::delegation::message_text(&message));
let project_id = store
.get_chat_session(&message.session_id)?
.map(|session| session.project_id);
Ok(Json(json!({
"projectId": project_id,
"sessionId": message.session_id,
"messageId": message.id,
"harness": harness,
Expand Down Expand Up @@ -9108,7 +9112,7 @@ async fn respond_chat(
Ok(Json(json!({ "ok": true })))
}

/// The `orx mcp-gate` bridge relaying one blocked tool call from a plan-mode
/// The `orx mcp` bridge relaying one blocked tool call from a plan-mode
/// claude turn. The response body is the permission decision verbatim
/// (`{"behavior":"allow",…}` / `{"behavior":"deny",…}`) — the bridge
/// stringifies it into the MCP tool result unchanged. Deliberately long-held:
Expand Down
28 changes: 7 additions & 21 deletions src/commands/up/agent_tools.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! The tools behind `orx mcp-gate`: the stdio MCP server every agent harness
//! The tools behind `orx mcp`: the stdio MCP server every agent harness
//! is given relays `tools/list` and `tools/call` here, authenticated as the
//! chat that harness runs.

Expand Down Expand Up @@ -247,12 +247,8 @@ async fn call(
status: None,
},
};
let client_turn_id = optional_text(args, "clientRequestId").map(|key| {
format!(
"ct_{}",
delegation::agent_token(&format!("{}:{key}", caller.id))
)
});
let client_turn_id = optional_text(args, "clientRequestId")
.map(|key| format!("ct_send_{}", delegation::request_key(&caller.id, key)));
let sent = state
.chat
.steer_message(
Expand Down Expand Up @@ -330,21 +326,11 @@ async fn call(
);
}
let mut stopped = Vec::new();
let mut links = vec![(caller.id.clone(), target.id.clone())];
while let Some((parent, id)) = links.pop() {
// The stop is no news to whoever stopped it; an answer that
// came before it still is.
if state.chat.interrupt(&id).await? {
stopped.push(id.clone());
news::mark_told(&store, &parent, &id)?;
}
links.extend(
store
.chat_delegates_of(&id)?
.into_iter()
.map(|child| (id.clone(), child)),
);
if state.chat.interrupt(&target.id).await? {
stopped.push(target.id.clone());
news::mark_told(&store, &caller.id, &target.id)?;
}
stopped.extend(state.chat.stop_delegates(&target.id).await?);
Ok(if stopped.is_empty() {
format!("Chat `{}` and its delegates were not running.", target.id)
} else {
Expand Down
24 changes: 14 additions & 10 deletions src/local/chat/delegation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ pub fn agent_token(session_id: &str) -> String {
.collect()
}

/// The orx MCP server one chat's agent spawns: this binary's `mcp-gate` over
/// The orx MCP server one chat's agent spawns: this binary's `mcp` over
/// stdio, with the env that names the chat to the `orx up` on `up_port`.
pub struct McpServer {
pub command: String,
Expand All @@ -52,7 +52,7 @@ pub fn mcp_server(session_id: &str, up_port: u16) -> Result<McpServer> {
.map_err(|e| anyhow!("cannot resolve the orx binary for its MCP server: {e}"))?;
Ok(McpServer {
command: command.to_string_lossy().into_owned(),
args: ["mcp-gate"],
args: ["mcp"],
env: [
("ORX_UP_PORT", up_port.to_string()),
("ORX_SESSION_ID", session_id.to_string()),
Expand Down Expand Up @@ -161,19 +161,23 @@ pub fn delegate_permission(parent: &StoredChatSession, harness_id: &str) -> Resu
/// is fixed, so a retry finds the chat the first attempt started.
pub fn started_chat_id(parent: &StoredChatSession, request: Option<&str>) -> String {
let uuid = match request {
Some(request) => {
let digest = Sha256::digest(format!("{}:{request}", parent.id).as_bytes());
uuid::Uuid::from_bytes(
digest[..16]
.try_into()
.expect("a SHA-256 digest has 16 bytes"),
)
}
Some(request) => request_key(&parent.id, request),
None => uuid::Uuid::new_v4(),
};
format!("chat_{uuid}")
}

/// What an agent's `clientRequestId` names: the same across retries and
/// restarts, and its own to each calling chat.
pub fn request_key(caller: &str, request: &str) -> uuid::Uuid {
let digest = Sha256::digest(format!("{caller}:{request}").as_bytes());
uuid::Uuid::from_bytes(
digest[..16]
.try_into()
.expect("a SHA-256 digest has 16 bytes"),
)
}

pub fn delegate_session(
id: String,
parent: &StoredChatSession,
Expand Down
31 changes: 27 additions & 4 deletions src/local/chat/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2369,7 +2369,7 @@ mod initial_message_tests {

// --- permission bridge ---------------------------------------------------------

/// The decision returned to the `orx mcp-gate` permission bridge for one
/// The decision returned to the `orx mcp` permission bridge for one
/// blocked tool call. Serialized verbatim into Claude Code's
/// permission-prompt-tool contract (the bridge stringifies it into the MCP
/// tool result), so the wire shape is exactly
Expand Down Expand Up @@ -2397,7 +2397,7 @@ impl PermissionDecision {
}

/// One outstanding bridge request: the oneshot unblocks the long-poll handler
/// in `request_permission` (and thereby the `orx mcp-gate` HTTP call and the
/// in `request_permission` (and thereby the `orx mcp` HTTP call and the
/// claude turn behind it).
struct PendingPermission {
session_id: String,
Expand Down Expand Up @@ -3544,7 +3544,7 @@ impl ChatHost {
}

/// Record the port `orx up` bound (once, at startup) so plan-mode turns can
/// hand it to the `orx mcp-gate` bridge.
/// hand it to the `orx mcp` bridge.
pub fn set_up_port(&self, port: u16) {
let _ = self.up_port.set(port);
self.opencode.set_up_port(port);
Expand Down Expand Up @@ -3809,7 +3809,7 @@ impl ChatHost {

/// Whether a bridge approval card of this session is still awaiting the
/// user. The claude turn watchdog consults this: a child held on the
/// mcp-gate long-poll is silently blocked *by design* (user think-time is
/// `orx mcp` long-poll is silently blocked *by design* (user think-time is
/// unbounded), so the no-output timeout must not kill it.
pub fn has_pending_permission(&self, session_id: &str) -> bool {
self.pending_permissions
Expand Down Expand Up @@ -6432,6 +6432,25 @@ impl ChatHost {
/// consumers use it to distinguish a stopped turn from a silent one.
/// Internal interrupts (plan-approval resume, session/project delete) stay
/// markerless on purpose.
/// Stop `id`'s delegates and every delegate below them, returning those
/// that were running. A stop is no news to the chat that delegated; an
/// answer that came before it still is.
pub async fn stop_delegates(self: &Arc<Self>, id: &str) -> Result<Vec<String>> {
let store = Store::open()?;
let mut stopped = Vec::new();
let mut parents = vec![id.to_string()];
while let Some(parent) = parents.pop() {
for child in store.chat_delegates_of(&parent)? {
if self.interrupt(&child).await? {
news::mark_told(&store, &parent, &child)?;
stopped.push(child.clone());
}
parents.push(child);
}
}
Ok(stopped)
}

pub async fn interrupt_by_user(self: &Arc<Self>, session_id: &str) -> Result<()> {
// Stamped before the abort: a fast resend can claim the freed slot and
// persist its user message before this runs, and a later timestamp
Expand All @@ -6444,6 +6463,10 @@ impl ChatHost {
let durable_clear = self.clear_queue_inner(session_id, true);
let interrupted = self.interrupt(session_id).await;
self.release_queue_cancellation_if_idle(session_id);
// Best-effort like the marker below: this chat's turn is stopped either way.
if let Err(error) = self.stop_delegates(session_id).await {
eprintln!("orx up: delegates of {session_id} not stopped: {error}");
}
if !interrupted? {
return durable_clear;
}
Expand Down
4 changes: 2 additions & 2 deletions src/local/claude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ impl TurnSlot {
}

/// What the resident child was spawned with. Any field that can only be applied
/// at launch (permission mode, effort, the mcp-gate bridge) forces a respawn
/// at launch (permission mode, effort, the `orx mcp` bridge) forces a respawn
/// when it changes; `model` is the exception — it retunes live via `set_model`,
/// so it is updated in place on a successful control request.
#[derive(Debug, Clone, PartialEq, Eq)]
Expand Down Expand Up @@ -211,7 +211,7 @@ pub fn classify_line(line: &str) -> ClaudeLine {
ClaudeLine::ControlResponse { request_id, result }
}
// A control_request FROM the child (e.g. a permission prompt) rides the
// mcp-gate bridge over HTTP, not this stream — we never answer it here.
// `orx mcp` bridge over HTTP, not this stream — we never answer it here.
Some("control_request") | None => ClaudeLine::Junk,
// Everything else is a stream-json output object: assistant/user/system/
// result. The turn loop discriminates on `type`.
Expand Down
10 changes: 5 additions & 5 deletions src/local/harness/claude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
//! `--permission-mode` from the session's setting (`auto`/`bypassPermissions` — see
//! `options`). AskUserQuestion / ExitPlanMode surface as interactive cards: the
//! turn ends on them and the user's answer resumes the session — except in plan
//! mode, where the mcp-gate bridge holds both open mid-turn and the answer
//! mode, where the `orx mcp` bridge holds both open mid-turn and the answer
//! continues the same turn.
//!
//! Detection: `claude auth status --json` is the readiness source of truth.
Expand Down Expand Up @@ -1127,7 +1127,7 @@ pub(crate) fn uses_permission_bridge(mode: Option<PermissionMode>) -> bool {
const PLAN_SETTINGS_REL: &str = ".openresearch/agent/claude-plan-settings.json";

/// Directory (relative to the worktree) of the MCP configs wiring the
/// `orx mcp-gate` bridge, one per chat: chats sharing a worktree spawn at once,
/// `orx mcp` bridge, one per chat: chats sharing a worktree spawn at once,
/// and each config names its own chat. Same git-excluded agent dir.
const MCP_CONFIG_DIR_REL: &str = ".openresearch/agent";

Expand Down Expand Up @@ -1180,7 +1180,7 @@ pub(crate) fn write_settings(repo: &std::path::Path, plan: bool) -> Result<PathB
}

/// Write the chat's `--mcp-config` file and return its path: alphaXiv always,
/// and with `gate` the `orx mcp-gate` bridge (this same binary), whose env
/// and with `gate` the `orx mcp` bridge (this same binary), whose env
/// block carries the `orx up` port, the session id, and a fresh per-child
/// token minted at spawn — everything the resident bridge needs to relay
/// requests back to the running server for the child's whole life.
Expand All @@ -1199,7 +1199,7 @@ pub(crate) fn write_mcp_config(
config["mcpServers"]["orx"] = serde_json::json!({
"type": "stdio",
"command": orx,
"args": ["mcp-gate"],
"args": ["mcp"],
// Orchestration tools are few and needed unprompted, so they
// skip tool search.
"alwaysLoad": true,
Expand Down Expand Up @@ -1467,7 +1467,7 @@ fn observe_turn_boundary(event: &Value, text: &str, saw_user_echo: &mut bool) ->
/// the fixture tests.
#[derive(Default)]
struct TurnState {
/// Whether this child was spawned with the mcp-gate bridge active. With the
/// Whether this child was spawned with the `orx mcp` bridge active. With the
/// bridge on, ExitPlanMode / AskUserQuestion come from the bridge (held,
/// mid-turn-answerable), so their `tool_use` renders nothing.
bridge_active: bool,
Expand Down
2 changes: 1 addition & 1 deletion src/local/harness/plan_gate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ const GIT_WHOLE_VERB_READS: &[&str] = &[
/// the call otherwise ("User has approved exiting plan mode", nobody asked —
/// verified on claude 2.1.197), letting the model exit plan mode and edit
/// files without the user's say. `ask` routes it to the permission prompt tool
/// (the `orx mcp-gate` bridge), which surfaces the plan card and blocks until
/// (the `orx mcp` bridge), which surfaces the plan card and blocks until
/// the user answers; without a bridge configured, `ask` in headless denies —
/// still strictly better than self-approval.
pub fn decide(payload: &Value) -> Option<Value> {
Expand Down
Loading
Loading