diff --git a/SKILL.md b/SKILL.md index fc2d0c976..20e3c31ce 100644 --- a/SKILL.md +++ b/SKILL.md @@ -98,7 +98,6 @@ group below has a module (`orx skill `) with the full flags and rules. | `orx exp status/run/cancel/wait/wake ` | Inspect, run, cancel, wait on, or register a wake-up for a local experiment node. | | `orx exp move/archive/unarchive/delete ` | Re-parent, hide, restore, or permanently delete experiment nodes; see `orx-experiment-tree`. | | `orx exp desc [--set "" \| --stdin]` | Read or overwrite the experiment's description. | -| `orx agent spawn "" [--title ""] [--stdin] [--no-wake]` | Delegate an independent task to a helper session; see `orx-agent-delegation`. | To **read or edit** a node's code—including diffing what a run changed—use plain Git in the local session worktree. See the `orx-git` module. @@ -136,7 +135,7 @@ list, with one-line descriptions, is printed at the end of `orx skill` output): - **orx-compute** — launch and monitor runs; after resolving the backend, read its bundled reference. - **orx-instances** — create persistent standalone machines for manual work. - **orx-git** — read, edit, and diff a node's code with plain git. -- **orx-agent-delegation** — delegate independent work to helper sessions safely. +- **orx-agent-delegation** — delegate to other models and chats with orx's MCP tools. - **orx-logs** — retrieve persisted run output for progress, debugging, or measurements. - **orx-results** — interpret, compare, and summarize measured experiment outcomes. - **orx-reports** — write durable research outputs into the project's artifacts directory. diff --git a/SYSTEM_PROMPT.md b/SYSTEM_PROMPT.md index 4add51eea..00967d282 100644 --- a/SYSTEM_PROMPT.md +++ b/SYSTEM_PROMPT.md @@ -50,6 +50,23 @@ normal repository tools for code and file inspection. Use this project id `orx` is internal and should stay under the hood; do not mention it in user-facing responses. +## Delegating work + +When your tools include the `orx` MCP server, use it for sub-agent work instead +of any built-in sub-agent tool. These are tools, not `orx` CLI commands. +`models` lists the versioned models you can delegate to, with their effort +levels. `delegate` runs a standalone task on one of them and returns at once. +You are subscribed to each delegate: its answer, or a question it asks, arrives +here as a new message. Continue other work, call `wait` when you cannot go on +without the answer, or end your turn. `answer` a delegate's question, or ask the +user. `subscribe` lets you hear from any other chat the same way, and `send`, +`status`, `read` and `cancel` message, check on, read and stop other chats. +Each message from the user starts with its ref, such as `msg_3fa9c1d2`; a ref +in a task or message passes that message on word for word, with its +attachments. In a reply to the user, a ref or a chat id shows as a link to it. +A message that starts with `[orx]` comes from orx or another chat's agent, not +the user. + ## Python environments - Follow user instructions and established dependency tooling; inspect project diff --git a/agent-skills/orx-agent-delegation/SKILL.md b/agent-skills/orx-agent-delegation/SKILL.md index 3a128ef25..c40cea440 100644 --- a/agent-skills/orx-agent-delegation/SKILL.md +++ b/agent-skills/orx-agent-delegation/SKILL.md @@ -1,34 +1,37 @@ --- name: orx-agent-delegation -description: "Create independent project chats with `orx agent spawn` using the user's New Chat settings. Covers standalone opening messages, project selection, worktrees, and compute authorization. Use before creating another chat." +description: "Delegate tasks to other models and chats with the orx MCP server's `delegate`, `wait`, `subscribe` and `answer` tools. Covers standalone briefs, worktrees, compute authorization, nesting and questions. Use before delegating or opening another chat." --- -# Create an independent chat +# Delegate to another chat -`orx agent spawn` creates an ordinary chat and submits its opening message, -just like New Chat in OpenResearch. It uses the user's saved agent, model, -reasoning, speed, permissions, and autonomy settings. It does not inherit this -conversation or this chat's settings. +The orx MCP server's tools are the only way to start another chat. `models` +lists the versioned models you can name. `delegate` starts a chat on one and +returns at once; you are subscribed to it, so its answer, or a question it +asks, arrives here as a new message. Call `wait` only when you cannot continue +without the answer, and end your turn otherwise. -```sh -orx agent spawn "" -orx agent spawn --title "" --stdin -orx agent spawn "" --project -``` +A delegate starts with nothing but its task. Write a standalone brief: the +project, experiment or commit, constraints, permitted compute, expected output, +and definition of done. Explicitly forbid compute launches when none are +authorized. To pass the user's own words or a screenshot, cite the message's +ref (`msg_3fa9c1d2`) in the task instead of retyping it. -The project defaults to this OpenResearch chat's project; pass `--project` when -that context is unavailable. The command requires the running local server. -`--harness`, `--model`, and `--no-wake` are no longer supported. - -The created chat is independent and appears in the sidebar without switching -the user's view. It has its own transcript and normal session worktree. Its -result will not be sent back here, and stopping this chat does not stop it. -Use the harness's native subagents for subordinate work that needs to report -back. Do not create a new chat as a substitute for a follow-up message. - -Include the relevant project, experiment or commit, constraints, permitted -compute, expected output, and definition of done in the opening message. Use -`--stdin` for longer messages. Explicitly forbid compute launches when none -are authorized. Changes stay in the new chat's worktree and never merge here -automatically. Do not assign a branch already checked out by another session -or edit a frozen experiment node. +- **Worktree.** By default a delegate works in this chat's worktree, so give + parallel delegates separate files. `worktree: "own"` gives it a fresh + worktree from the project's baseline that appears in the sidebar: commit + first and name the commit in the task when it should start from your work. + Its changes never merge here automatically. +- **Independent chats.** `notify: false` starts a chat that is not your + delegate: your side chat, or with `worktree: "own"` a chat of its own, for + work that should not report back. You do not hear from it unless you + `subscribe`, and you cannot `cancel` it. Do not open one as a substitute for + a follow-up message; `send` the chat you already have. +- **Nesting.** A delegate may delegate only when you allow it with + `canDelegate` or the user's setting does. Keep nesting shallow. +- **Questions.** `answer` a delegate's question when the brief already + decides it; otherwise ask the user. Approvals are the user's. +- **Effort.** Pass `effort` from `models` only when the task needs more or less + reasoning than the route's default. +- **Retries.** Give `delegate` and `send` a `clientRequestId` when you may + retry, so a retry does not start the work twice. diff --git a/arc/agents.md b/arc/agents.md index b9657af50..85702db21 100644 --- a/arc/agents.md +++ b/arc/agents.md @@ -99,9 +99,8 @@ to the user's native store, and orx copies recent history only for display. run, so the agent runs the same version as the dashboard. The environment names the chat and the owning dashboard's port (plus a token, on a persistent remote host). That - is how `orx exp run` records which chat launched a run, how an agent asks to - be woken when a run ends, and how `orx agent spawn` opens a new chat in the - project. + is how `orx exp run` records which chat launched a run and how an agent asks + to be woken when a run ends. - **alphaXiv tools.** Claude Code, Codex, OpenCode and ACP agents always get a stdio server, `orx alphaxiv-mcp`, named `alphaxiv`. If Codex already defines that name, orx disables it for the thread and uses `orx_alphaxiv`; @@ -133,9 +132,9 @@ 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 - registers a small MCP server, `orx mcp-gate`, as 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 + 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 endpoint grants permissions. - Plan mode puts a small automatic policy in front of the user: read-only @@ -177,9 +176,62 @@ forever. ## Sub-agents and new chats -An agent's own sub-agents (Claude's tasks, OpenCode's child sessions, -Antigravity's spawned conversations) appear as parts nested under the call -that started them, read from the agent's native records. An agent can also -open an independent chat in the same project with `orx agent spawn`, which -goes through the dashboard's API like a user's request and becomes an -ordinary chat. +Every agent whose harness takes an MCP server gets orx's own, `orx +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 +picks a route that can run it, unless the agent names one: the vendor's own +agent first, then flat-rate plans, direct APIs, and resellers last. The same +model is spelled differently by every agent and provider, so routes are joined +on a canonical id derived from each spelling. + +**A delegate is a side chat of the chat that started it,** working in the +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 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. + +**Any chat can subscribe to any other.** A subscription tells its subscriber +each finished turn of its target, and each question the target asks, as the +first message of the subscriber's next turn. Run wake-ups go through the same +delivery: a chat's news, from runs and chats alike, is never lost, never +duplicated, never interrupts a running turn, and arrives as one turn however +much of it is waiting, each piece kept in the transcript as its own message. A turn that ends while its own delegates are +still working is not an answer yet. An agent can collect the same news inside +its turn with `wait`, which marks it told. A delegator subscribes to its +delegates. Once the user writes in a delegate, its composer lets them keep it: +it stops reporting to the chat that started it and stands as that chat's side +chat, or on its own with its own worktree, and the delegator's later +`subscribe` or `wait` does not undo that. A side chat reports only when its +agent `send`s. Agents answer questions through orx; approvals stay with the user. + +**Agents write to each other in the open.** Everything orx or another chat's +agent writes into a chat (a task, a message, news) reaches its agent opening +with `[orx]`, so the agent can tell it from the user. The transcript records +it with its kind and sender and keeps what the sender wrote, refs included; +only the agent reads the refs expanded and the instructions around them. The +dashboard shows it as the sender's message, and a finished run by its outcome. + +**Messages travel by reference.** Each user message reaches its agent tagged +with a short ref from its id. A ref in a task or message expands to the cited +message, its chat and its attachments, so a delegate reads the user's own words +rather than a paraphrase. In the dashboard, a ref or chat id an agent writes is +a link to that message or chat. An agent can read any chat. It can message or answer +its own delegates, and any other chat whose permission mode orx can read and is +no broader than its own, and it can stop its own delegates. + +**Nesting is deliberate.** By default a delegate cannot delegate in turn. A delegation can let its delegate delegate in turn, a setting +changes the default, and every delegate is told how many levels down it is. + +Where orx's server is present, the harness's own sub-agent tools are off +(Claude's Agent and Task tools, Codex's multi-agent feature, OpenCode's task +tool), so sub-agent work goes through orx and can run any model. A delegate +on Claude Code also gets the prompt-cache lifetime Claude gives its own +sub-agents, not the main conversation's longer one. Harnesses without the +server keep their native sub-agents, which appear as parts nested under the +call that started them, read from the agent's native records. diff --git a/arc/experiments.md b/arc/experiments.md index bd6f8cef8..b50a4809e 100644 --- a/arc/experiments.md +++ b/arc/experiments.md @@ -112,7 +112,8 @@ When a run ends, the chats that asked to be woken for it get a wake-up turn with the outcome. Asking is explicit (`orx exp wake`), and the wake-ups are rows in the store with a claim and a TTL, so a crash between claiming and delivering never loses or duplicates one, and a wake-up never interrupts a -turn already running or a message the user queued. +turn already running or a message the user queued. They are delivered with a +chat's other news, so runs and delegates that finish together wake it once. Remote run directories are removed later by a background pass, in bounded batches per host, which keeps the source archives that live runs still need. diff --git a/arc/storage.md b/arc/storage.md index e39a7e5a8..6c22a125a 100644 --- a/arc/storage.md +++ b/arc/storage.md @@ -44,9 +44,10 @@ and a terminal `orx` on the same machine would open different databases. A SQLite database in WAL mode is orx's truth for everything that is not code: projects, the experiment records, runs and their backend descriptors, chat -sessions, messages and turn leases, wake-up registrations, UI and workspace -state. Many short-lived processes open it concurrently, each with a busy -timeout; WAL lets readers proceed while one writer commits. +sessions, messages and turn leases, wake-up registrations, chat delegations +and subscriptions, UI and workspace state. Many short-lived processes open it +concurrently, each with a busy timeout; WAL lets readers proceed while one +writer commits. **The schema only grows.** Every open of the store applies the whole schema: tables are created if missing, and each added column is an `ALTER TABLE ADD diff --git a/src/commands/agent.rs b/src/commands/agent.rs deleted file mode 100644 index 862d7afd8..000000000 --- a/src/commands/agent.rs +++ /dev/null @@ -1,133 +0,0 @@ -//! Create an ordinary project chat through the resident server's chat API. - -use std::io::Read; - -use crate::error::{anyhow, Result}; -use crate::local::chat; -use crate::AgentCommand; - -pub async fn run(args: crate::AgentArgs) -> Result<()> { - match args.command { - AgentCommand::Spawn { - task, - stdin, - title, - project, - } => { - let prompt = task_text(task, stdin)?; - let port = chat::trusted_up_port()?.ok_or_else(|| anyhow!( - "Connect to the running OpenResearch server with ORX_LOCAL_SESSION=1 and ORX_UP_PORT (and ORX_UP_AUTH_TOKEN when required)." - ))?; - let project = match project { - Some(project) => project, - None => { - let session_id = chat::launching_chat_session().ok_or_else(|| { - anyhow!( - "Pass --project when there is no current OpenResearch chat." - ) - })?; - let session = crate::commands::up::chat_request_via_up( - port, - reqwest::Method::GET, - &format!("/api/chat/sessions/{session_id}"), - &serde_json::json!({}), - ) - .await?; - session - .pointer("/session/projectId") - .and_then(serde_json::Value::as_str) - .ok_or_else(|| { - anyhow!("The current chat is unavailable. Pass --project .") - })? - .to_string() - } - }; - spawn(port, &project, &prompt, title.as_deref()).await - } - } -} - -fn task_text(task: Option, stdin: bool) -> Result { - let text = if stdin { - if task.is_some() { - return Err(anyhow!( - "Pass the message as an argument or --stdin, not both." - )); - } - let mut buf = String::new(); - std::io::stdin().read_to_string(&mut buf)?; - buf - } else { - task.unwrap_or_default() - }; - let text = text.trim(); - if text.is_empty() { - return Err(anyhow!( - "Provide an opening message: orx agent spawn \"\"." - )); - } - Ok(text.to_string()) -} - -async fn spawn(port: u16, project: &str, prompt: &str, title: Option<&str>) -> Result<()> { - use crate::commands::up::chat_request_via_up; - use reqwest::Method; - use serde_json::json; - - let created = chat_request_via_up( - port, - Method::POST, - "/api/chat/sessions", - &json!({"projectId": project}), - ) - .await?; - let id = created - .pointer("/session/id") - .and_then(serde_json::Value::as_str) - .ok_or_else(|| anyhow!("OpenResearch returned no created chat ID."))?; - println!("Created chat {id}."); - println!("Open it in OpenResearch: http://127.0.0.1:{port}/projects/{project}/tasks/{id}"); - if let Some(title) = title.map(str::trim).filter(|title| !title.is_empty()) { - chat_request_via_up( - port, - Method::PATCH, - &format!("/api/chat/sessions/{id}"), - &json!({"title": title}), - ) - .await - .map_err(|error| { - anyhow!( - "Chat {id} was created, but naming it failed: {error}. Open that chat to continue." - ) - })?; - } - let client_turn_id = format!("ct_{}", uuid::Uuid::new_v4()); - let result = chat_request_via_up(port, Method::POST, &format!("/api/chat/sessions/{id}/message"), - &json!({"text": prompt, "clientTurnId": client_turn_id})).await - .map_err(|error| anyhow!("Chat {id} was created, but opening-message acceptance could not be confirmed: {error}. Check that chat before retrying."))?; - if result - .pointer("/turn/queued") - .and_then(serde_json::Value::as_bool) - == Some(true) - { - println!("Opening message accepted and queued."); - } else { - println!("Opening message accepted."); - } - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::task_text; - #[test] - fn opening_message_requires_one_nonempty_source() { - assert_eq!( - task_text(Some(" Inspect the code ".into()), false).unwrap(), - "Inspect the code" - ); - assert!(task_text(None, false).is_err()); - assert!(task_text(Some(" ".into()), false).is_err()); - assert!(task_text(Some("argument".into()), true).is_err()); - } -} diff --git a/src/commands/mcp_gate.rs b/src/commands/mcp.rs similarity index 72% rename from src/commands/mcp_gate.rs rename to src/commands/mcp.rs index c2403914f..f71ca67b0 100644 --- a/src/commands/mcp_gate.rs +++ b/src/commands/mcp.rs @@ -1,24 +1,31 @@ -//! `orx mcp-gate` — the plan-mode permission bridge. +//! `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 -//! Claude Code spawns via `--mcp-config` and consults via -//! `--permission-prompt-tool mcp__orx__approve` (see -//! `local::harness::claude::write_mcp_config`). Every permission decision the -//! CLI would have shown as an interactive prompt arrives here as a -//! `tools/call`; we relay it to the running `orx up` over localhost HTTP — -//! which auto-decides by policy or surfaces a card and *blocks until the user -//! answers* — and hand the decision back. That held call is what turns -//! headless plan mode into desktop-style mid-turn approvals. +//! 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 +//! its thread config, OpenCode through its config file, ACP agents through +//! `session/new`. Stdio is the one transport every harness supports (ACP +//! requires it), so each relays here and this process forwards over localhost +//! HTTP to the `orx up` that spawned the agent. +//! +//! Two tool families ride it. `approve` is Claude's permission prompt tool +//! (`--permission-prompt-tool mcp__orx__approve`): each decision Claude would +//! have shown interactively arrives as a `tools/call`, and `orx up` either +//! decides by policy or surfaces a card and *blocks until the user answers*. +//! The orchestration tools (delegate and friends) are listed and served by +//! `orx up` itself, so this process only relays them. //! //! The wire is MCP's stdio transport: newline-delimited JSON-RPC 2.0, the same //! framing as `local::codex` (this end is the server). Only three methods //! matter — `initialize`, `tools/list`, `tools/call` — so it's hand-rolled //! rather than pulling in an MCP crate. //! -//! Failure posture: never hang Claude and never allow by accident. Any -//! transport or orx-side error answers `deny` with the reason; unknown methods -//! get a JSON-RPC error; a missing env contract exits nonzero (Claude reports -//! the server as failed and plan mode degrades to its default gating). +//! Failure posture: never hang the agent and never allow by accident. Any +//! transport or orx-side error answers `deny` (or a tool error) with the +//! reason; unknown methods get a JSON-RPC error; a missing env contract exits +//! nonzero (the harness reports the server as failed). + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; use serde_json::{json, Value}; use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; @@ -26,12 +33,14 @@ use tokio::sync::mpsc; use crate::error::{anyhow, Result}; -/// Env contract injected by `write_mcp_config` (values ride the MCP server's -/// `env` block, so they survive however Claude spawns us). +/// Env contract the harness adapters put in the server's `env` block, so the +/// values survive however the harness spawns us. `token` is Claude's per-child +/// permission token; `agent_token` names the chat for orchestration tools. struct GateEnv { up_port: u16, session_id: String, - token: String, + token: Option, + agent_token: Option, } impl GateEnv { @@ -42,14 +51,24 @@ impl GateEnv { .ok_or_else(|| anyhow!("ORX_UP_PORT missing or invalid"))?; let session_id = std::env::var("ORX_SESSION_ID").map_err(|_| anyhow!("ORX_SESSION_ID missing"))?; - let token = - std::env::var("ORX_GATE_TOKEN").map_err(|_| anyhow!("ORX_GATE_TOKEN missing"))?; + let var = |name: &str| std::env::var(name).ok().filter(|value| !value.is_empty()); Ok(Self { up_port, session_id, - token, + token: var("ORX_GATE_TOKEN"), + agent_token: var("ORX_AGENT_TOKEN"), }) } + + fn agent_request(&self, method: &str, params: Value) -> Option { + let token = self.agent_token.as_ref()?; + Some(json!({ + "sessionId": self.session_id, + "token": token, + "method": method, + "params": params, + })) + } } pub async fn run() -> Result<()> { @@ -60,6 +79,7 @@ pub async fn run() -> Result<()> { .connect_timeout(std::time::Duration::from_secs(3)) .build() .map_err(|e| anyhow!("http client: {e}"))?; + let tools_url = format!("http://127.0.0.1:{}/api/internal/mcp", env.up_port); // Single writer task: tool calls are handled concurrently (Claude may // check several tools at once), so responses funnel through one channel @@ -77,6 +97,9 @@ pub async fn run() -> Result<()> { } }); + // A call the agent cancels, such as an interrupted `wait`, stops here too, + // so `orx up` does not go on to claim news nobody will read. + let calls: Arc>> = Arc::default(); let stdin = BufReader::new(tokio::io::stdin()); let mut lines = stdin.lines(); while let Some(line) = lines.next_line().await.unwrap_or(None) { @@ -102,18 +125,24 @@ pub async fn run() -> Result<()> { )); } Some("tools/list") => { - let _ = out_tx.send(reply( - id, - json!({ - "tools": [{ - "name": "approve", - "description": "Ask the orx user to approve a tool call", - "inputSchema": { "type": "object", "additionalProperties": true }, - }] - }), - )); + let mut tools = Vec::new(); + if env.token.is_some() { + tools.push(json!({ + "name": "approve", + "description": "Ask the orx user to approve a tool call", + "inputSchema": { "type": "object", "additionalProperties": true }, + })); + } + // An unreachable `orx up` leaves only `approve`: the agent + // keeps working without orchestration rather than failing. + if let Some(body) = env.agent_request("tools/list", json!({})) { + if let Ok(listed) = relay(&http, &tools_url, body).await { + tools.extend(listed["tools"].as_array().cloned().unwrap_or_default()); + } + } + let _ = out_tx.send(reply(id, json!({ "tools": tools }))); } - Some("tools/call") => { + Some("tools/call") if msg.pointer("/params/name") == Some(&json!("approve")) => { // Handled concurrently: a held approval must not block the next // permission check (Claude can run tools in parallel). let args = msg @@ -145,6 +174,39 @@ pub async fn run() -> Result<()> { )); }); } + Some("tools/call") => { + let params = msg.get("params").cloned().unwrap_or_else(|| json!({})); + let body = env.agent_request("tools/call", params); + let http = http.clone(); + let url = tools_url.clone(); + let out = out_tx.clone(); + let key = id.as_ref().map(Value::to_string); + let running = calls.clone(); + let finished = key.clone(); + let call = tokio::spawn(async move { + let result = match body { + Some(body) => relay(&http, &url, body).await, + None => Err(anyhow!("orx tools are unavailable in this session")), + }; + let result = result.unwrap_or_else(|e| { + json!({ "content": [{ "type": "text", "text": e.to_string() }], "isError": true }) + }); + if let Some(key) = &finished { + running.lock().unwrap().remove(key); + } + let _ = out.send(reply(id, result)); + }); + if let Some(key) = key { + calls.lock().unwrap().insert(key, call.abort_handle()); + } + } + Some("notifications/cancelled") => { + if let Some(key) = msg.pointer("/params/requestId").map(Value::to_string) { + if let Some(call) = calls.lock().unwrap().remove(&key) { + call.abort(); + } + } + } // Notifications (no id) are fire-and-forget; anything else with an // id gets a proper method-not-found so the client never stalls. _ => { @@ -168,8 +230,8 @@ fn reply(id: Option, result: Value) -> Value { json!({ "jsonrpc": "2.0", "id": id.unwrap_or(Value::Null), "result": result }) } -/// POST the permission request to `orx up` and return its decision JSON. -/// The response body is the decision verbatim (`{"behavior": ...}`). +/// POST one request to `orx up` and return its JSON body; an error status +/// carries the server's `error` text. async fn relay(http: &reqwest::Client, url: &str, body: Value) -> Result { let resp = http .post(url) @@ -177,10 +239,13 @@ async fn relay(http: &reqwest::Client, url: &str, body: Value) -> Result .send() .await .map_err(|e| anyhow!("{e}"))?; - if !resp.status().is_success() { - return Err(anyhow!("orx up answered {}", resp.status())); + let status = resp.status(); + let body = resp.json::().await.map_err(|e| anyhow!("{e}"))?; + if !status.is_success() { + let reason = body["error"].as_str().unwrap_or("no reason given"); + return Err(anyhow!("orx up answered {status}: {reason}")); } - resp.json::().await.map_err(|e| anyhow!("{e}")) + Ok(body) } pub async fn run_antigravity() -> Result<()> { @@ -306,6 +371,7 @@ async fn antigravity_decision(input: &str) -> Result { .pointer("/toolCall/args") .ok_or_else(|| anyhow!("missing tool arguments"))?; let env = GateEnv::from_env()?; + let token = env.token.ok_or_else(|| anyhow!("ORX_GATE_TOKEN missing"))?; if workspace_read(name, args, &payload) { return Ok(json!({"decision": "allow"})); } @@ -316,7 +382,7 @@ async fn antigravity_decision(input: &str) -> Result { let decision = relay( &http, &format!("http://127.0.0.1:{}/api/internal/permissions", env.up_port), - json!({"sessionId":env.session_id,"token":env.token,"toolName":tool,"toolInput":input}), + json!({"sessionId":env.session_id,"token":token,"toolName":tool,"toolInput":input}), ) .await?; Ok(match decision.get("behavior").and_then(Value::as_str) { diff --git a/src/commands/mod.rs b/src/commands/mod.rs index d26a2bc3b..c1c7dec42 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -15,7 +15,6 @@ //! return `Err(anyhow!(...))` (clap already enforces required positionals, so //! most of those usage guards are unnecessary in the Rust port). -pub mod agent; pub mod alphaxiv_mcp; pub mod app; pub mod compute; @@ -33,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; diff --git a/src/commands/up.rs b/src/commands/up.rs index 9e2c8d855..324408e26 100644 --- a/src/commands/up.rs +++ b/src/commands/up.rs @@ -48,6 +48,7 @@ use crate::updates; use crate::workspace_state::{GlobalWorkspaceState, WorkspaceState}; use crate::{browser, UpArgs}; +mod agent_tools; pub(crate) mod compute_settings; mod harness_setup; use compute_settings::*; @@ -128,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(); { @@ -809,6 +810,7 @@ fn router(state: AppState, remote_auth: Option) -> Router { .patch(update_chat_session), ) .route("/api/chat/sessions/{id}/messages", get(chat_messages)) + .route("/api/chat/messages/{cited}", get(cited_chat_message)) .route( "/api/chat/sessions/{id}/submissions/{client_id}", get(chat_submission), @@ -845,10 +847,13 @@ fn router(state: AppState, remote_auth: Option) -> 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` 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)) .route("/api/agent/status", get(agent_status)) .fallback(spa) @@ -881,7 +886,7 @@ async fn require_remote_auth( ) .into_response(); } - if path == "/api/internal/permissions" { + if path == "/api/internal/permissions" || path == "/api/internal/mcp" { return next.run(request).await; } let provided = request @@ -938,7 +943,7 @@ fn remote_route_forbidden(path: &str) -> bool { fn is_remote_callback_route(method: &Method, path: &str) -> bool { if method == Method::GET { - // `orx agent spawn`'s install preflight (read-only). + // Older `orx agent spawn` clients' install preflight (read-only). return path .strip_prefix("/api/harnesses/") .and_then(|path| path.strip_suffix("/snapshot")) @@ -2480,22 +2485,6 @@ pub(crate) async fn submit_run_via_up( }) } -pub(crate) async fn chat_request_via_up( - port: u16, - method: reqwest::Method, - path: &str, - body: &Value, -) -> Result { - let response = authenticate_up_request( - local_client()?.request(method, format!("http://127.0.0.1:{port}{path}")), - ) - .json(body) - .send() - .await - .map_err(|error| anyhow!("Could not reach the trusted OpenResearch server: {error}"))?; - decode_local_response(response, "submit the chat request").await -} - pub(crate) async fn cancel_run_via_up(port: u16, run_id: &str) -> Result<()> { let response = authenticate_up_request( local_client()? @@ -6021,6 +6010,7 @@ struct SetUiStateReq { preferred_agent: Option, workspace: Option, preferred_autonomy: Option, + nested_delegation: Option, } #[derive(Deserialize)] @@ -6076,6 +6066,9 @@ async fn set_ui_state(Json(req): Json) -> ApiResult { if let Some(autonomy) = req.preferred_autonomy { store.set_preferred_autonomy(autonomy)?; } + if let Some(allowed) = req.nested_delegation { + store.set_nested_delegation(allowed)?; + } if let Some(workspace) = req.workspace { store.set_global_workspace_state(&workspace)?; } @@ -8048,7 +8041,7 @@ struct SessionsQuery { } fn sidebar_session_json(store: &Store, session: &StoredChatSession, busy: bool) -> Result { - let mut value = local::chat::session_json(session, busy); + let mut value = local::chat::session_json_with(Some(store), session, busy); value["awaitingInput"] = json!(store.chat_session_awaiting_input(&session.id, busy)?); Ok(value) } @@ -8450,6 +8443,8 @@ struct UpdateChatSessionReq { #[serde(default, deserialize_with = "present_nullable_string")] goal: Option>, autonomy: Option, + /// `false` keeps a delegate for the user: see `release_delegate`. + notify_parent: Option, } #[derive(serde::Deserialize)] @@ -8511,7 +8506,9 @@ async fn set_chat_configuration( .get(&id, &saved.launch, &cwd) .await .map_err(bad_request)?; - match client.restore(native_id, &cwd).await { + let mcp_servers = local::harness::acp::orx_mcp_servers(&id, state.chat.up_port()) + .map_err(bad_request)?; + match client.restore(native_id, &cwd, mcp_servers).await { Ok(configuration) => store.set_acp_configuration(&id, &configuration)?, Err(error) => { state.chat.acp.stop(&id).await; @@ -8587,6 +8584,11 @@ async fn update_chat_session( .set_autonomy(&id, autonomy) .await? .ok_or_else(|| not_found("chat session"))? + } else if req.notify_parent == Some(false) { + let session = local::chat::delegation::release_delegate(&Store::open()?, &id)? + .ok_or_else(|| not_found("chat session"))?; + state.chat.emit_session(Some(session.clone())).await; + session } else { return Err(bad_request("nothing to update")); }; @@ -8616,6 +8618,40 @@ async fn chat_subagent(Path(id): Path, Query(query): Query) -> ApiResult { + let store = Store::open()?; + let message = local::chat::delegation::cited_message(&store, &cited)? + .ok_or_else(|| not_found("message"))?; + let source = local::chat::stored_to_wire(&message) + .parts + .into_iter() + .find_map(|part| part.orx); + // An agent wrote it: this chat's own, or another chat's for the user. + let agent_chat = match &source { + Some(source) => source.from.clone().filter(|from| from.starts_with("chat_")), + None => (message.role == "assistant").then(|| message.session_id.clone()), + }; + let harness = agent_chat + .map(|id| store.get_chat_session(&id)) + .transpose()? + .flatten() + .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, + "preview": preview, + }))) +} + async fn chat_messages(State(state): State, Path(id): Path) -> ApiResult { // Messages first: these are two connections, so a turn writing between them // can only leave the leaf *ahead* of the list, which the client falls back on @@ -8782,6 +8818,7 @@ async fn send_chat_message( req.images, annotations, req.client_turn_id, + None, ) .await .map_err(|error| { @@ -8809,6 +8846,7 @@ async fn send_chat_message( req.images, annotations, req.client_turn_id, + None, ) .await .map_err(|error| { @@ -9067,13 +9105,14 @@ async fn respond_chat( .into_iter() .filter(|annotation| !annotation.text.trim().is_empty()) .collect(), + from: None, }) .await .map_err(bad_request)?; 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: @@ -9468,6 +9507,7 @@ mod tests { tour_completed: true, workspace: None, preferred_autonomy: Some(Autonomy::Copilot), + nested_delegation: false, preferred_agent: Some(StoredAgentSelection { harness: "codex".into(), model: Some("custom-model".into()), @@ -9498,6 +9538,7 @@ mod tests { workspace: None, preferred_autonomy: None, preferred_agent: None, + nested_delegation: false, }; let catalog = json!({"harnesses": [{"id":"claude-code", "agentReady":true, "models":[{"id":"opus"}], "options":{"defaultPermissionMode":"plan", "reasoningLevels":[{"id":"default"}]}}]}); @@ -9743,6 +9784,7 @@ mod tests { preferred_agent: None, workspace: Some(invalid), preferred_autonomy: None, + nested_delegation: None, })) .await; assert_eq!(result.err().unwrap().0, StatusCode::BAD_REQUEST); diff --git a/src/commands/up/agent_tools.rs b/src/commands/up/agent_tools.rs new file mode 100644 index 000000000..33accca89 --- /dev/null +++ b/src/commands/up/agent_tools.rs @@ -0,0 +1,669 @@ +//! 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. + +use axum::extract::State; +use axum::http::StatusCode; +use axum::Json; +use serde::Deserialize; +use serde_json::{json, Value}; + +use super::{harnesses_payload, reject_if_moving, ApiError, ApiResult, AppState, HarnessQuery}; +use crate::error::{anyhow, bail, Result}; +use crate::local::chat::{ + delegation, news, OrxDisplay, OrxKind, OrxSource, PromptAnswer, TurnOverrides, + ORX_MESSAGE_PREFIX, +}; +use crate::local::model_routes; +use crate::store::{Store, StoredChatSession}; + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +pub(super) struct AgentToolRequest { + session_id: String, + token: String, + method: String, + #[serde(default)] + params: Value, +} + +pub(super) async fn agent_tools( + State(state): State, + Json(request): Json, +) -> ApiResult { + if delegation::agent_token(&request.session_id) != request.token { + return Err(ApiError( + StatusCode::UNAUTHORIZED, + "unknown agent token".into(), + )); + } + let caller = Store::open()? + .get_chat_session(&request.session_id)? + .ok_or_else(|| ApiError(StatusCode::UNAUTHORIZED, "unknown agent token".into()))?; + match request.method.as_str() { + "tools/list" => Ok(Json(json!({ "tools": tools() }))), + "tools/call" => { + let name = request + .params + .get("name") + .and_then(Value::as_str) + .unwrap_or(""); + let args = request + .params + .get("arguments") + .cloned() + .unwrap_or_else(|| json!({})); + reject_if_moving(&state)?; + let (text, is_error) = match call(&state, &caller, name, &args).await { + Ok(text) => (text, false), + Err(error) => (error.to_string(), true), + }; + Ok(Json(json!({ + "content": [{ "type": "text", "text": text }], + "isError": is_error, + }))) + } + other => Err(ApiError( + StatusCode::BAD_REQUEST, + format!("unknown method {other}"), + )), + } +} + +fn tools() -> Value { + let chat_id = json!({ "type": "string", "description": "A chat's id, such as `chat_…`." }); + let chat_ids = json!({ "type": "array", "items": { "type": "string" }, "description": "Chat ids, such as `chat_…`." }); + let request_id = json!({ "type": "string", "description": "Optional key you keep across retries of this call: a retry with the same key returns what the first call did instead of doing it again." }); + json!([ + { + "name": "models", + "description": "List the versioned models you can delegate to. Each line is a model, the routes that can run it in the order orx prefers, and the effort levels its first route takes.", + "inputSchema": { "type": "object", "properties": {} }, + }, + { + "name": "delegate", + "description": "Start a new chat on another model to do a task. Name a versioned model from `models`; orx picks the route unless you name one. The delegate sees only `task`, so include everything it needs; a message's ref, such as `msg_3fa9c1d2`, in `task` passes that message on word for word, with its attachments. This returns at once and subscribes you to the delegate: its answer arrives in this chat as a new message when it finishes, or sooner through `wait`.", + "inputSchema": { + "type": "object", + "properties": { + "model": { "type": "string", "description": "A versioned model id from `models`, such as `deepseek-v4.1-flash`." }, + "task": { "type": "string", "description": "The complete, standalone instructions for the delegate." }, + "route": { "type": "string", "description": "Optional route from `models`, such as `openrouter`. Omit to use orx's order." }, + "effort": { "type": "string", "description": "Optional effort level from `models`. Omit for the route's default." }, + "title": { "type": "string", "description": "Optional short name for the delegate's chat." }, + "worktree": { "type": "string", "enum": ["shared", "own"], "description": "`shared` (the default) works in this chat's worktree. `own` gets a fresh worktree from the project's baseline and appears in the sidebar; commit first and name the commit in `task` if it should start from your work." }, + "notify": { "type": "boolean", "description": "Default true. False starts a chat that is not your delegate: a side chat of yours, or with `worktree: own` a chat of its own, which you do not hear from unless you `subscribe`." }, + "canDelegate": { "type": "boolean", "description": "Whether the delegate may start delegates of its own. Omit to use the user's setting, which is off unless they turned it on; set it only when the task needs nested delegates." }, + "clientRequestId": request_id, + }, + "required": ["model", "task"], + }, + }, + { + "name": "subscribe", + "description": "Hear from chats, not only the ones you delegated to: each time one finishes a turn or asks a question, it arrives in this chat as a new message, or through `wait`. Returns each chat's state now; news starts from there.", + "inputSchema": { "type": "object", "properties": { "chatIds": chat_ids }, "required": ["chatIds"] }, + }, + { + "name": "unsubscribe", + "description": "Stop hearing from chats.", + "inputSchema": { "type": "object", "properties": { "chatIds": chat_ids }, "required": ["chatIds"] }, + }, + { + "name": "wait", + "description": "Block until chats you subscribe to have news, and return it: a finished turn's answer, or a question to `answer`. Without `chatIds`, waits on every subscribed chat still working; naming a chat subscribes you to it. News that `wait` returns does not arrive again as a message. When you have nothing else to do, ending your turn works as well: the news arrives as a new message.", + "inputSchema": { + "type": "object", + "properties": { + "chatIds": chat_ids, + "until": { "type": "string", "enum": ["any", "all"], "description": "`any` (the default) returns at the first news; `all` waits for an answer from every chat. A question returns at once either way." }, + "timeoutSeconds": { "type": "integer", "description": "Default 600, at most 1800. Chats still working when it expires keep working." }, + }, + }, + }, + { + "name": "status", + "description": "Read whether a chat is working, waiting on a question or an approval, and the answer its latest turn ended with.", + "inputSchema": { "type": "object", "properties": { "chatId": chat_id }, "required": ["chatId"] }, + }, + { + "name": "read", + "description": "Read a chat's recent messages, each with the ref, such as `msg_3fa9c1d2`, that cites it.", + "inputSchema": { + "type": "object", + "properties": { "chatId": chat_id, "limit": { "type": "integer", "description": "How many messages, newest last. Default 10, at most 50." } }, + "required": ["chatId"], + }, + }, + { + "name": "send", + "description": "Send a message to a chat you delegated to, or to any chat whose permissions are no broader than yours, such as the chat that delegated to you or a side chat's parent. It runs as that chat's next turn, or joins its running turn when its agent accepts steering. Refs such as `msg_3fa9c1d2` in the message expand to the messages they cite.", + "inputSchema": { + "type": "object", + "properties": { "chatId": chat_id, "message": { "type": "string" }, "clientRequestId": request_id }, + "required": ["chatId", "message"], + }, + }, + { + "name": "answer", + "description": "Answer a question a chat asked: choose among its option labels, write an answer, or both.", + "inputSchema": { + "type": "object", + "properties": { + "chatId": chat_id, + "promptId": { "type": "string", "description": "The question's prompt id, from its news or `status`." }, + "choices": { "type": "array", "items": { "type": "string" }, "description": "Option labels, exactly as given." }, + "text": { "type": "string", "description": "A written answer, or a note beside the choices." }, + }, + "required": ["chatId", "promptId"], + }, + }, + { + "name": "cancel", + "description": "Stop a chat you delegated to, and every chat it delegated to in turn. Their queued messages stay queued.", + "inputSchema": { "type": "object", "properties": { "chatId": chat_id }, "required": ["chatId"] }, + }, + ]) +} + +/// How long `wait` blocks unless told otherwise. +const WAIT_DEFAULT_SECONDS: u64 = 600; + +async fn call( + state: &AppState, + caller: &StoredChatSession, + name: &str, + args: &Value, +) -> Result { + match name { + "models" => { + let models = model_routes::models(&catalog(state).await); + if models.is_empty() { + bail!("No agent is ready to run a delegate. The user can sign in to one in OpenResearch."); + } + Ok(model_routes::listing(&models)) + } + "delegate" => delegate(state, caller, args).await, + "subscribe" => { + let mut lines = Vec::new(); + for id in chat_ids(args)? { + let store = Store::open()?; + let target = chat(&store, &id)?; + if target.id == caller.id { + bail!("A chat cannot subscribe to itself."); + } + let told = store + .latest_chat_turn(&target.id)? + .filter(|turn| { + matches!(turn.state.as_str(), "completed" | "failed" | "interrupted") + }) + .map(|turn| turn.id); + store.subscribe_chat(&caller.id, &target.id, told.as_deref())?; + let working = state.chat.is_busy(&target.id).await; + lines.push(delegation::status(&store, &target, working, &caller.id)?); + } + Ok(format!("Subscribed.\n\n{}", lines.join("\n\n---\n\n"))) + } + "unsubscribe" => { + let store = Store::open()?; + let ids = chat_ids(args)?; + for id in &ids { + store.unsubscribe_chat(&caller.id, id)?; + } + Ok(format!("Unsubscribed from {}.", ids.join(", "))) + } + "wait" => wait(state, caller, args).await, + "status" => { + let store = Store::open()?; + let target = chat(&store, text(args, "chatId")?)?; + let working = state.chat.is_busy(&target.id).await; + delegation::status(&store, &target, working, &caller.id) + } + "read" => { + let store = Store::open()?; + let target = chat(&store, text(args, "chatId")?)?; + let limit = args + .get("limit") + .and_then(Value::as_u64) + .unwrap_or(10) + .clamp(1, 50); + delegation::transcript(&store, &target.id, limit as usize) + } + "send" => { + let store = Store::open()?; + let target = chat(&store, text(args, "chatId")?)?; + reachable(&store, caller, &target)?; + let written = text(args, "message")?; + let message = format!( + "{ORX_MESSAGE_PREFIX}Message from chat `{}`:\n\n{}", + caller.id, + delegation::expand_refs(&store, written)? + ); + let shown = OrxDisplay { + text: written.to_string(), + source: OrxSource { + kind: OrxKind::Message, + from: Some(caller.id.clone()), + status: None, + }, + }; + 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( + &target.id, + message, + TurnOverrides::default(), + Vec::new(), + Vec::new(), + client_turn_id, + Some(shown), + ) + .await?; + Ok(match sent { + None => format!("Sent into chat `{}`'s running turn.", target.id), + Some(result) if result.queued => { + format!("Queued for chat `{}`'s next turn.", target.id) + } + Some(_) => format!("Chat `{}` started a turn with your message.", target.id), + }) + } + "answer" => { + let store = Store::open()?; + let target = chat(&store, text(args, "chatId")?)?; + reachable(&store, caller, &target)?; + let prompt_id = text(args, "promptId")?; + let pending = delegation::pending_prompt(&store, &target.id)? + .filter(|pending| pending.id == prompt_id) + .ok_or_else(|| anyhow!("Chat `{}` has no open question `{prompt_id}`; call `status` for its current one.", target.id))?; + if pending.kind() != "question" { + bail!("Only the user can approve a step; `answer` answers questions."); + } + let choices: Vec = args + .get("choices") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(Value::as_str) + .map(str::to_string) + .collect(); + if let Some(unknown) = choices.iter().find(|choice| { + !pending + .prompt + .options + .iter() + .any(|option| &option.label == *choice) + }) { + bail!("`{unknown}` is not one of the question's options."); + } + let note = optional_text(args, "text").map(str::to_string); + if choices.is_empty() && note.is_none() { + bail!("Give `choices`, `text`, or both."); + } + state + .chat + .respond(PromptAnswer { + session_id: target.id.clone(), + prompt_id: prompt_id.to_string(), + approve: true, + resume_mode: None, + answers: choices, + note, + annotations: Vec::new(), + from: Some(caller.id.clone()), + }) + .await?; + Ok(format!("Answered chat `{}`; it continues.", target.id)) + } + "cancel" => { + let store = Store::open()?; + let target = chat(&store, text(args, "chatId")?)?; + if store.delegation(&target.id)?.parent.as_deref() != Some(caller.id.as_str()) { + bail!( + "Only the chat that delegated to `{}` can stop it.", + target.id + ); + } + let mut stopped = Vec::new(); + 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 { + format!( + "Stopped {}.", + stopped + .iter() + .map(|id| format!("`{id}`")) + .collect::>() + .join(", ") + ) + }) + } + other => bail!("Unknown tool `{other}`."), + } +} + +async fn delegate(state: &AppState, caller: &StoredChatSession, args: &Value) -> Result { + let store = Store::open()?; + let delegation = store.delegation(&caller.id)?; + if !delegation.may_delegate { + bail!("This chat cannot start delegates: the chat that delegated to it did not allow nesting. Do the work yourself, or `send` the chat that delegated to you."); + } + let request = optional_text(args, "clientRequestId"); + let id = delegation::started_chat_id(caller, request); + // A retry's first attempt succeeded once its task is in; until then the + // retry finishes starting the chat that attempt created. + if request.is_some() && store.latest_chat_turn(&id)?.is_some() { + return Ok(format!( + "Already started chat `{id}` for this clientRequestId." + )); + } + let notify = args.get("notify").and_then(Value::as_bool).unwrap_or(true); + let may_delegate = match args.get("canDelegate").and_then(Value::as_bool) { + Some(allowed) => allowed, + None => store.ui_state()?.nested_delegation, + }; + let own_worktree = match optional_text(args, "worktree") { + None | Some("shared") => false, + Some("own") => true, + Some(other) => bail!("`worktree` is `shared` or `own`, not `{other}`."), + }; + let written = text(args, "task")?; + let task = delegation::delegate_task( + &delegation::expand_refs(&store, written)?, + &caller.id, + notify.then_some((delegation.depth + 1, may_delegate)), + ); + let models = model_routes::models(&catalog(state).await); + let route = model_routes::resolve(&models, text(args, "model")?, optional_text(args, "route")) + .map_err(|e| anyhow!(e))?; + let effort = optional_text(args, "effort"); + if let Some(effort) = effort.filter(|effort| !route.efforts.iter().any(|e| e == effort)) { + bail!(if route.efforts.is_empty() { + format!( + "`{}` on {} takes no effort level; omit `effort`.", + route.model, route.name + ) + } else { + format!( + "`{effort}` is not an effort `{}` takes on {}: {}.", + route.model, + route.name, + route.efforts.join(", ") + ) + }); + } + let _admission = state + .project_lifecycle + .admit(&caller.project_id) + .ok_or_else(|| anyhow!("This project is being deleted."))?; + let permission = delegation::delegate_permission(caller, &route.harness)?; + let title = optional_text(args, "title").map(str::to_string); + let child = delegation::delegate_session( + id, + caller, + &route, + permission, + effort.map(str::to_string), + title, + own_worktree, + ); + let created = match store.create_chat_session(&child) { + Ok(()) => true, + Err(_) if request.is_some() && store.get_chat_session(&child.id)?.is_some() => false, + Err(error) => return Err(error), + }; + // A chat its starter does not hear from stands as the user's, like a + // delegate the user kept. + if notify { + if let Err(error) = store + .record_chat_delegate(&child.id, &caller.id, may_delegate) + .and_then(|()| store.subscribe_chat(&caller.id, &child.id, None)) + { + if created { + store.delete_chat_session(&child.id)?; + } + return Err(error); + } + } + state.chat.emit_session(Some(child.clone())).await; + let sent = state + .chat + .send_message( + &child.id, + task, + TurnOverrides::default(), + Vec::new(), + Vec::new(), + request.map(|_| format!("ct_{}", child.id)), + Some(OrxDisplay { + text: written.to_string(), + source: OrxSource { + kind: OrxKind::Task, + from: Some(caller.id.clone()), + status: None, + }, + }), + ) + .await; + if let Err(error) = sent { + // A delegate that never got its task would never answer. + if created { + let _ = state.chat.delete_session(&child.id).await; + } + return Err(error); + } + let effort = effort + .map(|effort| format!(" at {effort} effort")) + .unwrap_or_default(); + Ok(if notify { + format!( + "Delegated to chat `{}` running `{}` on {}{effort}. Its answer arrives here as a new message when it finishes, or sooner through `wait`.", + child.id, route.model, route.name + ) + } else { + format!( + "Started chat `{}` running `{}` on {}{effort}. It is not your delegate and you are not subscribed to it; `subscribe` to hear from it.", + child.id, route.model, route.name + ) + }) +} + +/// Blocks until the caller's subscriptions have news, then tells it here +/// instead of in a wake: the news is marked told as it is returned. +async fn wait(state: &AppState, caller: &StoredChatSession, args: &Value) -> Result { + let all = match optional_text(args, "until") { + None | Some("any") => false, + Some("all") => true, + Some(other) => bail!("`until` is `any` or `all`, not `{other}`."), + }; + let timeout = args + .get("timeoutSeconds") + .and_then(Value::as_u64) + .unwrap_or(WAIT_DEFAULT_SECONDS) + .clamp(1, delegation::WAIT_MAX_SECONDS); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(timeout); + let named = args + .get("chatIds") + .is_some() + .then(|| chat_ids(args)) + .transpose()?; + let mut waiting: Vec = { + let store = Store::open()?; + if let Some(ids) = &named { + for id in ids { + chat(&store, id)?; + if id == &caller.id { + bail!("A chat cannot wait on itself."); + } + store.subscribe_chat(&caller.id, id, None)?; + } + } + store + .list_chat_subscriptions(Some(&caller.id))? + .into_iter() + .filter(|sub| sub.outstanding && !sub.paused) + .map(|sub| sub.target_session_id) + .filter(|id| named.as_ref().is_none_or(|ids| ids.contains(id))) + .collect() + }; + if waiting.is_empty() { + return Ok("Nothing to wait for: every chat you subscribe to has told you its latest answer, or the user turned off its notifications.".into()); + } + let mut collected = Vec::new(); + let mut paused: Vec = Vec::new(); + let mut gone: Vec = Vec::new(); + loop { + let store = Store::open()?; + // A turn interrupted mid-wait reads nothing more; what it would have + // been told arrives as a new message instead. + if !state.chat.is_busy(&caller.id).await { + return Ok("This turn ended before any news arrived.".into()); + } + // Collected news is marked told only once returned, so a turn that + // ends first still gets it as a new message. + let mut asked = false; + for item in news::chat_news(&store, Some(&caller.id))? { + if !waiting.iter().any(|id| id == item.target()) + || (matches!(item, news::News::Answer(_)) + && state.chat.is_busy(item.target()).await) + { + continue; + } + asked |= matches!(item, news::News::Question { .. }); + if matches!(item, news::News::Answer(_)) { + waiting.retain(|id| id != item.target()); + } + collected.push(item); + } + // A target is done waiting on when the user stopped it telling this + // chat, another `wait` was told its news, or it is gone. + let subscriptions = store.list_chat_subscriptions(Some(&caller.id))?; + waiting.retain(|id| { + let Some(sub) = subscriptions + .iter() + .find(|sub| &sub.target_session_id == id) + else { + gone.push(id.clone()); + return false; + }; + if sub.paused { + paused.push(id.clone()); + } + sub.outstanding && !sub.paused + }); + let done = if all { + waiting.is_empty() + } else { + !collected.is_empty() + }; + if asked || done || waiting.is_empty() || std::time::Instant::now() >= deadline { + let mut told = Vec::new(); + for item in collected { + if let Some(token) = item.claim(&store)? { + item.settle(&store, &token, true)?; + told.push(item); + } + } + let mut text = if told.is_empty() { + format!("No news after {timeout} seconds.") + } else { + news::messages(&store, &told)? + .into_iter() + .map(|(text, _)| text) + .collect::>() + .join("\n\n---\n\n") + }; + let list = |ids: &[String]| { + ids.iter() + .map(|id| format!("`{id}`")) + .collect::>() + .join(", ") + }; + if !paused.is_empty() { + text.push_str(&format!( + "\n\nThe user turned off notifications from {}; read it with `status` when you need it.", + list(&paused) + )); + } + if !gone.is_empty() { + text.push_str(&format!( + "\n\nYou no longer subscribe to {}: it was deleted or unsubscribed.", + list(&gone) + )); + } + if !waiting.is_empty() { + text.push_str(&format!( + "\n\nStill working: {}. Wait again, or end your turn: their news arrives as new messages.", + list(&waiting) + )); + } + return Ok(text); + } + drop(store); + tokio::time::sleep(std::time::Duration::from_millis(500)).await; + } +} + +async fn catalog(state: &AppState) -> Value { + let query = HarnessQuery { + refresh: None, + retry: None, + harness: None, + }; + harnesses_payload(state, &query).await +} + +fn optional_text<'a>(args: &'a Value, key: &str) -> Option<&'a str> { + args.get(key) + .and_then(Value::as_str) + .map(str::trim) + .filter(|value| !value.is_empty()) +} + +fn text<'a>(args: &'a Value, key: &str) -> Result<&'a str> { + optional_text(args, key).ok_or_else(|| anyhow!("`{key}` is required.")) +} + +fn chat_ids(args: &Value) -> Result> { + let ids: Vec = args + .get("chatIds") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(Value::as_str) + .map(|id| id.trim().to_string()) + .filter(|id| !id.is_empty()) + .collect(); + if ids.is_empty() { + bail!("`chatIds` needs at least one chat id."); + } + Ok(ids) +} + +fn chat(store: &Store, id: &str) -> Result { + store + .get_chat_session(id)? + .ok_or_else(|| anyhow!("No chat `{id}` exists.")) +} + +/// Chats `caller` may change: those it is linked to by a delegation or a +/// side chat, and any other whose permissions are no broader than its own. +/// A chat may steer its own delegates, and any chat that can do no more +/// unasked than it can; a narrower chat steering a broader one would widen it. +fn reachable(store: &Store, caller: &StoredChatSession, target: &StoredChatSession) -> Result<()> { + let delegated = store.delegation(&target.id)?.parent.as_deref() == Some(caller.id.as_str()); + if delegated || delegation::within_reach(caller, target) { + Ok(()) + } else { + bail!( + "Chat `{}` may do more without asking than this chat, so only the user can steer it.", + target.id + ) + } +} diff --git a/src/local/acp/host.rs b/src/local/acp/host.rs index decf09147..058e7c8d9 100644 --- a/src/local/acp/host.rs +++ b/src/local/acp/host.rs @@ -217,7 +217,12 @@ impl Client { Ok(()) } - pub async fn restore(&self, native_id: &str, cwd: &Path) -> Result { + pub async fn restore( + &self, + native_id: &str, + cwd: &Path, + mcp_servers: Vec, + ) -> Result { use agent_client_protocol::schema::v1::{LoadSessionRequest, ResumeSessionRequest}; let capabilities = &self.initialized["agentCapabilities"]; let method = if capabilities["sessionCapabilities"]["resume"].is_object() { @@ -228,14 +233,13 @@ impl Client { bail!("The agent cannot restore this session. Send a message to continue with the saved transcript"); }; self.set_native_id(native_id); - let servers = super::alphaxiv_mcp_servers()?; let params = if method == "session/resume" { serde_json::to_value( - ResumeSessionRequest::new(native_id.to_owned(), cwd).mcp_servers(servers), + ResumeSessionRequest::new(native_id.to_owned(), cwd).mcp_servers(mcp_servers), )? } else { serde_json::to_value( - LoadSessionRequest::new(native_id.to_owned(), cwd).mcp_servers(servers), + LoadSessionRequest::new(native_id.to_owned(), cwd).mcp_servers(mcp_servers), )? }; self.request(method, params).await @@ -817,7 +821,14 @@ mod tests { .await .unwrap(); let native_id = response["sessionId"].as_str().unwrap(); - client.restore(native_id, &cwd).await.unwrap(); + client + .restore( + native_id, + &cwd, + super::super::alphaxiv_mcp_servers().unwrap(), + ) + .await + .unwrap(); host.shutdown().await; } } diff --git a/src/local/agent_skills.rs b/src/local/agent_skills.rs index fccf40186..6b052f5f4 100644 --- a/src/local/agent_skills.rs +++ b/src/local/agent_skills.rs @@ -186,7 +186,7 @@ const S_GIT: AgentSkill = AgentSkill { }; const S_AGENT_DELEGATION: AgentSkill = AgentSkill { name: "orx-agent-delegation", - description: "Create independent project chats with `orx agent spawn` using the user's New Chat settings. Covers standalone opening messages, project selection, worktrees, and compute authorization. Use before creating another chat.", + description: "Delegate tasks to other models and chats with the orx MCP server's `delegate`, `wait`, `subscribe` and `answer` tools. Covers standalone briefs, worktrees, compute authorization, nesting and questions. Use before delegating or opening another chat.", content: AGENT_DELEGATION, resources: &[], }; diff --git a/src/local/chat/delegation.rs b/src/local/chat/delegation.rs new file mode 100644 index 000000000..c28ada4ba --- /dev/null +++ b/src/local/chat/delegation.rs @@ -0,0 +1,927 @@ +//! Delegated chats. An agent hands a task to another model through the orx +//! MCP server; the delegate runs as a side chat of the delegating chat, or in +//! a worktree of its own, and the delegator subscribes to it (see `news`). +//! Agents cite messages by ref and read each other's state through here. + +use serde_json::{json, Value}; +use sha2::{Digest as _, Sha256}; +use std::sync::OnceLock; + +use super::{ + attachments_dir, stored_to_wire, MessagePhase, OrxKind, OrxSource, WirePart, WirePrompt, + ORX_MESSAGE_PREFIX, +}; +use crate::error::{anyhow, Result}; +use crate::local::harness::{self, PermissionMode}; +use crate::local::model_routes::Route; +use crate::store::{now_ms, Store, StoredChatMessage, StoredChatSession}; + +/// A delegate's answer rides inline up to this size; `status` reads the rest. +const ANSWER_INLINE_BYTES: usize = 16 * 1024; + +/// The first line of a delegate's answer, as the dashboard previews it. +const ANSWER_PREVIEW_CHARS: usize = 200; + +/// The longest `wait`. Harnesses give the orx server a tool timeout past it, +/// so a wait ends on its own terms rather than the harness's. +pub const WAIT_MAX_SECONDS: u64 = 1800; +pub const TOOL_TIMEOUT_SECONDS: u64 = WAIT_MAX_SECONDS + 60; + +/// Proves which chat a call to the orx MCP server speaks for. Derived from a +/// key that lives only in this process, so a respawned agent keeps its token +/// and nothing needs revoking: a deleted chat's token names no chat. +pub fn agent_token(session_id: &str) -> String { + static KEY: OnceLock = OnceLock::new(); + let key = KEY.get_or_init(|| format!("{}{}", uuid::Uuid::new_v4(), uuid::Uuid::new_v4())); + Sha256::digest(format!("{key}:{session_id}").as_bytes()) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() +} + +/// 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, + pub args: [&'static str; 1], + pub env: [(&'static str, String); 3], +} + +pub fn mcp_server(session_id: &str, up_port: u16) -> Result { + let command = crate::paths::spawnable_exe() + .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"], + env: [ + ("ORX_UP_PORT", up_port.to_string()), + ("ORX_SESSION_ID", session_id.to_string()), + ("ORX_AGENT_TOKEN", agent_token(session_id)), + ], + }) +} + +/// Claude Code caches a delegate like a main conversation (1h on a +/// subscription, at 2× the 5m write price). It gets the lifetime a native +/// subagent would instead, unless the user pinned the main-conversation TTL. +pub fn delegate_prompt_cache_ttl() -> Option { + let var = |key: &str| { + crate::local::shell_env::var(key) + .map(|value| value.to_string_lossy().into_owned()) + .or_else(|| { + crate::config::list_synced_env() + .into_iter() + .find_map(|(name, value)| (name == key).then_some(value)) + }) + }; + if var("CLAUDE_CODE_PROMPT_CACHE_TTL").is_some() { + return None; + } + Some( + var("CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL").unwrap_or_else(|| { + let one_hour = var("ENABLE_PROMPT_CACHING_1H").is_some_and(|v| v == "1" || v == "true"); + if one_hour { "1h" } else { "5m" }.to_string() + }), + ) +} + +/// How much a chat may do unasked, from asking (0) to bypassing (3). Plan +/// asks. `None` for a harness without permission modes. +fn permission_rank(session: &StoredChatSession) -> Option { + let mode = + harness::effective_permission_id(&session.harness, session.permission_mode.as_deref()) + .and_then(|id| harness::permission_mode_for(&session.harness, &id))?; + Some(if session.plan_mode { + 0 + } else { + mode_rank(mode) + }) +} + +fn mode_rank(mode: PermissionMode) -> u8 { + match mode { + PermissionMode::Plan | PermissionMode::Ask => 0, + PermissionMode::AcceptEdits => 1, + PermissionMode::Auto => 2, + PermissionMode::Bypass => 3, + } +} + +/// Whether `caller` may message `target` without widening what it can do: a +/// target that may do more unasked than its caller, or whose modes orx cannot +/// read, is the user's to steer. +pub fn within_reach(caller: &StoredChatSession, target: &StoredChatSession) -> bool { + match (permission_rank(caller), permission_rank(target)) { + (Some(caller), Some(target)) => target <= caller, + _ => false, + } +} + +/// The broadest mode the delegate's harness offers that is no broader than +/// the delegator's. Plan narrows to asking: a delegate is sent to do its task. +/// A delegator whose modes orx cannot read gets a delegate that asks. +pub fn delegate_permission(parent: &StoredChatSession, harness_id: &str) -> Result> { + let ceiling = permission_rank(parent).unwrap_or(0); + let child = + harness::chat_harness(harness_id).ok_or_else(|| anyhow!("unknown agent {harness_id}"))?; + let choices = child.options().permission_modes; + if choices.is_empty() { + // Its own policy decides what it may do, which only a chat that may + // do anything can stand behind. + return if ceiling == mode_rank(PermissionMode::Bypass) { + Ok(None) + } else { + Err(anyhow!( + "{} has no permission modes orx can hold to this chat's; pick another `route`, or ask the user.", + child.name() + )) + }; + } + choices + .iter() + .filter_map(|choice| { + PermissionMode::from_id(&choice.id) + .filter(|mode| *mode != PermissionMode::Plan) + .map(|mode| (mode_rank(mode), choice.id.clone())) + }) + .filter(|(rank, _)| *rank <= ceiling) + .max_by_key(|(rank, _)| *rank) + .map(|(_, id)| Some(id)) + .ok_or_else(|| { + anyhow!( + "{} has no permission mode as narrow as this chat's", + child.name() + ) + }) +} + +/// A delegate's chat: a side chat of its delegator, unless it gets a +/// worktree of its own and stands as a chat in the sidebar. +/// The id of a chat an agent starts. Given the agent's `clientRequestId` it +/// 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) => 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, + route: &Route, + permission_mode: Option, + effort: Option, + title: Option, + own_worktree: bool, +) -> StoredChatSession { + let now = now_ms(); + StoredChatSession { + id, + project_id: parent.project_id.clone(), + harness: route.harness.clone(), + native_session_id: None, + title_source: title.is_some().then(|| "user".to_string()), + title, + model: Some(route.model.clone()), + service_tier: None, + permission_mode, + plan_mode: false, + plan_reset_pending: false, + reasoning_level: effort, + archived: false, + context_usage_json: None, + bootstrap_context: None, + goal: None, + autonomy: parent.autonomy.clone(), + active_leaf_id: None, + side_parent_session_id: (!own_worktree).then(|| parent.id.clone()), + side_parent_leaf_id: None, + created_at: now, + updated_at: now, + } +} + +/// What a message says to another agent: a user's text, or an assistant's +/// final-answer parts, else its trailing text. +pub fn message_text(message: &StoredChatMessage) -> String { + let parts = stored_to_wire(message).parts; + let text = |part: &WirePart| part.text.clone().filter(|_| part.kind == "text"); + let chosen: Vec = if message.role != "assistant" { + parts.iter().filter_map(text).collect() + } else { + let finals: Vec = parts + .iter() + .filter(|part| part.phase == Some(MessagePhase::FinalAnswer)) + .filter_map(text) + .collect(); + if finals.is_empty() { + let mut tail: Vec = parts + .iter() + .rev() + .take_while(|part| matches!(part.kind.as_str(), "text" | "reasoning")) + .filter_map(text) + .collect(); + tail.reverse(); + tail + } else { + finals + } + }; + chosen.join("\n\n").trim().to_string() +} + +/// The text a turn ended with. +pub fn answer(store: &Store, assistant_message_id: &str) -> Result { + Ok(store + .get_chat_message(assistant_message_id)? + .map(|message| message_text(&message)) + .unwrap_or_default()) +} + +/// How many hex digits of a message's random id its ref carries. +const REF_HEX: usize = 8; + +/// How an agent cites a message: the start of its id, like a short commit hash. +pub fn message_ref(message_id: &str) -> String { + let len = "msg_".len() + REF_HEX; + message_id.get(..len).unwrap_or(message_id).to_string() +} + +/// Replace each ref an agent wrote with the message it cites, quoted with its +/// chat and attachments, so the receiving agent reads the exact words. One that +/// cites no message stays as written. +pub fn expand_refs(store: &Store, text: &str) -> Result { + let mut expanded = String::with_capacity(text.len()); + let mut rest = text; + while let Some(start) = rest.find("msg_") { + let end = start + "msg_".len() + REF_HEX; + let cited = rest + .get(start..end) + .filter(|cited| is_ref(rest, start, cited)) + .map(|cited| cited_message(store, cited)) + .transpose()? + .flatten() + .map(|message| quote(&message)) + .transpose()?; + match cited { + Some(quote) => { + expanded.push_str(rest[..start].trim_end()); + expanded.push_str("e); + rest = rest[end..].trim_start(); + } + None => { + expanded.push_str(&rest[..start + 1]); + rest = &rest[start + 1..]; + } + } + } + expanded.push_str(rest); + Ok(expanded.trim().to_string()) +} + +/// Whether `cited`, found at `start` of `text`, is a whole ref rather than +/// part of a longer id or word. +fn is_ref(text: &str, start: usize, cited: &str) -> bool { + let word = |c: char| c.is_alphanumeric() || c == '_' || c == '-'; + let hex = &cited["msg_".len()..]; + hex.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) + && !text[..start].ends_with(word) + && !text[start + cited.len()..].starts_with(word) +} + +/// The one message a ref cites. +pub fn cited_message(store: &Store, cited: &str) -> Result> { + let Some(hex) = cited.strip_prefix("msg_") else { + return Ok(None); + }; + let ids = store.chat_message_ids_with_prefix(hex)?; + let [id] = ids.as_slice() else { + return Ok(None); + }; + store.get_chat_message(id) +} + +fn quote(message: &StoredChatMessage) -> Result { + let mut body = message_text(message); + let images: Vec = stored_to_wire(message) + .parts + .into_iter() + .filter(|part| part.kind == "image") + .filter_map(|part| part.text) + .collect(); + if !images.is_empty() { + let dir = attachments_dir()?; + body.push_str("\n\nAttached files, saved on disk at:"); + for name in images { + body.push_str(&format!("\n- {}", dir.join(name).display())); + } + } + let quoted: Vec = body + .lines() + .map(|line| { + if line.is_empty() { + ">".into() + } else { + format!("> {line}") + } + }) + .collect(); + Ok(format!( + "\n\n{}\n>\n> — {}, in chat `{}` ({})\n\n", + quoted.join("\n"), + author(message), + message.session_id, + message_ref(&message.id), + )) +} + +/// Who wrote a message, as an agent reads it. +pub fn author(message: &StoredChatMessage) -> String { + let source = stored_to_wire(message) + .parts + .into_iter() + .find_map(|part| part.orx); + match source { + Some(OrxSource { + from: Some(from), + kind: OrxKind::Task | OrxKind::Message | OrxKind::Answer | OrxKind::Question, + .. + }) => format!("chat `{from}`'s agent"), + Some(_) => "orx".into(), + None if message.role == "user" => "the user".into(), + None => "its agent".into(), + } +} + +/// A question or approval a chat's latest turn waits on. +#[derive(Clone)] +pub struct PendingPrompt { + pub id: String, + pub prompt: WirePrompt, +} + +impl PendingPrompt { + /// The card's kind. OpenCode asks to leave Plan with a question card, + /// which is the user's approval all the same. + pub fn kind(&self) -> &str { + if self.prompt.plan_exit { + "plan" + } else { + &self.prompt.kind + } + } +} + +/// Claude's approval bridge puts each card in an assistant message of its own +/// beside the turn's, so every message since the turn began is searched. +pub fn pending_prompt(store: &Store, session_id: &str) -> Result> { + let Some(turn) = store.latest_chat_turn(session_id)? else { + return Ok(None); + }; + let mut messages = store.list_chat_messages_since(session_id, turn.created_at)?; + messages + .retain(|message| message.role == "assistant" && message.id != turn.assistant_message_id); + messages.extend(store.get_chat_message(&turn.assistant_message_id)?); + Ok(messages.iter().rev().find_map(|message| { + stored_to_wire(message).parts.into_iter().find_map(|part| { + let prompt = part.prompt.filter(|prompt| !prompt.resolved)?; + Some(PendingPrompt { + id: part.id, + prompt, + }) + }) + })) +} + +pub(super) fn question_text(id: &str, model: &str, pending: &PendingPrompt) -> String { + format!( + "{ORX_MESSAGE_PREFIX}Chat `{id}` ({model}) asks a question and waits for an answer:\n\n{}\n\nAnswer with `answer` (chatId `{id}`, promptId `{}`), or ask the user.", + question_body(&pending.prompt), + pending.id + ) +} + +/// A question as its asker put it: header, question and options. +pub(super) fn question_body(prompt: &WirePrompt) -> String { + let mut lines = Vec::new(); + if let Some(header) = prompt.header.as_deref().filter(|h| !h.trim().is_empty()) { + lines.push(format!("**{}**\n", header.trim())); + } + if let Some(question) = prompt.question.as_deref().filter(|q| !q.trim().is_empty()) { + lines.push(format!("{}\n", question.trim())); + } + for option in &prompt.options { + match option.description.as_deref().filter(|d| !d.is_empty()) { + Some(description) => lines.push(format!("- {} — {description}", option.label)), + None => lines.push(format!("- {}", option.label)), + } + } + if prompt.multi_select { + lines.push("(More than one may be chosen.)".into()); + } + lines.join("\n").trim().to_string() +} + +/// One chat as `viewer` sees it: working, asking, or idle with its answer. +pub fn status( + store: &Store, + target: &StoredChatSession, + working: bool, + viewer: &str, +) -> Result { + let model = target.model.clone().unwrap_or_default(); + let pending = pending_prompt(store, &target.id)?; + let turn = store.latest_chat_turn(&target.id)?; + let mut text = match (&pending, working, &turn) { + (Some(pending), _, _) if pending.kind() == "question" => { + question_text(&target.id, &model, pending) + } + (Some(pending), _, _) => format!( + "Chat `{}` ({model}) waits for the user to approve {} in that chat.", + target.id, + pending.prompt.tool.as_deref().unwrap_or("a step") + ), + (None, true, _) => format!("Chat `{}` ({model}) is working.", target.id), + (None, false, Some(turn)) => { + let mut text = format!( + "Chat `{}` ({model}) is idle; its latest turn {}.", + target.id, turn.state + ); + if let Some(error) = turn + .error_message + .as_deref() + .filter(|_| turn.state != "completed") + { + text.push_str(&format!("\nError: {error}")); + } + text + } + (None, false, None) => format!("Chat `{}` ({model}) has not run a turn.", target.id), + }; + let paused = store + .list_chat_subscriptions(Some(viewer))? + .into_iter() + .any(|sub| sub.target_session_id == target.id && sub.paused); + if paused { + text.push_str( + "\nThe user turned off its notifications to you; read it with `status` when you need it.", + ); + } + if let Some(turn) = turn.filter(|_| !working) { + let answer = answer(store, &turn.assistant_message_id)?; + if !answer.is_empty() { + // In full: this is where a truncated answer points. + text.push_str(&format!( + "\n\nIts answer {}:\n\n{answer}", + message_ref(&turn.assistant_message_id), + )); + } + } + Ok(text) +} + +/// A chat's recent messages, oldest first, each with the ref that cites it. +pub fn transcript(store: &Store, session_id: &str, limit: usize) -> Result { + let messages = store.list_chat_messages(session_id)?; + let recent: Vec = messages + .iter() + .filter(|message| matches!(message.role.as_str(), "user" | "assistant")) + .rev() + .take(limit) + .map(|message| { + format!( + "{} {}: {}", + message_ref(&message.id), + author(message), + inline(&message_text(message)) + ) + }) + .collect::>() + .into_iter() + .rev() + .collect(); + Ok(if recent.is_empty() { + format!("Chat `{session_id}` has no messages yet.") + } else { + recent.join("\n\n") + }) +} + +/// A delegate's link to the chat that started it, for the dashboard: whether +/// it tells that chat when it finishes, where it stands, and its answer. +pub fn session_links(store: &Store, session: &StoredChatSession) -> Result { + let delegation = store.delegation(&session.id)?; + let Some(parent) = delegation.parent else { + return Ok(Value::Null); + }; + let notifies = store + .list_chat_subscriptions(Some(&parent))? + .into_iter() + .any(|sub| sub.target_session_id == session.id && !sub.paused); + let turn = store.latest_chat_turn(&session.id)?; + let answer = turn + .as_ref() + .filter(|turn| turn.state != "running") + .map(|turn| answer(store, &turn.assistant_message_id)) + .transpose()? + .filter(|answer| !answer.is_empty()) + .map(|answer| preview(&answer)); + let error = turn + .as_ref() + .filter(|turn| turn.state == "failed") + .and_then(|turn| turn.error_message.as_deref()) + .map(preview); + let asking = pending_prompt(store, &session.id)?.map(|pending| pending.kind().to_string()); + Ok(json!({ + "parentId": parent, + "depth": delegation.depth, + "notifies": notifies, + "state": turn.map(|turn| turn.state), + "answer": answer, + "error": error, + "asking": asking, + })) +} + +/// The user keeps a delegate for themselves: it stops telling the chat that +/// started it, and stands as that chat's side chat, or on its own when it has +/// its own worktree. The delegator's agent can still read it. +pub fn release_delegate(store: &Store, id: &str) -> Result> { + let Some(session) = store.get_chat_session(id)? else { + return Ok(None); + }; + let parent = store + .delegation(id)? + .parent + .ok_or_else(|| anyhow!("This chat is not a delegate."))?; + store.pause_chat_subscription(&parent, id)?; + store.remove_chat_delegate(id)?; + Ok(Some(session)) +} + +/// The first line of text, without the Markdown markers that lead it. +pub fn preview(text: &str) -> String { + let line = text + .lines() + .find(|line| !line.trim().is_empty()) + .unwrap_or(""); + let line = line + .trim_start_matches(['#', '>', '-', '*', '_', ' ']) + .trim_end_matches(['#', '*', '_', ' ']); + line.chars().take(ANSWER_PREVIEW_CHARS).collect() +} + +/// A started chat's first message: who sent it and, for a delegate, where it +/// sits, so nesting stays deliberate, then the task it was given. +pub fn delegate_task(task: &str, parent: &str, delegate: Option<(u32, bool)>) -> String { + let Some((depth, may_delegate)) = delegate else { + return format!( + "{ORX_MESSAGE_PREFIX}Task from chat `{parent}`, which does not hear from you unless it subscribes; `send` it what it must know.\n\n{task}" + ); + }; + let levels = if depth == 1 { + "1 level".to_string() + } else { + format!("{depth} levels") + }; + let nesting = if may_delegate { + "You may start delegates of your own with `delegate`, but keep nesting shallow unless the task calls for it." + } else { + "You cannot start delegates of your own; do the work yourself." + }; + format!( + "{ORX_MESSAGE_PREFIX}Task from chat `{parent}`. You are its delegate, {levels} below a chat the user started, and your final message is your answer to it. {nesting}\n\n{task}" + ) +} + +pub(super) fn inline(answer: &str) -> String { + if answer.len() <= ANSWER_INLINE_BYTES { + return answer.to_string(); + } + let mut end = ANSWER_INLINE_BYTES; + while !answer.is_char_boundary(end) { + end -= 1; + } + format!( + "{}\n\n[Truncated; call `status` for the full answer.]", + &answer[..end] + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::local::chat::news::{chat_news, News}; + use crate::store::StoredChatTurn; + + fn chat(harness: &str, permission_mode: &str) -> StoredChatSession { + let route = Route { + name: harness.into(), + harness: harness.into(), + model: "m".into(), + free: false, + efforts: Vec::new(), + }; + let root = StoredChatSession { + id: "chat_root".into(), + project_id: "proj".into(), + harness: harness.into(), + native_session_id: None, + title: None, + title_source: None, + model: None, + service_tier: None, + permission_mode: None, + plan_mode: false, + plan_reset_pending: false, + reasoning_level: None, + archived: false, + context_usage_json: None, + bootstrap_context: None, + goal: None, + autonomy: None, + active_leaf_id: None, + side_parent_session_id: None, + side_parent_leaf_id: None, + created_at: 0, + updated_at: 0, + }; + delegate_session( + "chat_child".into(), + &root, + &route, + Some(permission_mode.into()), + None, + None, + false, + ) + } + + #[test] + fn a_delegate_never_gets_a_broader_mode_than_its_delegator() { + for (parent, mode, child, expected) in [ + ("claude-code", "acceptEdits", "codex", "ask"), + ("claude-code", "auto", "codex", "approve-for-me"), + ("claude-code", "auto", "opencode", "auto-approve"), + ("claude-code", "plan", "codex", "ask"), + ("codex", "full-access", "claude-code", "bypassPermissions"), + ("opencode", "default", "claude-code", "manual"), + ] { + let got = delegate_permission(&chat(parent, mode), child).unwrap(); + assert_eq!(got.as_deref(), Some(expected), "{parent} {mode} → {child}"); + } + } + + #[test] + fn previews_are_the_first_line_without_markdown_markers() { + assert_eq!( + preview("\n# The History of the Abacus\n\nBody"), + "The History of the Abacus" + ); + assert_eq!( + preview("**The Slipstick: A History**"), + "The Slipstick: A History" + ); + assert_eq!(preview("> quoted"), "quoted"); + assert_eq!(preview(&"x".repeat(500)).len(), ANSWER_PREVIEW_CHARS); + } + + fn save_message(store: &Store, id: &str, session: &str, role: &str, parts: Vec) { + store + .upsert_chat_message(&StoredChatMessage { + id: id.into(), + session_id: session.into(), + role: role.into(), + parts_json: serde_json::to_string(&parts).unwrap(), + created_at: 0, + completed_at: None, + parent_id: None, + base_native_session_id: None, + result_native_session_id: None, + }) + .unwrap(); + } + + #[test] + fn a_ref_expands_to_the_cited_message_and_its_files() { + let dir = std::env::temp_dir().join(format!("orx-refs-{}", uuid::Uuid::new_v4())); + let store = Store::open_at(dir.clone()).unwrap(); + let id = "msg_3fa9c1d2-0000-4000-8000-000000000000"; + save_message( + &store, + id, + "chat_user", + "user", + vec![ + WirePart::text("p0", "Plot loss against width."), + WirePart::image("img0", "shot.png"), + ], + ); + assert_eq!(message_ref(id), "msg_3fa9c1d2"); + let expanded = expand_refs(&store, "Do this: msg_3fa9c1d2 Thanks.").unwrap(); + assert!(expanded.starts_with("Do this:\n\n> Plot loss against width.\n>\n> Attached files")); + assert!(expanded + .ends_with("shot.png\n>\n> — the user, in chat `chat_user` (msg_3fa9c1d2)\n\nThanks.")); + assert_eq!( + cited_message(&store, "msg_3fa9c1d2") + .unwrap() + .map(|message| message.session_id), + Some("chat_user".into()) + ); + for untouched in [ + "Colour it #3fa9c1d2.", + "msg_deadbeef", + "msg_3fa9c1d2b", + "msg_3fa9c1d2-0000-4000-8000-000000000000", + "my_msg_3fa9c1d2", + "msg_3fa9c1", + ] { + assert_eq!(expand_refs(&store, untouched).unwrap(), untouched); + } + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn a_released_delegate_stops_telling_its_parent_and_stands_alone() { + let dir = std::env::temp_dir().join(format!("orx-release-{}", uuid::Uuid::new_v4())); + let store = Store::open_at(dir.clone()).unwrap(); + let child = chat("opencode", "default"); + let mut parent = child.clone(); + parent.id = "chat_root".into(); + parent.side_parent_session_id = None; + store.create_chat_session(&parent).unwrap(); + store.create_chat_session(&child).unwrap(); + store + .record_chat_delegate(&child.id, &parent.id, false) + .unwrap(); + store.subscribe_chat(&parent.id, &child.id, None).unwrap(); + assert_eq!(session_links(&store, &child).unwrap()["notifies"], true); + + release_delegate(&store, &child.id).unwrap(); + assert_eq!(session_links(&store, &child).unwrap(), Value::Null); + let delegation = store.delegation(&child.id).unwrap(); + assert_eq!((delegation.depth, delegation.parent), (0, None)); + store.subscribe_chat(&parent.id, &child.id, None).unwrap(); + assert!(store.list_chat_subscriptions(Some(&parent.id)).unwrap()[0].paused); + assert!(release_delegate(&store, &child.id).is_err()); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn a_question_is_news_before_the_turn_that_asked_it() { + let dir = std::env::temp_dir().join(format!("orx-news-{}", uuid::Uuid::new_v4())); + let store = Store::open_at(dir.clone()).unwrap(); + let child = chat("opencode", "default"); + let mut parent = child.clone(); + parent.id = "chat_root".into(); + parent.side_parent_session_id = None; + store.create_chat_session(&parent).unwrap(); + store.create_chat_session(&child).unwrap(); + store + .record_chat_delegate(&child.id, &parent.id, false) + .unwrap(); + store.subscribe_chat(&parent.id, &child.id, None).unwrap(); + let turn = StoredChatTurn { + id: "turn_1".into(), + session_id: child.id.clone(), + user_message_id: None, + assistant_message_id: "msg_answer".into(), + client_turn_id: "ct_1".into(), + request_hash: "hash".into(), + prepared_input: "task".into(), + settings_json: "{}".into(), + state: "preparing".into(), + delivery_state: "not_sent".into(), + attempt_count: 0, + next_retry_at: None, + error_kind: None, + error_message: None, + recovery_action: None, + recovered_by_turn_id: None, + created_at: 1, + updated_at: 1, + }; + store.admit_chat_turn(None, &turn).unwrap(); + let question = |resolved: bool| { + let mut part = WirePart::text("q1", ""); + part.kind = "prompt".into(); + part.prompt = Some(WirePrompt { + kind: "question".into(), + question: Some("Which backend?".into()), + resolved, + ..Default::default() + }); + save_message( + &store, + "msg_answer", + &child.id, + "assistant", + vec![WirePart::text("t", "Before I start:"), part], + ); + }; + let kinds = || -> Vec<&'static str> { + chat_news(&store, Some(&parent.id)) + .unwrap() + .iter() + .map(|item| match item { + News::Answer(_) => "answer", + News::Question { .. } => "question", + News::Run(_) | News::Unmonitored(_) => "run", + }) + .collect() + }; + + question(false); + assert_eq!(kinds(), ["question"], "a held question is news mid-turn"); + store.complete_chat_turn("turn_1").unwrap(); + let asked = chat_news(&store, Some(&parent.id)).unwrap(); + assert_eq!( + asked.len(), + 1, + "the turn that ended asking is not its answer" + ); + let token = asked[0].claim(&store).unwrap().unwrap(); + asked[0].settle(&store, &token, true).unwrap(); + assert!(kinds().is_empty(), "a told question waits for its answer"); + question(true); + assert_eq!(kinds(), ["answer"]); + let mut card = WirePart::text("perm", ""); + card.kind = "prompt".into(); + card.prompt = Some(WirePrompt { + kind: "question".into(), + question: Some("Which dataset?".into()), + ..Default::default() + }); + store + .upsert_chat_message(&StoredChatMessage { + id: "msg_perm".into(), + session_id: child.id.clone(), + role: "assistant".into(), + parts_json: serde_json::to_string(&[card]).unwrap(), + created_at: 2, + completed_at: None, + parent_id: None, + base_native_session_id: None, + result_native_session_id: None, + }) + .unwrap(); + assert_eq!( + pending_prompt(&store, &child.id) + .unwrap() + .map(|pending| pending.id), + Some("perm".into()), + "Claude's bridge asks from a message of its own" + ); + let plan_exit = WirePrompt { + kind: "question".into(), + plan_exit: true, + ..Default::default() + }; + let pending = PendingPrompt { + id: "exit".into(), + prompt: plan_exit, + }; + assert_eq!( + pending.kind(), + "plan", + "leaving Plan is the user's to approve" + ); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn the_answer_is_the_final_text_or_else_the_trailing_text() { + let dir = std::env::temp_dir().join(format!("orx-delegate-{}", uuid::Uuid::new_v4())); + let store = Store::open_at(dir.clone()).unwrap(); + let save = |id: &str, parts: Vec| { + save_message(&store, id, "chat_child", "assistant", parts) + }; + let mut commentary = WirePart::text("a", "Looking around."); + commentary.phase = Some(MessagePhase::Commentary); + let mut done = WirePart::text("c", "The answer is 42."); + done.phase = Some(MessagePhase::FinalAnswer); + let tool = WirePart::tool("b", "Bash", "completed", None); + save("phased", vec![commentary.clone(), tool.clone(), done]); + save( + "plain", + vec![commentary, tool, WirePart::text("d", "Plain ending.")], + ); + assert_eq!(answer(&store, "phased").unwrap(), "The answer is 42."); + assert_eq!(answer(&store, "plain").unwrap(), "Plain ending."); + assert_eq!(answer(&store, "missing").unwrap(), ""); + let _ = std::fs::remove_dir_all(dir); + } +} diff --git a/src/local/chat/mod.rs b/src/local/chat/mod.rs index 85405e1b5..9cd750c22 100644 --- a/src/local/chat/mod.rs +++ b/src/local/chat/mod.rs @@ -8,6 +8,8 @@ //! normalized parts into the per-turn assistant message; every flush persists //! the message and broadcasts it as a `chat.message` SSE event. +pub mod delegation; +pub mod news; pub(crate) mod subagent; use std::collections::{HashMap, HashSet, VecDeque}; @@ -826,6 +828,9 @@ pub struct WirePrompt { pub note: Option, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub annotations: Vec, + /// The chat whose agent answered for the user, through `answer`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub answered_by: Option, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] @@ -859,6 +864,49 @@ pub struct WirePart { /// byte-identical on the wire — no migration. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub children: Vec, + /// Set on a message orx or another chat's agent wrote, which the + /// dashboard shows as theirs rather than the user's. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub orx: Option, +} + +/// What orx or another chat's agent wrote into a chat. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum OrxKind { + /// A delegate's task, from the chat that delegated it. + Task, + /// A `send` from another chat. + Message, + /// A subscribed chat finished its turn. + Answer, + /// A subscribed chat asks a question. + Question, + /// A run the chat asked to be woken for ended. + Run, + /// orx lost sight of runs the chat waits on. + Monitoring, +} + +/// Who wrote a message into a chat when the user did not. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct OrxSource { + pub kind: OrxKind, + /// The chat or run it comes from. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub from: Option, + /// A run's status, or the state a chat's turn ended in. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub status: Option, +} + +/// How the transcript shows a message orx or another chat's agent wrote. Its +/// agent reads more: the sender's ids, cited messages and what to do next. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct OrxDisplay { + pub text: String, + pub source: OrxSource, } impl WirePart { @@ -872,6 +920,7 @@ impl WirePart { prompt: None, phase: None, children: Vec::new(), + orx: None, } } @@ -931,6 +980,7 @@ impl WirePart { prompt: None, phase: None, children: Vec::new(), + orx: None, } } @@ -945,6 +995,7 @@ impl WirePart { prompt: Some(prompt), phase: None, children: Vec::new(), + orx: None, } } } @@ -988,6 +1039,10 @@ pub struct SavedAttachment { pub const ATTACHMENTS_DIR: &str = "chat-attachments"; +/// Opens what an agent reads from orx or another chat's agent, so it can tell +/// those messages from the user's. +pub const ORX_MESSAGE_PREFIX: &str = "[orx] "; + pub fn attachments_dir() -> Result { let dir = crate::store::data_dir().join(ATTACHMENTS_DIR); std::fs::create_dir_all(&dir) @@ -1239,10 +1294,23 @@ pub fn import_native_chat( } pub fn session_json(s: &StoredChatSession, busy: bool) -> Value { + session_json_with(Store::open().ok().as_ref(), s, busy) +} + +/// `session_json` for a caller that already holds the store, such as a list. +pub fn session_json_with(store: Option<&Store>, s: &StoredChatSession, busy: bool) -> Value { + let delegate = store + .map(|store| { + delegation::session_links(store, s).unwrap_or_else(|error| { + eprintln!("orx up: delegate of {}: {error}", s.id); + Value::Null + }) + }) + .unwrap_or_default(); let acp = s .harness .starts_with("acp:") - .then(|| Store::open().ok()?.acp_session_state(&s.id).ok().flatten()) + .then(|| store?.acp_session_state(&s.id).ok().flatten()) .flatten(); let context_usage = s .context_usage_json @@ -1280,6 +1348,7 @@ pub fn session_json(s: &StoredChatSession, busy: bool) -> Value { "contextUsage": context_usage, "activeLeafId": s.active_leaf_id, "sideParentSessionId": s.side_parent_session_id, + "delegate": delegate, "goal": s.goal, "autonomy": Autonomy::from_stored(s.autonomy.as_deref()).id(), }) @@ -2300,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 @@ -2328,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, @@ -2624,6 +2693,8 @@ struct QueuedMessage { request_hash: String, text: String, transcript_text: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + orx: Vec, overrides: TurnOverrides, images: Vec, annotations: Vec, @@ -2653,6 +2724,7 @@ pub(crate) fn legacy_opening_message( &TranscriptDisplay { text: transcript_text.clone(), annotations: None, + orx: Vec::new(), record_user_message: !brief_recorded, }, &overrides, @@ -2664,6 +2736,7 @@ pub(crate) fn legacy_opening_message( request_hash: request_hash.clone(), text, transcript_text, + orx: Vec::new(), overrides, images: Vec::new(), annotations: Vec::new(), @@ -2753,6 +2826,8 @@ pub struct SteerMessage { pub display: String, pub text: String, pub client_turn_id: Option, + /// Set when orx or another chat's agent wrote it. + pub orx: Option, } #[derive(Clone)] @@ -2764,6 +2839,9 @@ struct AnnotatedText { struct TranscriptDisplay { text: Option, annotations: Option>, + /// Messages orx or another chat's agent wrote, shown each under its + /// sender in place of `text`. + orx: Vec, /// A re-sampled turn re-sends the anchor's attachments and annotations, which /// would otherwise build a stray duplicate bubble even with the text blanked. record_user_message: bool, @@ -2894,15 +2972,24 @@ fn contextualize_messages( .join("\n\n") } +/// The parts of a user message: its text, or each message orx wrote with its +/// sender, then attachments and annotations. fn transcript_parts( display_text: &str, + orx: &[OrxDisplay], saved_images: &[SavedAttachment], annotations: &[TextAnnotation], ) -> Vec { let mut parts = Vec::new(); - if !display_text.is_empty() { + if orx.is_empty() && !display_text.is_empty() { parts.push(WirePart::text("p0", display_text.to_string())); } + for (i, message) in orx.iter().enumerate() { + parts.push(WirePart { + orx: Some(message.source.clone()), + ..WirePart::text(format!("p{i}"), message.text.clone()) + }); + } for (i, attachment) in saved_images.iter().enumerate() { parts.push(WirePart::image( format!("img{i}"), @@ -3122,7 +3209,12 @@ fn new_queued_id() -> String { /// Chip label for a parked message: its text, or an attachment count for an /// image/file-only send (which carries no text to show). fn queued_label(m: &QueuedMessage) -> String { - let display_text = m.transcript_text.as_deref().unwrap_or(&m.text); + let display_text = m + .orx + .first() + .map(|orx| orx.text.as_str()) + .or(m.transcript_text.as_deref()) + .unwrap_or(&m.text); if !display_text.trim().is_empty() || m.images.is_empty() { return display_text.to_string(); } @@ -3240,7 +3332,7 @@ impl TurnGuard { } /// Reserve a wake-up turn only when no turn or queued user message exists. - async fn claim_hidden(host: &Arc, session_id: &str) -> Option { + async fn claim_idle(host: &Arc, session_id: &str) -> Option { if host.deleting_sessions.lock().unwrap().contains(session_id) { return None; } @@ -3452,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); @@ -3659,6 +3751,8 @@ impl ChatHost { result_native_session_id: None, })?; self.emit("chat.message", message_json(&msg, session_id)); + self.emit_session(Store::open()?.get_chat_session(session_id)?) + .await; // A question card answered mid-turn is NOT an exit recourse from plan // mode, so it must not count as "saw a prompt" — a turn that asks a // question and then ends with its plan as plain text still needs the @@ -3715,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 @@ -4096,13 +4190,30 @@ impl ChatHost { let id = new_queued_id(); let client_turn_id = format!("ct_{}", uuid::Uuid::new_v4()); let steer_client_turn_id = message.client_turn_id.clone(); + // The raw text: the queue path expands slash-skills itself. What orx + // wrote is the agent's text, which no path expands, and keeps how it + // is shown. + let orx: Vec = message + .orx + .iter() + .map(|source| OrxDisplay { + text: message.display.clone(), + source: source.clone(), + }) + .collect(); + let text = if orx.is_empty() { + message.display + } else { + message.text + }; let messages = vec![AnnotatedText { - text: message.display.clone(), + text: text.clone(), annotations: Vec::new(), }]; let transcript = TranscriptDisplay { text: None, annotations: None, + orx: orx.clone(), record_user_message: true, }; let overrides = TurnOverrides::default(); @@ -4111,9 +4222,9 @@ impl ChatHost { id: id.clone(), client_turn_id: client_turn_id.clone(), request_hash: turn_request_hash(&messages, &transcript, &overrides, &images)?, - // The raw text: the queue path expands slash-skills itself. - text: message.display, + text, transcript_text: None, + orx, overrides, images: Vec::new(), annotations: Vec::new(), @@ -4450,6 +4561,7 @@ impl ChatHost { transcript: TranscriptDisplay { text: item.transcript_text.clone(), annotations: None, + orx: item.orx.clone(), record_user_message: true, }, overrides, @@ -4604,6 +4716,9 @@ impl ChatHost { /// parked queue when busy — whenever the live turn can't take it, notably /// attachments (they need the on-disk preamble only a full turn builds) /// and changed composer settings, which apply only at a turn boundary. + /// `orx` shows a message orx or another chat's agent wrote, whose agent + /// reads `text`. + #[expect(clippy::too_many_arguments)] pub async fn steer_message( self: &Arc, session_id: &str, @@ -4612,6 +4727,7 @@ impl ChatHost { images: Vec, annotations: Vec, client_turn_id: Option, + orx: Option, ) -> Result> { let lock = self .submission_locks @@ -4648,6 +4764,7 @@ impl ChatHost { images, annotations, client_turn_id, + orx, ) .await .map(Some); @@ -4671,6 +4788,7 @@ impl ChatHost { } let message = SteerMessage { text: project + .filter(|_| orx.is_none()) .map(|project| { expand_slash_skills( &project, @@ -4680,8 +4798,11 @@ impl ChatHost { ) }) .unwrap_or_else(|| text.clone()), - display: text.clone(), + display: orx + .as_ref() + .map_or_else(|| text.clone(), |orx| orx.text.clone()), client_turn_id: id.map(str::to_string), + orx: orx.as_ref().map(|orx| orx.source.clone()), }; if send_live_steer(&store, session_id, id, &request_hash, &sink, message)? { return Ok(None); @@ -4695,12 +4816,14 @@ impl ChatHost { images, annotations, client_turn_id, + orx, ) .await .map(Some) } /// Persist the user message and run one harness turn in the background. + #[expect(clippy::too_many_arguments)] pub async fn send_message( self: &Arc, session_id: &str, @@ -4709,6 +4832,7 @@ impl ChatHost { images: Vec, annotations: Vec, client_turn_id: Option, + orx: Option, ) -> Result { let lock = self .submission_locks @@ -4725,10 +4849,12 @@ impl ChatHost { images, annotations, client_turn_id, + orx, ) .await } + #[expect(clippy::too_many_arguments)] async fn send_message_locked( self: &Arc, session_id: &str, @@ -4737,6 +4863,7 @@ impl ChatHost { images: Vec, annotations: Vec, client_turn_id: Option, + orx: Option, ) -> Result { if let Some(id) = client_turn_id.as_deref().filter(|id| !id.trim().is_empty()) { if let Some((hash, _)) = Store::open()?.steer_receipt(session_id, id)? { @@ -4748,7 +4875,10 @@ impl ChatHost { )); } } - let transcript = message_transcript(&text, &annotations); + let transcript = TranscriptDisplay { + orx: orx.into_iter().collect(), + ..message_transcript(&text, &annotations) + }; self.send_message_showing( session_id, SendTurnRequest { @@ -5014,6 +5144,7 @@ impl ChatHost { transcript: TranscriptDisplay { text: Some(String::new()), annotations: None, + orx: Vec::new(), record_user_message: false, }, overrides: settings, @@ -5128,6 +5259,13 @@ impl ChatHost { ForkKind::Edit(_) => Vec::new(), ForkKind::Retry => replayed_attachments(&anchor_parts)?, }; + // What orx wrote is re-sent as its agent first read it, not as shown. + let orx_input = match kind { + ForkKind::Retry if anchor_parts.iter().any(|part| part.orx.is_some()) => store + .chat_turn_for_user_message(session_id, &anchor.id)? + .map(|turn| turn.prepared_input), + _ => None, + }; if text.is_empty() && annotations.is_empty() && attachments.is_empty() { return Err(anyhow!("nothing to re-sample")); } @@ -5142,6 +5280,7 @@ impl ChatHost { TranscriptDisplay { text: Some(String::new()), annotations: None, + orx: Vec::new(), record_user_message: false, }, ), @@ -5150,6 +5289,7 @@ impl ChatHost { TranscriptDisplay { text: Some(text.clone()), annotations: Some(annotations.clone()), + orx: Vec::new(), record_user_message: true, }, ), @@ -5187,7 +5327,7 @@ impl ChatHost { session_id, SendTurnRequest { messages: vec![AnnotatedText { text, annotations }], - prepared_input: None, + prepared_input: orx_input, replace_settings: false, transcript: display, overrides, @@ -5272,25 +5412,31 @@ impl ChatHost { Ok(()) } - async fn send_hidden_message( + /// Starts a turn with messages orx writes, each shown under its sender. + async fn send_orx_messages( self: &Arc, session_id: &str, - text: String, + messages: Vec<(String, OrxDisplay)>, guard: TurnGuard, ) -> Result { + let (texts, orx): (Vec, Vec) = messages.into_iter().unzip(); self.send_message_showing( session_id, SendTurnRequest { - messages: vec![AnnotatedText { - text, - annotations: Vec::new(), - }], + messages: texts + .into_iter() + .map(|text| AnnotatedText { + text, + annotations: Vec::new(), + }) + .collect(), prepared_input: None, replace_settings: false, transcript: TranscriptDisplay { - text: Some(String::new()), + text: None, annotations: None, - record_user_message: false, + orx, + record_user_message: true, }, overrides: TurnOverrides::default(), images: TurnAttachments::Uploaded(Vec::new()), @@ -5332,6 +5478,7 @@ impl ChatHost { let TranscriptDisplay { text: transcript_text, annotations: transcript_annotations, + orx, record_user_message, } = transcript; let text = messages @@ -5507,6 +5654,7 @@ impl ChatHost { request_hash: request_hash.clone(), text, transcript_text, + orx, overrides, images, annotations, @@ -5697,7 +5845,11 @@ impl ChatHost { session.archived = false; } let saved_images = images.save()?; - let display_text = transcript_text.as_deref().unwrap_or(&text); + let display_text = orx + .first() + .map(|orx| orx.text.as_str()) + .or(transcript_text.as_deref()) + .unwrap_or(&text); // The input auto-titling runs on — set only on the first message. // Owned because the title carries what the user typed, not the expanded // harness prompt built from its selected slash skills. @@ -5733,7 +5885,7 @@ impl ChatHost { } } - let parts = transcript_parts(display_text, &saved_images, &transcript_annotations); + let parts = transcript_parts(display_text, &orx, &saved_images, &transcript_annotations); // A resume whose transcript text is empty (e.g. a note-less plan // approval) records no user message: the resolved card already tells // that part of the story, and an empty bubble would just be noise. @@ -5755,8 +5907,8 @@ impl ChatHost { session.active_leaf_id.as_deref(), )?); // Slash-skills: the transcript keeps the `/name` the user typed; the - // harness gets the expanded prompt. - if prepared_input.is_none() { + // harness gets the expanded prompt. What orx writes is never a command. + if prepared_input.is_none() && orx.is_empty() { for message in &messages { prepare_project_slash_worktree(&project, &message.text, &session.id).await; } @@ -5766,10 +5918,28 @@ impl ChatHost { } else { None }; + // A command keeps its leading `/`, and what orx writes keeps its + // leading `[orx]`; any other message carries the ref an agent cites it by. + let message_ref = user_msg + .as_ref() + .filter(|_| { + orx.is_empty() + && !messages + .iter() + .any(|m| m.text.trim_start().starts_with('/')) + }) + .map(|message| delegation::message_ref(&message.id)); let mut turn_text = prepared_input.unwrap_or_else(|| { - let expanded = contextualize_messages(messages, |text| { - expand_slash_skills(&project, text, Some(&session.harness), Some(&session.id)) + let mut expanded = contextualize_messages(messages, |text| { + if orx.is_empty() { + expand_slash_skills(&project, text, Some(&session.harness), Some(&session.id)) + } else { + text.to_string() + } }); + if let Some(message_ref) = message_ref { + expanded = format!("{message_ref}\n{expanded}"); + } with_turn_context( session.native_session_id.as_deref(), bootstrap.as_deref(), @@ -6262,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, id: &str) -> Result> { + 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, 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 @@ -6274,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; } @@ -6446,6 +6639,7 @@ impl ChatHost { } _ => None, }; + let (text, shown) = req.as_written(text); self.send_message_showing( &req.session_id, SendTurnRequest { @@ -6458,6 +6652,7 @@ impl ChatHost { transcript: TranscriptDisplay { text: transcript, annotations: Some(req.annotations.clone()), + orx: shown.into_iter().collect(), record_user_message: true, }, overrides, @@ -6480,6 +6675,24 @@ impl ChatHost { self.set_plan_mode(&req.session_id, plan_mode).await?; } self.resolve_prompt_card(&req); + // A held reply reads as the user's own; say which chat gave it, + // where that can join the running turn rather than start one. + if prompt.native_id.is_some() + && req.from.is_some() + && crate::local::harness::supports_steering(&session.harness) + { + let (text, shown) = req.as_written(req.plain_answer_text()); + self.steer_message( + &req.session_id, + text, + TurnOverrides::default(), + Vec::new(), + Vec::new(), + None, + shown, + ) + .await?; + } Ok(()) } ResumeAction::Nothing => { @@ -6522,6 +6735,15 @@ impl ChatHost { Ok(msg) => self.emit("chat.message", message_json(&msg, &req.session_id)), Err(e) => eprintln!("orx up: answered prompt not marked resolved: {e}"), } + // A delegate's card stops showing the question; the answered turn goes on. + if let Ok(Some(session)) = + Store::open().and_then(|store| store.get_chat_session(&req.session_id)) + { + self.emit( + "chat.session", + json!({ "session": session_json(&session, true) }), + ); + } } /// Broadcast a freshly re-read session row, resolving `busy` live from the @@ -6889,9 +7111,32 @@ pub struct PromptAnswer { pub note: Option, #[serde(default)] pub annotations: Vec, + /// The chat whose agent answered for the user, through `answer`. + #[serde(skip)] + pub from: Option, } impl PromptAnswer { + /// What the asking agent reads of an answer, and how the transcript shows + /// it: as the answering chat's message when the user did not answer. + pub(crate) fn as_written(&self, text: String) -> (String, Option) { + let Some(from) = &self.from else { + return (text, None); + }; + let shown = OrxDisplay { + text: self.plain_answer_text(), + source: OrxSource { + kind: OrxKind::Message, + from: Some(from.clone()), + status: None, + }, + }; + ( + format!("{ORX_MESSAGE_PREFIX}Chat `{from}` answered for the user:\n\n{text}"), + Some(shown), + ) + } + pub(crate) fn plain_answer_text(&self) -> String { let note = self.note.as_deref().filter(|note| !note.trim().is_empty()); let mut text = if self.answers.is_empty() { @@ -7019,6 +7264,7 @@ fn stamp_resolved(prompt: &mut WirePrompt, answer: Option<&PromptAnswer>) { prompt.approved = Some(answer.approve); prompt.note = answer.note.clone().filter(|n| !n.trim().is_empty()); prompt.annotations = answer.annotations.clone(); + prompt.answered_by = answer.from.clone(); } } @@ -7237,6 +7483,7 @@ fn message_transcript(text: &str, annotations: &[TextAnnotation]) -> TranscriptD } }), annotations: None, + orx: Vec::new(), record_user_message: true, } } @@ -7264,7 +7511,7 @@ fn turn_request_hash( overrides: &TurnOverrides, images: &TurnAttachments, ) -> Result { - let value = json!({ + let mut value = json!({ "messages": messages.iter().map(|message| json!({ "text": message.text, "annotations": message.annotations, @@ -7274,6 +7521,10 @@ fn turn_request_hash( "settings": overrides, "images": images.hash_value(), }); + // Only messages orx wrote hash it, so a retry from before it existed still matches. + if !transcript.orx.is_empty() { + value["orx"] = json!(transcript.orx); + } let mut digest = Sha256::new(); digest.update(serde_json::to_vec(&value)?); Ok(format!("{:x}", digest.finalize())) @@ -7366,6 +7617,9 @@ fn resolve_permission_change( pub struct TurnCtx { pub host: Arc, pub turn_id: String, + /// What the turn's message last showed it waiting on, so the session + /// is re-sent when that changes. + asking: Option, durable: bool, usage_execution_id: String, pub(crate) native_message_models: HashMap, @@ -7433,6 +7687,7 @@ fn turn_ctx_from_stored( retry_owner: None, retry_started_emitted: false, retry_exhausted: false, + asking: None, orx_retry_started: None, orx_retry_count: 0, terminal_error: None, @@ -7820,6 +8075,7 @@ impl TurnCtx { retry_owner: None, retry_started_emitted: false, retry_exhausted: false, + asking: None, orx_retry_started: None, orx_retry_count: 0, terminal_error: None, @@ -8016,10 +8272,10 @@ impl TurnCtx { /// Record a steer inline without waiting for the flush interval. pub fn record_steer(&mut self, steer: &SteerMessage, confirmed: bool) { - self.upsert_part(WirePart::steer( - format!("steer-{}", uuid::Uuid::new_v4()), - &steer.display, - )); + self.upsert_part(WirePart { + orx: steer.orx.clone(), + ..WirePart::steer(format!("steer-{}", uuid::Uuid::new_v4()), &steer.display) + }); if self.flush().is_ok() && confirmed { if let Some(id) = steer.client_turn_id.as_deref() { let _ = Store::open().and_then(|store| store.finish_steer(&self.session_id, id)); @@ -8162,6 +8418,23 @@ impl TurnCtx { })?; wire_assistant }; + // A delegate's card shows what it waits on, so a card appearing or + // resolved mid-turn re-sends its session. + let asking = wire_assistant.parts.iter().find_map(|part| { + part.prompt + .as_ref() + .filter(|prompt| !prompt.resolved) + .map(|prompt| prompt.kind.clone()) + }); + if asking != self.asking { + self.asking = asking; + if let Some(session) = store.get_chat_session(&self.session_id)? { + self.host.emit( + "chat.session", + json!({ "session": session_json(&session, true) }), + ); + } + } self.host.emit( "chat.message", message_json(&wire_assistant, &self.session_id), @@ -8174,7 +8447,7 @@ impl TurnCtx { /// Merge the persisted resolution state of prompt parts into the in-memory /// assistant message, so a concurrent `respond` that resolved a card isn't /// clobbered by this turn's next flush. Only ever flips `false`→`true` and - /// fills an empty echo (`answers`/`approved`/`note`/`annotations`) — never the reverse — + /// fills an empty echo (`answers`/`approved`/`note`/`annotations`/`answered_by`) — never the reverse — /// so it's safe regardless of ordering: the in-memory copy normally never /// carries an echo of its own, and dropping the stored one here would /// erase the stamped outcome on the next flush. @@ -8208,6 +8481,7 @@ impl TurnCtx { prompt.approved = stored_prompt.approved; prompt.note = stored_prompt.note.clone(); prompt.annotations = stored_prompt.annotations.clone(); + prompt.answered_by = stored_prompt.answered_by.clone(); } } } @@ -8283,11 +8557,12 @@ fn active_path<'a>( } fn side_chat_context<'a>( + parent: &str, messages: impl IntoIterator, ) -> Option { let snapshot = crate::local::harness::transcript_snapshot(messages); (!snapshot.is_empty()).then(|| format!( - "\nThis is a side chat branched from another chat, which may still be running in this same worktree. Use this snapshot of that chat, taken when the side chat opened, to answer questions about its work. Do not modify files unless the user asks.\n{snapshot}\n" + "\nThis is a side chat branched from chat `{parent}`, which may still be running in this same worktree. Use this snapshot of that chat, taken when the side chat opened, to answer questions about its work. Do not modify files unless the user asks.\n{snapshot}\n" )) } @@ -8308,7 +8583,10 @@ fn effective_bootstrap_context( if !messages.iter().any(|message| &message.id == leaf) { return Err(anyhow!("side chat parent context is unavailable")); } - Ok(side_chat_context(active_path(&messages, Some(leaf)))) + Ok(side_chat_context( + parent, + active_path(&messages, Some(leaf)), + )) } fn side_chat_session( @@ -8321,7 +8599,7 @@ fn side_chat_session( .filter(|id| messages.iter().any(|m| &m.id == *id)); // Legacy transcripts without a valid leaf keep their existing snapshot semantics. let bootstrap_context = if leaf.is_none() && !messages.is_empty() { - side_chat_context(messages.iter()) + side_chat_context(&parent.id, messages.iter()) } else { None }; @@ -8482,189 +8760,9 @@ fn materialize_unfinished_turns( // --- run watcher ---------------------------------------------------------------- -fn run_wakeup_text(run: &crate::store::StoredRun) -> Option { - if run.status == "lost" { - return Some(format!( - "[orx] Run `{}` ended with **Outcome unavailable**. Its final outcome could not be \ - collected. Inspect any partial logs using `orx logs {}`; do not assume success or failure.", - run.id, run.id - )); - } - matches!(run.status.as_str(), "done" | "failed").then(|| { - format!( - "[orx] Run `{}` finished with status **{}**. You can compare this result with other \ - project runs using `orx runs {}` and inspect the file located by `orx logs {}`.", - run.id, run.status, run.project_id, run.id - ) - }) -} - -// Only local identifiers here: the error text includes remote ssh stderr, so the agent reads it -// as command output instead of inside an `[orx]` instruction. -fn run_monitoring_text(runs: &[crate::store::StoredRun]) -> String { - let lines = runs - .iter() - .map(|run| { - format!( - "- run `{}` of experiment `{}` (still **{}**)", - run.id, run.experiment_id, run.status - ) - }) - .collect::>() - .join("\n"); - format!( - "[orx] orx can no longer monitor these live runs:\n{lines}\nRun `orx exp status ` \ - for the reason and tell the user so they can fix it. orx wakes you once it can see a run \ - finish; until then each run keeps its current status." - ) -} - -fn first_wakeup_per_session(wakeups: Vec) -> Vec { - let mut seen_sessions = HashSet::new(); - wakeups - .into_iter() - .filter(|wakeup| seen_sessions.insert(wakeup.chat_session_id.clone())) - .collect() -} - -async fn process_run_wakeups( - chat: &Arc, - store: Store, - data_dir_move_in_progress: Option<&std::sync::atomic::AtomicBool>, -) -> Result<()> { - if data_dir_move_in_progress.is_some_and(|flag| flag.load(std::sync::atomic::Ordering::SeqCst)) - { - return Ok(()); - } - store.prune_run_wakeups()?; - for wakeup in first_wakeup_per_session(store.list_ready_run_wakeups()?) { - if wakeup.state != "pending" { - continue; - } - let Some(mut guard) = TurnGuard::claim_hidden(chat, &wakeup.chat_session_id).await else { - continue; - }; - if data_dir_move_in_progress - .is_some_and(|flag| flag.load(std::sync::atomic::Ordering::SeqCst)) - { - guard.release().await; - return Ok(()); - } - let Some(token) = store.claim_run_wakeup(&wakeup.run.id, &wakeup.chat_session_id)? else { - guard.release().await; - continue; - }; - if !store.renew_run_wakeup_claim(&wakeup.run.id, &wakeup.chat_session_id, &token)? { - guard.release().await; - continue; - } - let Some(text) = run_wakeup_text(&wakeup.run) else { - store.release_run_wakeup(&wakeup.run.id, &wakeup.chat_session_id, &token)?; - guard.release().await; - continue; - }; - match chat - .send_hidden_message(&wakeup.chat_session_id, text, guard) - .await - { - Ok(TurnSubmission::Started(_)) => { - if !store.mark_run_wakeup_delivered( - &wakeup.run.id, - &wakeup.chat_session_id, - &token, - )? { - return Err(anyhow!( - "run wake-up claim expired before delivery was recorded" - )); - } - } - Ok( - TurnSubmission::Queued(_) - | TurnSubmission::QueuedExisting(_) - | TurnSubmission::Existing(_) - | TurnSubmission::NotStarted, - ) => { - store.release_run_wakeup(&wakeup.run.id, &wakeup.chat_session_id, &token)?; - } - Err(err) => { - store.release_run_wakeup(&wakeup.run.id, &wakeup.chat_session_id, &token)?; - if !chat.is_busy(&wakeup.chat_session_id).await { - eprintln!("orx up: run watcher: {err}"); - } - } - } - } - process_run_monitoring_alerts(chat, store, data_dir_move_in_progress).await -} - -/// Tells each waiting session, once per outage, which of its live runs can no -/// longer be monitored, leaving their terminal wake-ups pending. -async fn process_run_monitoring_alerts( - chat: &Arc, - store: Store, - data_dir_move_in_progress: Option<&std::sync::atomic::AtomicBool>, -) -> Result<()> { - let mut unalerted = Vec::new(); - for wakeup in store.list_active_run_wakeups()? { - let unmonitored = crate::jobs::BackendDescriptor::parse(&wakeup.run.backend_json) - .is_ok_and(|descriptor| descriptor.monitoring_error.is_some()); - if unmonitored && !wakeup.monitoring_alerted { - unalerted.push(wakeup); - } else if !unmonitored && wakeup.monitoring_alerted { - store.set_run_wakeup_monitoring_alerted( - &wakeup.run.id, - &wakeup.chat_session_id, - false, - )?; - } - } - let mut by_session: HashMap> = HashMap::new(); - for wakeup in unalerted { - by_session - .entry(wakeup.chat_session_id.clone()) - .or_default() - .push(wakeup); - } - for (session_id, alerts) in by_session { - let Some(mut guard) = TurnGuard::claim_hidden(chat, &session_id).await else { - continue; - }; - if data_dir_move_in_progress - .is_some_and(|flag| flag.load(std::sync::atomic::Ordering::SeqCst)) - { - guard.release().await; - return Ok(()); - } - let mut claimed = Vec::new(); - for wakeup in alerts { - if store.set_run_wakeup_monitoring_alerted(&wakeup.run.id, &session_id, true)? { - claimed.push(wakeup.run); - } - } - if claimed.is_empty() { - guard.release().await; - continue; - } - let text = run_monitoring_text(&claimed); - let started = chat.send_hidden_message(&session_id, text, guard).await; - if !matches!(started, Ok(TurnSubmission::Started(_))) { - for run in &claimed { - store.set_run_wakeup_monitoring_alerted(&run.id, &session_id, false)?; - } - if let Err(err) = started { - if !chat.is_busy(&session_id).await { - eprintln!("orx up: run watcher: {err}"); - } - } - } - } - Ok(()) -} - -// --- spawned agents ------------------------------------------------------------- - -/// Resume explicitly subscribed agent sessions after a run finishes. Busy and -/// draining sessions retain their durable wake-up until they become idle. +/// Resume explicitly subscribed agent sessions after a run finishes or a chat +/// they subscribe to has news. Busy and draining sessions keep their durable +/// wake-up until idle. pub async fn watch_runs( chat: Arc, data_dir_move_in_progress: Arc, @@ -8684,9 +8782,9 @@ pub async fn watch_runs( } let Ok(store) = Store::open() else { continue }; if let Err(err) = - process_run_wakeups(&chat, store, Some(data_dir_move_in_progress.as_ref())).await + news::deliver_news(&chat, store, Some(data_dir_move_in_progress.as_ref())).await { - eprintln!("orx up: run watcher: {err}"); + eprintln!("orx up: news watcher: {err}"); } } } @@ -9603,6 +9701,7 @@ mod cap_tests { prompt: None, phase: None, children: Vec::new(), + orx: None, }; // A spawn part whose sub-agent transcript (a child) has huge output. let mut spawn = bloated_tool("spawn"); @@ -9655,6 +9754,7 @@ mod cap_tests { prompt: None, phase: None, children: Vec::new(), + orx: None, }]; cap_tool_parts(&mut parts); @@ -9764,6 +9864,7 @@ mod cap_tests { prompt: None, phase: None, children: Vec::new(), + orx: None, }]; assert!(!attach_target_event( @@ -9799,6 +9900,7 @@ mod cap_tests { prompt: None, phase: None, children: Vec::new(), + orx: None, }; let mut parts = vec![make_part("one"), make_part("two")]; let claimed = HashSet::new(); @@ -9837,6 +9939,7 @@ mod cap_tests { prompt: None, phase: None, children: Vec::new(), + orx: None, }; let mut parts = vec![make_part("one", "/one"), make_part("two", "/two")]; let mut ids = attach_target_event( @@ -9875,6 +9978,7 @@ mod cap_tests { prompt: None, phase: None, children: Vec::new(), + orx: None, }]; settle_interrupted_tool_parts(&mut parts); @@ -9904,6 +10008,7 @@ mod cap_tests { prompt: None, phase: None, children: Vec::new(), + orx: None, }]; let replacement = WirePart { id: "logs".into(), @@ -9920,6 +10025,7 @@ mod cap_tests { prompt: None, phase: None, children: Vec::new(), + orx: None, }; upsert_preserving_children(&mut parts, replacement); @@ -10078,6 +10184,7 @@ mod bridge_tests { ..Default::default() }, )], + orx: None, }]; assert!(resolve_stale_prompts_in_parts(&mut parts, true)); @@ -10145,6 +10252,7 @@ mod bridge_tests { answers: Vec::new(), note: Some("Keep the tests".into()), annotations: Vec::new(), + from: None, }), ); assert_eq!(plan.approved, Some(true)); @@ -10255,6 +10363,7 @@ mod bridge_tests { answers: answers.iter().map(|s| s.to_string()).collect(), note: note.map(str::to_string), annotations: Vec::new(), + from: None, } } @@ -10300,6 +10409,50 @@ mod bridge_tests { assert_eq!(prompt.note, None); } + #[test] + fn a_flush_keeps_the_answer_echo_another_path_stamped() { + let dir = std::env::temp_dir().join(format!("orx-adopt-{}", uuid::Uuid::new_v4())); + let store = Store::open_at(dir.clone()).unwrap(); + let mut ctx = TurnCtx::test_stub(); + let card = |prompt: WirePrompt| { + let mut part = WirePart::text("card", ""); + part.kind = "prompt".into(); + part.prompt = Some(prompt); + part + }; + let mut stamped = WirePrompt { + kind: "question".into(), + ..Default::default() + }; + let mut answer = answer(&["A"], true, None); + answer.from = Some("chat_parent".into()); + stamp_resolved(&mut stamped, Some(&answer)); + store + .upsert_chat_message(&StoredChatMessage { + id: ctx.assistant.id.clone(), + session_id: ctx.session_id.clone(), + role: "assistant".into(), + parts_json: serde_json::to_string(&[card(stamped)]).unwrap(), + created_at: 1, + completed_at: None, + parent_id: None, + base_native_session_id: None, + result_native_session_id: None, + }) + .unwrap(); + ctx.assistant.parts = vec![card(WirePrompt { + kind: "question".into(), + ..Default::default() + })]; + + ctx.adopt_resolved_prompts(&store); + let adopted = ctx.assistant.parts[0].prompt.as_ref().unwrap(); + assert!(adopted.resolved); + assert_eq!(adopted.answers, ["A"]); + assert_eq!(adopted.answered_by.as_deref(), Some("chat_parent")); + let _ = std::fs::remove_dir_all(dir); + } + #[test] fn stamp_resolved_without_answer_preserves_an_earlier_echo() { // A stale-card cleanup (PendingGuard drop, resolve_stale_prompts) runs @@ -10710,54 +10863,91 @@ mod run_wakeup_tests { #[test] fn wakeup_messages_are_exact_and_exclude_cancellation() { assert_eq!( - run_wakeup_text(&run("done")).as_deref(), + news::run_wakeup_text(&run("done")).as_deref(), Some( "[orx] Run `run_x` finished with status **done**. You can compare this result \ with other project runs using `orx runs p1` and inspect the file located by `orx logs run_x`." ) ); assert_eq!( - run_wakeup_text(&run("failed")).as_deref(), + news::run_wakeup_text(&run("failed")).as_deref(), Some( "[orx] Run `run_x` finished with status **failed**. You can compare this result \ with other project runs using `orx runs p1` and inspect the file located by `orx logs run_x`." ) ); - assert!(run_wakeup_text(&run("cancelled")).is_none()); + assert!(news::run_wakeup_text(&run("cancelled")).is_none()); assert_eq!( - run_wakeup_text(&run("lost")).as_deref(), + news::run_wakeup_text(&run("lost")).as_deref(), Some("[orx] Run `run_x` ended with **Outcome unavailable**. Its final outcome could not be collected. Inspect any partial logs using `orx logs run_x`; do not assume success or failure.") ); } #[test] fn hidden_transcript_override_creates_no_user_parts() { - assert!(transcript_parts("", &[], &[]).is_empty()); + assert!(transcript_parts("", &[], &[], &[]).is_empty()); } #[test] - fn only_earliest_wakeup_per_session_is_attempted_each_tick() { - let mut first = run("done"); - first.id = "run_first".into(); - let mut second = run("done"); - second.id = "run_second".into(); - let selected = first_wakeup_per_session(vec![ - crate::store::RunWakeup { - run: first, - chat_session_id: "owner".into(), - state: "pending".into(), - monitoring_alerted: false, - }, - crate::store::RunWakeup { - run: second, - chat_session_id: "owner".into(), - state: "pending".into(), - monitoring_alerted: false, + fn each_message_orx_writes_shows_as_its_own_part_with_its_sender() { + let run = |id: &str, status: &str| OrxDisplay { + text: format!("Run {id} ended."), + source: OrxSource { + kind: OrxKind::Run, + from: Some(id.into()), + status: Some(status.into()), }, - ]); + }; + let orx = [run("run_x", "done"), run("run_y", "failed")]; + let parts = transcript_parts("what the agent reads", &orx, &[], &[]); + let shown: Vec<_> = parts + .iter() + .map(|part| { + ( + part.id.as_str(), + part.text.as_deref().unwrap_or_default(), + part.orx.as_ref(), + ) + }) + .collect(); + assert_eq!( + shown, + [ + ("p0", "Run run_x ended.", Some(&orx[0].source)), + ("p1", "Run run_y ended.", Some(&orx[1].source)), + ] + ); + } - assert_eq!(selected.len(), 1); - assert_eq!(selected[0].run.id, "run_first"); + #[test] + fn each_run_that_ended_is_its_own_message() { + let (store, dir) = temp_store("batched"); + let mut second = run("failed"); + second.id = "run_y".into(); + let news: Vec = [run("done"), second] + .into_iter() + .map(|run| { + news::News::Run(Box::new(crate::store::RunWakeup { + run, + chat_session_id: "owner".into(), + state: "pending".into(), + monitoring_alerted: false, + })) + }) + .collect(); + let messages = news::messages(&store, &news).unwrap(); + assert_eq!(messages.len(), 2); + assert!(messages[0] + .0 + .starts_with("[orx] Run `run_x` finished with status **done**")); + assert!(messages[1] + .0 + .starts_with("[orx] Run `run_y` finished with status **failed**")); + let status = |i: usize| messages[i].1.source.status.as_deref(); + assert_eq!((status(0), status(1)), (Some("done"), Some("failed"))); + assert_eq!(messages[1].1.source.from.as_deref(), Some("run_y")); + drop(store); + let _ = std::fs::remove_dir_all(dir); } #[test] @@ -10807,6 +10997,7 @@ with other project runs using `orx runs p1` and inspect the file located by `orx request_hash: "hash".into(), text: "user first".into(), transcript_text: None, + orx: Vec::new(), overrides: TurnOverrides::default(), images: Vec::new(), annotations: Vec::new(), @@ -10816,7 +11007,7 @@ with other project runs using `orx runs p1` and inspect the file located by `orx }]), ); - assert!(TurnGuard::claim_hidden(&host, "owner").await.is_none()); + assert!(TurnGuard::claim_idle(&host, "owner").await.is_none()); } #[test] @@ -10827,6 +11018,7 @@ with other project runs using `orx runs p1` and inspect the file located by `orx request_hash: "hash".into(), text: "retry me".into(), transcript_text: None, + orx: Vec::new(), overrides: TurnOverrides::default(), images: Vec::new(), annotations: Vec::new(), @@ -10863,7 +11055,7 @@ with other project runs using `orx runs p1` and inspect the file located by `orx )); drop(store); - process_run_wakeups(&host, Store::open_at(dir.clone()).unwrap(), None) + news::deliver_news(&host, Store::open_at(dir.clone()).unwrap(), None) .await .unwrap(); @@ -10885,7 +11077,7 @@ with other project runs using `orx runs p1` and inspect the file located by `orx let moving = std::sync::atomic::AtomicBool::new(true); drop(store); - process_run_wakeups(&host, Store::open_at(dir.clone()).unwrap(), Some(&moving)) + news::deliver_news(&host, Store::open_at(dir.clone()).unwrap(), Some(&moving)) .await .unwrap(); @@ -10913,7 +11105,7 @@ with other project runs using `orx runs p1` and inspect the file located by `orx .insert("owner".into(), TurnState::Draining); drop(store); - process_run_wakeups(&host, Store::open_at(dir.clone()).unwrap(), None) + news::deliver_news(&host, Store::open_at(dir.clone()).unwrap(), None) .await .unwrap(); @@ -10940,7 +11132,7 @@ with other project runs using `orx runs p1` and inspect the file located by `orx }; let mut second = run("running"); second.id = "run_y".into(); - let text = run_monitoring_text(&[first, second]); + let text = news::run_monitoring_text(&[first, second]); assert!(!text.contains("REMOTE_SENTINEL")); assert_eq!( text, @@ -10969,7 +11161,7 @@ once it can see a run finish; until then each run keeps its current status." .insert("owner".into(), TurnState::Draining); drop(store); - process_run_wakeups(&host, Store::open_at(dir.clone()).unwrap(), None) + news::deliver_news(&host, Store::open_at(dir.clone()).unwrap(), None) .await .unwrap(); @@ -10999,7 +11191,7 @@ once it can see a run finish; until then each run keeps its current status." )); drop(store); - process_run_wakeups(&host, Store::open_at(dir.clone()).unwrap(), None) + news::deliver_news(&host, Store::open_at(dir.clone()).unwrap(), None) .await .unwrap(); @@ -11102,8 +11294,12 @@ mod transcript_tree_tests { let side = side_chat_session(&parent_session("codex"), &messages); assert_eq!(side.bootstrap_context, None); assert_eq!(side.side_parent_leaf_id.as_deref(), Some("a3")); - let context = - side_chat_context(active_path(&messages, side.side_parent_leaf_id.as_deref())).unwrap(); + let context = side_chat_context( + "chat_parent", + active_path(&messages, side.side_parent_leaf_id.as_deref()), + ) + .unwrap(); + assert!(context.contains("branched from chat `chat_parent`")); assert!(context.contains("kept branch") && context.contains("loss is falling")); assert!(!context.contains("abandoned retry")); assert_eq!(side.side_parent_session_id.as_deref(), Some("chat_parent")); @@ -11146,7 +11342,10 @@ mod transcript_tree_tests { } let side = side_chat_session(&parent, &messages); store.create_chat_session(&side).unwrap(); - let expected = side_chat_context(active_path(&messages, parent.active_leaf_id.as_deref())); + let expected = side_chat_context( + &parent.id, + active_path(&messages, parent.active_leaf_id.as_deref()), + ); assert_eq!( effective_bootstrap_context(&store, &side).unwrap(), expected @@ -11216,7 +11415,10 @@ mod transcript_tree_tests { let expected = crate::local::harness::transcript_snapshot(messages.iter()); assert!(expected.len() <= 32 * 1024); assert!(expected.ends_with('界')); - assert_eq!(side.bootstrap_context, side_chat_context(messages.iter())); + assert_eq!( + side.bootstrap_context, + side_chat_context(&parent.id, messages.iter()) + ); assert!(side.bootstrap_context.unwrap().contains(&expected)); } @@ -11344,6 +11546,7 @@ mod steering_tests { display: text.into(), text: text.into(), client_turn_id: None, + orx: None, } } @@ -11364,6 +11567,7 @@ mod steering_tests { vec![], vec![], Some("ct1".into()), + None, ) }; assert!(send().await.unwrap().is_none()); @@ -11381,7 +11585,8 @@ mod steering_tests { TurnOverrides::default(), vec![], vec![], - Some("ct1".into()) + Some("ct1".into()), + None, ) .await .is_err()); diff --git a/src/local/chat/news.rs b/src/local/chat/news.rs new file mode 100644 index 000000000..0b8960ecf --- /dev/null +++ b/src/local/chat/news.rs @@ -0,0 +1,472 @@ +//! What a chat has not been told yet: a finished turn or a question from a +//! chat it subscribes to, and the end of a run it asked to be woken for. Each +//! idle chat's next turn starts with all of its news at once, unless the agent +//! collected chat news first with `wait`. + +use std::collections::BTreeMap; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; + +use super::delegation::{ + answer, inline, message_ref, message_text, pending_prompt, question_body, question_text, + PendingPrompt, +}; +use super::{ + stored_to_wire, ChatHost, OrxDisplay, OrxKind, OrxSource, TurnGuard, TurnSubmission, + ORX_MESSAGE_PREFIX, +}; +use crate::error::{bail, Result}; +use crate::store::{ReadyChatSubscription, RunWakeup, Store, StoredRun, ToldEvent}; + +/// How much of a message the user wrote in a subscribed chat its news quotes. +const USER_PREVIEW_CHARS: usize = 300; + +pub enum News { + Answer(ReadyChatSubscription), + Question { + subscriber: String, + target: String, + prompt: Box, + }, + /// A run the chat asked to be woken for ended. + Run(Box), + /// orx lost sight of a run the chat waits on; told once per outage. + Unmonitored(Box), +} + +impl News { + pub fn subscriber(&self) -> &str { + match self { + News::Answer(ready) => &ready.subscriber_session_id, + News::Question { subscriber, .. } => subscriber, + News::Run(wakeup) | News::Unmonitored(wakeup) => &wakeup.chat_session_id, + } + } + + /// The chat or run the news is about. + pub fn target(&self) -> &str { + match self { + News::Answer(ready) => &ready.target_session_id, + News::Question { target, .. } => target, + News::Run(wakeup) | News::Unmonitored(wakeup) => &wakeup.run.id, + } + } + + /// Lease the news for telling, unless it was told already or another + /// sweep holds it. + pub fn claim(&self, store: &Store) -> Result> { + match self { + News::Answer(ready) => store.claim_chat_subscription( + self.subscriber(), + self.target(), + ToldEvent::Turn(&ready.turn_id), + ), + News::Question { prompt, .. } => store.claim_chat_subscription( + self.subscriber(), + self.target(), + ToldEvent::Prompt(&prompt.id), + ), + News::Run(wakeup) => store.claim_run_wakeup(&wakeup.run.id, &wakeup.chat_session_id), + News::Unmonitored(wakeup) => Ok(store + .set_run_wakeup_monitoring_alerted(&wakeup.run.id, &wakeup.chat_session_id, true)? + .then(String::new)), + } + } + + /// Release a claim. `told` records the news as told; without it the news + /// is offered again on a later sweep. + pub fn settle(&self, store: &Store, token: &str, told: bool) -> Result<()> { + match self { + News::Answer(ready) => { + let event = ToldEvent::Turn(&ready.turn_id); + let told = told.then_some(event); + store.settle_chat_subscription(self.subscriber(), self.target(), token, told)?; + } + News::Question { prompt, .. } => { + let event = ToldEvent::Prompt(&prompt.id); + let told = told.then_some(event); + store.settle_chat_subscription(self.subscriber(), self.target(), token, told)?; + } + News::Run(wakeup) if told => { + if !store.mark_run_wakeup_delivered( + &wakeup.run.id, + &wakeup.chat_session_id, + token, + )? { + bail!("run wake-up claim expired before delivery was recorded"); + } + } + News::Run(wakeup) => { + store.release_run_wakeup(&wakeup.run.id, &wakeup.chat_session_id, token)? + } + News::Unmonitored(_) if told => {} + News::Unmonitored(wakeup) => { + store.set_run_wakeup_monitoring_alerted( + &wakeup.run.id, + &wakeup.chat_session_id, + false, + )?; + } + } + Ok(()) + } +} + +/// Everything subscriptions owe, or owe one subscriber. A chat waiting on a +/// question owes the question, not the turn that ended asking it. +pub fn chat_news(store: &Store, subscriber: Option<&str>) -> Result> { + let mut prompts: BTreeMap> = BTreeMap::new(); + let mut pending = |target: &str| -> Result> { + if !prompts.contains_key(target) { + prompts.insert(target.to_string(), pending_prompt(store, target)?); + } + Ok(prompts[target].clone()) + }; + let mut news = Vec::new(); + for sub in store.list_chat_subscriptions(subscriber)? { + if sub.paused || !sub.outstanding { + continue; + } + let Some(prompt) = + pending(&sub.target_session_id)?.filter(|pending| pending.kind() == "question") + else { + continue; + }; + if sub.told_prompt_id.as_deref() != Some(prompt.id.as_str()) { + news.push(News::Question { + subscriber: sub.subscriber_session_id, + target: sub.target_session_id, + prompt: Box::new(prompt), + }); + } + } + for ready in store.list_ready_chat_subscriptions()? { + if subscriber.is_some_and(|id| id != ready.subscriber_session_id) { + continue; + } + if echoes_its_subscriber(store, &ready)? { + mark_told( + store, + &ready.subscriber_session_id, + &ready.target_session_id, + )?; + continue; + } + let asking = + pending(&ready.target_session_id)?.is_some_and(|pending| pending.kind() == "question"); + if !asking { + news.push(News::Answer(ready)); + } + } + Ok(news) +} + +/// Whether the target's turn only answered being told the subscriber's own +/// news. That is no news to the subscriber, and telling it would wake two +/// chats subscribed to each other in turn forever. +fn echoes_its_subscriber(store: &Store, ready: &ReadyChatSubscription) -> Result { + let Some(turn) = store.get_chat_turn(&ready.target_session_id, &ready.turn_id)? else { + return Ok(false); + }; + let Some(message) = turn + .user_message_id + .map(|id| store.get_chat_message(&id)) + .transpose()? + .flatten() + else { + return Ok(false); + }; + let parts = stored_to_wire(&message).parts; + Ok(!parts.is_empty() + && parts.iter().all(|part| { + part.orx.as_ref().is_some_and(|orx| { + matches!(orx.kind, OrxKind::Answer | OrxKind::Question) + && orx.from.as_deref() == Some(ready.subscriber_session_id.as_str()) + }) + })) +} + +/// Runs that ended, and runs orx can no longer see, for the chats waiting on +/// them. A run that is seen again re-arms its outage alert. +fn run_news(store: &Store) -> Result> { + store.prune_run_wakeups()?; + let mut news: Vec = store + .list_ready_run_wakeups()? + .into_iter() + .filter(|wakeup| wakeup.state == "pending" && run_wakeup_text(&wakeup.run).is_some()) + .map(|wakeup| News::Run(Box::new(wakeup))) + .collect(); + for wakeup in store.list_active_run_wakeups()? { + let unmonitored = crate::jobs::BackendDescriptor::parse(&wakeup.run.backend_json) + .is_ok_and(|descriptor| descriptor.monitoring_error.is_some()); + if unmonitored && !wakeup.monitoring_alerted { + news.push(News::Unmonitored(Box::new(wakeup))); + } else if !unmonitored && wakeup.monitoring_alerted { + store.set_run_wakeup_monitoring_alerted( + &wakeup.run.id, + &wakeup.chat_session_id, + false, + )?; + } + } + Ok(news) +} + +/// What a chat is told about its news, each piece as its agent reads it and +/// as the transcript shows it, with one for every run orx lost sight of. +pub fn messages<'a>( + store: &Store, + news: impl IntoIterator, +) -> Result> { + let mut messages = Vec::new(); + let mut unmonitored = Vec::new(); + for item in news { + let model = || -> Result { + Ok(store + .get_chat_session(item.target())? + .and_then(|session| session.model) + .unwrap_or_default()) + }; + match item { + News::Question { target, prompt, .. } => messages.push(( + question_text(target, &model()?, prompt), + OrxDisplay { + text: question_body(&prompt.prompt), + source: source(OrxKind::Question, Some(target), None), + }, + )), + News::Answer(ready) => messages.push(answer_text(store, ready, &model()?)?), + News::Run(wakeup) => messages.extend(run_wakeup_text(&wakeup.run).map(|text| { + let shown = text.trim_start_matches(ORX_MESSAGE_PREFIX).to_string(); + let run = &wakeup.run; + let source = source(OrxKind::Run, Some(&run.id), Some(&run.status)); + ( + text, + OrxDisplay { + text: shown, + source, + }, + ) + })), + News::Unmonitored(wakeup) => unmonitored.push(wakeup.run.clone()), + } + } + if !unmonitored.is_empty() { + messages.push(( + run_monitoring_text(&unmonitored), + OrxDisplay { + text: monitoring_lines(&unmonitored), + source: source(OrxKind::Monitoring, None, None), + }, + )); + } + Ok(messages) +} + +fn source(kind: OrxKind, from: Option<&str>, status: Option<&str>) -> OrxSource { + OrxSource { + kind, + from: from.map(str::to_string), + status: status.map(str::to_string), + } +} + +/// The answer leads, right after the line naming its chat; the transcript +/// shows the answer, or the error when there is none. +fn answer_text( + store: &Store, + ready: &ReadyChatSubscription, + model: &str, +) -> Result<(String, OrxDisplay)> { + let id = &ready.target_session_id; + let turn = store.get_chat_turn(id, &ready.turn_id)?; + let answer = answer(store, &ready.assistant_message_id)?; + let mut text = format!( + "{ORX_MESSAGE_PREFIX}Chat `{id}` ({model}) finished its turn: **{}**.", + ready.turn_state + ); + if !answer.is_empty() { + text.push_str(&format!( + " Its answer is {}:\n\n{}\n", + message_ref(&ready.assistant_message_id), + inline(&answer) + )); + } + let error = turn + .as_ref() + .and_then(|turn| turn.error_message.clone()) + .filter(|_| ready.turn_state != "completed"); + if let Some(error) = &error { + text.push_str(&format!("\nError: {error}")); + } + let user_message = turn + .and_then(|turn| turn.user_message_id) + .map(|id| store.get_chat_message(&id)) + .transpose()? + .flatten(); + if let Some(message) = user_message { + let wrote = message_text(&message); + let from_agent = stored_to_wire(&message) + .parts + .iter() + .any(|part| part.orx.is_some()); + if !from_agent && !wrote.is_empty() { + let preview: String = wrote.chars().take(USER_PREVIEW_CHARS).collect(); + text.push_str(&format!( + "\nThe user wrote this turn's message there {}: {preview}", + message_ref(&message.id) + )); + } + } + let untold = store.untold_chat_answers(ready)?; + if !untold.is_empty() { + let turns = if untold.len() == 1 { "turn" } else { "turns" }; + text.push_str(&format!( + "\n\nBefore it, the chat finished {} more {turns} you were not told of. Their answers, oldest first:", + untold.len() + )); + for id in &untold { + let earlier = super::delegation::answer(store, id)?; + if !earlier.is_empty() { + text.push_str(&format!("\n\n{}:\n\n{}", message_ref(id), inline(&earlier))); + } + } + text.push('\n'); + } + if let Some(pending) = pending_prompt(store, id)? { + let tool = pending.prompt.tool.as_deref().unwrap_or("a step"); + text.push_str(&format!( + "\nIt waits for the user to approve {tool} in that chat." + )); + } + let shown = OrxDisplay { + text: if answer.is_empty() { + error.unwrap_or_default() + } else { + inline(&answer) + }, + source: source(OrxKind::Answer, Some(id), Some(&ready.turn_state)), + }; + Ok((text.trim_end().to_string(), shown)) +} + +pub(super) fn run_wakeup_text(run: &StoredRun) -> Option { + if run.status == "lost" { + return Some(format!( + "{ORX_MESSAGE_PREFIX}Run `{}` ended with **Outcome unavailable**. Its final outcome could not be \ + collected. Inspect any partial logs using `orx logs {}`; do not assume success or failure.", + run.id, run.id + )); + } + matches!(run.status.as_str(), "done" | "failed").then(|| { + format!( + "{ORX_MESSAGE_PREFIX}Run `{}` finished with status **{}**. You can compare this result with other \ + project runs using `orx runs {}` and inspect the file located by `orx logs {}`.", + run.id, run.status, run.project_id, run.id + ) + }) +} + +// Only local identifiers here: the error text includes remote ssh stderr, so the agent reads it +// as command output instead of inside an orx message. +pub(super) fn run_monitoring_text(runs: &[StoredRun]) -> String { + let lines = monitoring_lines(runs); + format!( + "{ORX_MESSAGE_PREFIX}orx can no longer monitor these live runs:\n{lines}\nRun `orx exp status ` \ + for the reason and tell the user so they can fix it. orx wakes you once it can see a run \ + finish; until then each run keeps its current status." + ) +} + +fn monitoring_lines(runs: &[StoredRun]) -> String { + runs.iter() + .map(|run| { + format!( + "- run `{}` of experiment `{}` (still **{}**)", + run.id, run.experiment_id, run.status + ) + }) + .collect::>() + .join("\n") +} + +/// Record `target`'s latest turn as told to `subscriber`, as when it stops +/// the target itself: the stop is no news to it. +pub fn mark_told(store: &Store, subscriber: &str, target: &str) -> Result<()> { + let Some(turn) = store.latest_chat_turn(target)? else { + return Ok(()); + }; + let event = ToldEvent::Turn(&turn.id); + if let Some(token) = store.claim_chat_subscription(subscriber, target, event)? { + store.settle_chat_subscription(subscriber, target, &token, Some(event))?; + } + Ok(()) +} + +/// Starts each idle chat's next turn with all the news it is owed. A busy +/// chat keeps its news until it is idle. Nothing is told while the data +/// directory moves. +pub(super) async fn deliver_news( + chat: &Arc, + store: Store, + data_dir_move_in_progress: Option<&AtomicBool>, +) -> Result<()> { + let moving = || data_dir_move_in_progress.is_some_and(|flag| flag.load(Ordering::SeqCst)); + if moving() { + return Ok(()); + } + let mut by_chat: BTreeMap> = BTreeMap::new(); + for item in run_news(&store)? + .into_iter() + .chain(chat_news(&store, None)?) + { + // A turn's end races the host's own bookkeeping; tell it once quiet. + if matches!(item, News::Answer(_)) && chat.is_busy(item.target()).await { + continue; + } + by_chat + .entry(item.subscriber().to_string()) + .or_default() + .push(item); + } + for (session_id, items) in by_chat { + let Some(mut guard) = TurnGuard::claim_idle(chat, &session_id).await else { + continue; + }; + if moving() { + guard.release().await; + return Ok(()); + } + let mut claimed = Vec::new(); + for item in items { + if let Some(token) = item.claim(&store)? { + claimed.push((item, token)); + } + } + if claimed.is_empty() { + guard.release().await; + continue; + } + let pieces = match messages(&store, claimed.iter().map(|(item, _)| item)) { + Ok(pieces) => pieces, + Err(error) => { + guard.release().await; + for (item, token) in &claimed { + item.settle(&store, token, false)?; + } + return Err(error); + } + }; + let submitted = chat.send_orx_messages(&session_id, pieces, guard).await; + let told = matches!(submitted, Ok(TurnSubmission::Started(_))); + for (item, token) in &claimed { + item.settle(&store, token, told)?; + } + if let Err(error) = submitted { + if !chat.is_busy(&session_id).await { + eprintln!("orx up: news for {session_id}: {error}"); + } + } + } + Ok(()) +} diff --git a/src/local/claude.rs b/src/local/claude.rs index f6c2964da..6d1887268 100644 --- a/src/local/claude.rs +++ b/src/local/claude.rs @@ -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)] @@ -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`. @@ -672,10 +672,8 @@ async fn spawn_client(spec: &SpawnSpec, auth_generation: u64) -> Result { cmd.arg("--mcp-config").arg(path); config.bridge_active = gate.is_some(); @@ -695,9 +693,22 @@ async fn spawn_client(spec: &SpawnSpec, auth_generation: u64) -> Result, +) -> crate::error::Result> { + let mut servers = crate::local::acp::alphaxiv_mcp_servers()?; + let Some(server) = + up_port.and_then(|port| crate::local::chat::delegation::mcp_server(session_id, port).ok()) + else { + return Ok(servers); + }; + let env = server + .env + .iter() + .map(|(name, value)| EnvVariable::new(*name, value.clone())) + .collect(); + let args = server.args.iter().map(|arg| arg.to_string()).collect(); + servers.push(McpServer::Stdio( + McpServerStdio::new("orx", server.command) + .args(args) + .env(env), + )); + Ok(servers) +} + async fn run_turn(ctx: &mut TurnCtx, definition: &Definition) -> Result<()> { let first_session = ctx.native_session_id.is_none(); ctx.host.resolve_stale_prompts(&ctx.session_id, true)?; @@ -230,7 +257,14 @@ async fn run_turn(ctx: &mut TurnCtx, definition: &Definition) -> Result<()> { }; client.set_native_id(&native_id); if method.is_some() { - match client.restore(&native_id, &cwd).await { + match client + .restore( + &native_id, + &cwd, + orx_mcp_servers(&ctx.session_id, ctx.host.up_port())?, + ) + .await + { Ok(response) => configuration = Some(response), Err(error) if error @@ -257,7 +291,7 @@ async fn run_turn(ctx: &mut TurnCtx, definition: &Definition) -> Result<()> { .request( "session/new", NewSessionRequest::new(&cwd) - .mcp_servers(crate::local::acp::alphaxiv_mcp_servers()?), + .mcp_servers(orx_mcp_servers(&ctx.session_id, ctx.host.up_port())?), ) .await?; let native_id = response["sessionId"] diff --git a/src/local/harness/antigravity.rs b/src/local/harness/antigravity.rs index d46fbfcd2..bc3de9ab3 100644 --- a/src/local/harness/antigravity.rs +++ b/src/local/harness/antigravity.rs @@ -962,6 +962,7 @@ fn apply_event(ctx: &mut TurnCtx, state: &mut TurnState, event: &Value) -> bool prompt: None, phase: None, children: Vec::new(), + orx: None, }); } } diff --git a/src/local/harness/claude.rs b/src/local/harness/claude.rs index a7fb53d75..30f7a6f06 100644 --- a/src/local/harness/claude.rs +++ b/src/local/harness/claude.rs @@ -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. @@ -478,6 +478,10 @@ fn parse_claude_model_list(result: &Value, ultracode: bool) -> Vec { let mut info = ModelInfo::new(value) .with_reasoning(&efforts) .with_label(name, blurb); + info.resolved_model = m + .get("resolvedModel") + .and_then(Value::as_str) + .map(str::to_string); // Claude reports no default *tier* because its unset default isn't // one: with adaptive thinking, the CLI scales effort per request. // Name the sentinel row for what actually runs — preselecting a @@ -1122,9 +1126,10 @@ pub(crate) fn uses_permission_bridge(mode: Option) -> bool { /// is already git-excluded. const PLAN_SETTINGS_REL: &str = ".openresearch/agent/claude-plan-settings.json"; -/// Path (relative to the worktree) of the plan-mode MCP config wiring the -/// `orx mcp-gate` permission bridge. Same git-excluded agent dir. -const MCP_CONFIG_REL: &str = ".openresearch/agent/claude-mcp.json"; +/// Directory (relative to the worktree) of the MCP configs wiring the +/// `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"; // Attribution updates input without granting permission; plan decisions stay separate. pub(crate) fn write_settings(repo: &std::path::Path, plan: bool) -> Result { @@ -1174,9 +1179,15 @@ pub(crate) fn write_settings(repo: &std::path::Path, plan: bool) -> Result, + session_id: &str, + gate: Option<(u16, &str)>, ) -> Result { let orx = crate::paths::spawnable_exe() .map_err(|e| anyhow!("cannot resolve orx binary path for the mcp bridge: {e}"))?; @@ -1184,19 +1195,25 @@ pub(crate) fn write_mcp_config( let mut config = serde_json::json!({"mcpServers": { "alphaxiv": {"type":"stdio", "command":orx, "args":["alphaxiv-mcp"]} }}); - if let Some((up_port, session_id, token)) = gate { + if let Some((up_port, token)) = gate { config["mcpServers"]["orx"] = serde_json::json!({ - "type": "stdio", - "command": orx, - "args": ["mcp-gate"], - "env": { - "ORX_UP_PORT": up_port.to_string(), - "ORX_SESSION_ID": session_id, - "ORX_GATE_TOKEN": token, - }, + "type": "stdio", + "command": orx, + "args": ["mcp"], + // Orchestration tools are few and needed unprompted, so they + // skip tool search. + "alwaysLoad": true, + "env": { + "ORX_UP_PORT": up_port.to_string(), + "ORX_SESSION_ID": session_id, + "ORX_GATE_TOKEN": token, + "ORX_AGENT_TOKEN": crate::local::chat::delegation::agent_token(session_id), + }, }); } - let path = repo.join(MCP_CONFIG_REL); + let path = repo + .join(MCP_CONFIG_DIR_REL) + .join(format!("claude-mcp-{session_id}.json")); if let Some(parent) = path.parent() { std::fs::create_dir_all(parent) .map_err(|e| anyhow!("cannot create {}: {e}", parent.display()))?; @@ -1450,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, @@ -1575,6 +1592,7 @@ fn apply_subagent_blocks( prompt: None, phase: None, children: Vec::new(), + orx: None, }, ); } @@ -1895,6 +1913,7 @@ fn apply_event(ctx: &mut TurnCtx, state: &mut TurnState, event: &Value) -> bool prompt: None, phase: None, children: Vec::new(), + orx: None, }); } } @@ -2603,7 +2622,7 @@ mod tests { #[test] fn local_mcp_config_contains_only_string_environment_values() { let repo = std::env::temp_dir().join(format!("orx-mcp-test-{}", uuid::Uuid::new_v4())); - let path = write_mcp_config(&repo, Some((4791, "session", "gate"))).unwrap(); + let path = write_mcp_config(&repo, "session", Some((4791, "gate"))).unwrap(); let config: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); let env = config["mcpServers"]["orx"]["env"].as_object().unwrap(); @@ -2755,6 +2774,10 @@ mod tests { "Adaptive" ); assert_eq!(with[0].default_reasoning_level, None); + assert_eq!( + with[1].resolved_model.as_deref(), + Some("claude-haiku-4-5-20251001") + ); // No description → the plain displayName stands. assert_eq!(with[1].display_name.as_deref(), Some("Haiku")); assert_eq!(with[1].description, None); @@ -2855,6 +2878,7 @@ mod tests { answers: answers.iter().map(|s| s.to_string()).collect(), note: note.map(str::to_string), annotations: Vec::new(), + from: None, } } diff --git a/src/local/harness/codex.rs b/src/local/harness/codex.rs index 424ff19dc..b0615ea9d 100644 --- a/src/local/harness/codex.rs +++ b/src/local/harness/codex.rs @@ -967,7 +967,7 @@ impl Harness for Codex { }; let auto_review_supported = config_supports_auto_review(&config) && super::detect::api_key("OPENAI_BASE_URL").is_none(); - let setup = codex_thread_setup( + let mut setup = codex_thread_setup( &repo, &playbook_md, ctx.permission_mode, @@ -976,6 +976,7 @@ impl Harness for Codex { ctx.service_tier.as_deref(), &config, )?; + add_orx_server(&mut setup["config"], &ctx.session_id, ctx.host.up_port()); resume_for_compaction(&client, thread_id, &session.path, setup).await?; client } @@ -1190,7 +1191,7 @@ impl Harness for Codex { if !answer.approve { return Ok(ResumeAction::Handled { plan_mode: None }); } - let text = async_question_answer(prompt, answer)?; + let (text, shown) = answer.as_written(async_question_answer(prompt, answer)?); ctx.host .steer_message( &ctx.session_id, @@ -1199,6 +1200,7 @@ impl Harness for Codex { Vec::new(), Vec::new(), None, + shown, ) .await?; Ok(ResumeAction::Handled { plan_mode: None }) @@ -1781,6 +1783,7 @@ fn tool_part( prompt: None, phase: None, children: Vec::new(), + orx: None, } } @@ -2816,6 +2819,29 @@ async fn codex_playbook( Ok((repo, playbook_md)) } +/// Add orx's MCP server to a thread's config. Native sub-agents are off while +/// it is on: delegation goes through orx, which can reach any model. +fn add_orx_server(config: &mut Value, session_id: &str, up_port: Option) { + let Some(server) = + up_port.and_then(|port| crate::local::chat::delegation::mcp_server(session_id, port).ok()) + else { + return; + }; + let env: serde_json::Map = server + .env + .iter() + .map(|(name, value)| (name.to_string(), Value::String(value.clone()))) + .collect(); + config["mcp_servers"]["orx"] = serde_json::json!({ + "command": server.command, + "args": server.args, + "env": env, + "default_tools_approval_mode": "approve", + "tool_timeout_sec": crate::local::chat::delegation::TOOL_TIMEOUT_SECONDS as f64, + }); + config["features"] = serde_json::json!({"multi_agent": false, "multi_agent_v2": false}); +} + /// Both a normal turn and idle compaction restore the same thread settings. fn codex_thread_setup( repo: &Path, @@ -2893,6 +2919,11 @@ async fn run_turn_app_server(ctx: &mut TurnCtx) -> Result<()> { ctx.service_tier.as_deref(), &config, )?; + add_orx_server( + &mut thread_setup["config"], + &ctx.session_id, + ctx.host.up_port(), + ); if ctx.reset_codex_model { // Codex keeps the old thread model when a turn omits its model override. append_native_recovery_context(ctx, &mut thread_setup); @@ -4245,6 +4276,7 @@ async fn run_turn_exec(ctx: &mut TurnCtx) -> Result<()> { prompt: None, phase: None, children: Vec::new(), + orx: None, }); } "exec_command_end" => { @@ -4372,6 +4404,7 @@ fn handle_item(ctx: &mut TurnCtx, item: &Value, next_id: &mut impl FnMut(&str) - prompt: None, phase: None, children: Vec::new(), + orx: None, }); } _ => {} @@ -6239,6 +6272,7 @@ requires_openai_auth = false answers: answers.iter().map(|s| s.to_string()).collect(), note: note.map(str::to_string), annotations: Vec::new(), + from: None, } } diff --git a/src/local/harness/cursor.rs b/src/local/harness/cursor.rs index b343e60dc..be4df9735 100644 --- a/src/local/harness/cursor.rs +++ b/src/local/harness/cursor.rs @@ -1005,6 +1005,7 @@ fn apply_tool_call(ctx: &mut TurnCtx, state: &mut TurnState, event: &Value) { prompt: None, phase: None, children: Vec::new(), + orx: None, }); } "completed" => { @@ -1037,6 +1038,7 @@ fn apply_tool_call(ctx: &mut TurnCtx, state: &mut TurnState, event: &Value) { prompt: None, phase: None, children: Vec::new(), + orx: None, }); } } @@ -1560,6 +1562,7 @@ ActionRequiredError: Named models unavailable Free plans can only use Auto. Swit note: None, resume_mode: None, annotations: Vec::new(), + from: None, }, ) .await @@ -1588,6 +1591,7 @@ ActionRequiredError: Named models unavailable Free plans can only use Auto. Swit note: None, resume_mode: None, annotations: Vec::new(), + from: None, }, ) .await diff --git a/src/local/harness/detect.rs b/src/local/harness/detect.rs index d321cbbbd..c3884d0d6 100644 --- a/src/local/harness/detect.rs +++ b/src/local/harness/detect.rs @@ -161,6 +161,10 @@ pub struct ModelInfo { /// Whether the model accepts image input, when the catalog says (OpenCode). #[serde(skip_serializing_if = "Option::is_none")] pub image_input: Option, + /// The versioned model an unversioned alias runs today (Claude's + /// `opus[1m]` → `claude-opus-5-5`), which model routing joins on. + #[serde(skip_serializing_if = "Option::is_none")] + pub resolved_model: Option, } impl ModelInfo { @@ -175,6 +179,7 @@ impl ModelInfo { default_reasoning_level: None, service_tiers: None, image_input: None, + resolved_model: None, } } diff --git a/src/local/harness/mod.rs b/src/local/harness/mod.rs index 4d7cd007c..5a1a516be 100644 --- a/src/local/harness/mod.rs +++ b/src/local/harness/mod.rs @@ -51,7 +51,7 @@ pub(crate) use detect::{ ProbeTiming, ProbeTimingSink, }; pub use detect::{HarnessAuthState, HarnessInfo, ModelInfo}; -pub use options::{HarnessOptions, PermissionMode}; +pub use options::{HarnessOptions, PermissionMode, REASONING_DEFAULT_ID}; pub use plan_gate::command_is_readonly; pub use plan_gate::decide as plan_gate_decide; diff --git a/src/local/harness/opencode.rs b/src/local/harness/opencode.rs index e17fddae1..e6d4be1d5 100644 --- a/src/local/harness/opencode.rs +++ b/src/local/harness/opencode.rs @@ -1054,6 +1054,7 @@ pub(crate) fn to_wire_part(part: &Value) -> Option { prompt: None, phase: None, children: Vec::new(), + orx: None, }), "tool" => { let state = part.get("state"); @@ -1085,6 +1086,7 @@ pub(crate) fn to_wire_part(part: &Value) -> Option { prompt: None, phase: None, children: Vec::new(), + orx: None, }) } _ => None, @@ -2721,6 +2723,7 @@ opencode/unknown answers: values.iter().map(|s| s.to_string()).collect(), note: note.map(str::to_owned), annotations: Vec::new(), + from: None, }; let mut saved = Vec::new(); for (index, response) in [ @@ -2778,6 +2781,7 @@ opencode/unknown answers: vec![choice.into()], note: None, annotations: Vec::new(), + from: None, }; assert_eq!(plan_exit_transition(&prompt, &response("Yes")), Some(false)); assert_eq!(plan_exit_transition(&prompt, &response("No")), Some(true)); diff --git a/src/local/harness/opencode_v2.rs b/src/local/harness/opencode_v2.rs index 4348fdd57..31bb30f05 100644 --- a/src/local/harness/opencode_v2.rs +++ b/src/local/harness/opencode_v2.rs @@ -1094,6 +1094,7 @@ mod tests { answers: Vec::new(), note: None, annotations: Vec::new(), + from: None, }; reply(&ctx, &endpoint, &prompt, &answer).await.unwrap(); } @@ -1149,6 +1150,7 @@ mod tests { answers: Vec::new(), note: Some("Skipped".into()), annotations: Vec::new(), + from: None, }; let result = reply(&ctx, &endpoint, &prompt, &answer).await; server.abort(); diff --git a/src/local/harness/plan_gate.rs b/src/local/harness/plan_gate.rs index afd5fc408..eae2bddd9 100644 --- a/src/local/harness/plan_gate.rs +++ b/src/local/harness/plan_gate.rs @@ -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 { diff --git a/src/local/mod.rs b/src/local/mod.rs index f7359b3c8..c46a53769 100644 --- a/src/local/mod.rs +++ b/src/local/mod.rs @@ -31,6 +31,7 @@ pub mod local_models; pub mod localrun; pub mod modal; pub mod model; +pub mod model_routes; pub mod native_chats; pub mod native_store; pub mod opencode; diff --git a/src/local/model_routes.rs b/src/local/model_routes.rs new file mode 100644 index 000000000..6197e8035 --- /dev/null +++ b/src/local/model_routes.rs @@ -0,0 +1,343 @@ +//! Model-first routing for delegated chats. +//! +//! An agent names a versioned model (`claude-opus-5.5`); orx finds every way +//! the user can run it — a route is one harness plus that harness's own model +//! id — and picks one by a default order unless the caller names a route. +//! The same model is spelled differently per route (`opus[1m]`, +//! `openrouter/anthropic/claude-opus-5.5`, `opencode/claude-opus-5-5`), so +//! routes are joined on a canonical id derived from each native id. + +use serde_json::Value; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Route { + /// What the agent names: the OpenCode provider, else the harness id. + pub name: String, + pub harness: String, + /// The harness's own model id, stored as the chat's model. + pub model: String, + pub free: bool, + /// The effort levels this route takes, as the chat's reasoning level. + pub efforts: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Model { + pub id: String, + /// Default order first. + pub routes: Vec, +} + +/// Aggregators resell other providers' models and come last by default. +const AGGREGATORS: &[&str] = &["openrouter"]; + +/// The provider-neutral id of a native model id: vendor prefixes, dated +/// snapshots, `-free` and context suffixes are route properties, and version +/// digits join with `.` whichever separator the route used. +pub fn canonical(id: &str) -> String { + let id = id.rsplit('/').next().unwrap_or(id); + let id = id + .split('[') + .next() + .unwrap_or(id) + .trim() + .to_ascii_lowercase(); + let mut parts: Vec<&str> = id.split('-').collect(); + if parts.len() > 1 && parts.last() == Some(&"free") { + parts.pop(); + } + let snapshot = |part: &&str| part.len() >= 4 && part.bytes().all(|b| b.is_ascii_digit()); + if parts.len() > 1 && parts.last().is_some_and(snapshot) { + parts.pop(); + } + let mut joined: Vec = Vec::new(); + for part in parts { + let numeric = !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit()); + match joined.last_mut() { + Some(version) + if numeric + && version.starts_with(|c: char| c.is_ascii_digit()) + && version.bytes().all(|b| b.is_ascii_digit() || b == b'.') => + { + version.push('.'); + version.push_str(part); + } + _ => joined.push(part.to_string()), + } + } + joined.join("-") +} + +/// Lower is preferred: the vendor's own harness, then flat-rate OpenCode +/// plans, direct APIs, other harnesses, and aggregators last. +fn rank(model: &str, route: &Route) -> u8 { + let first_party = match route.harness.as_str() { + "claude-code" => model.starts_with("claude-"), + "codex" => model.starts_with("gpt-"), + _ => false, + }; + if first_party { + return 0; + } + if route.harness != "opencode" { + return 4; + } + match route.name.as_str() { + "opencode-go" => 1, + "opencode" => 2, + name if AGGREGATORS.contains(&name) => 5, + _ => 3, + } +} + +/// The route name an agent passes back for a harness. ACP agents are known by +/// a slug of their name, since their ids are opaque; a slug another harness +/// already took keeps the id. +fn harness_route_name(harness: &Value, id: &str, taken: &[String]) -> String { + if !id.starts_with("acp:") { + return id.to_string(); + } + let name = harness.get("name").and_then(Value::as_str).unwrap_or(id); + let slug = name + .to_ascii_lowercase() + .split(|c: char| !c.is_ascii_alphanumeric()) + .filter(|word| !word.is_empty()) + .collect::>() + .join("-"); + if slug.is_empty() || taken.contains(&slug) { + id.to_string() + } else { + slug + } +} + +/// Every model the ready harnesses in a `/api/harnesses` payload can run. +pub fn models(catalog: &Value) -> Vec { + let mut models: Vec = Vec::new(); + let mut harness_names: Vec = Vec::new(); + let harnesses = catalog.get("harnesses").and_then(Value::as_array); + for harness in harnesses.into_iter().flatten() { + if harness.get("agentReady").and_then(Value::as_bool) != Some(true) { + continue; + } + let Some(harness_id) = harness.get("id").and_then(Value::as_str) else { + continue; + }; + let harness_name = harness_route_name(harness, harness_id, &harness_names); + harness_names.push(harness_name.clone()); + let entries = harness.get("models").and_then(Value::as_array); + for entry in entries.into_iter().flatten() { + let Some(native) = entry.get("id").and_then(Value::as_str) else { + continue; + }; + let resolved = entry.get("resolvedModel").and_then(Value::as_str); + let id = canonical(resolved.unwrap_or(native)); + let name = match harness_id { + "opencode" => native.split('/').next().unwrap_or(native), + _ => harness_name.as_str(), + }; + let efforts = entry + .get("reasoningLevels") + .or_else(|| harness.pointer("/options/reasoningLevels")) + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(|level| level.get("id").and_then(Value::as_str)) + .filter(|id| *id != crate::local::harness::REASONING_DEFAULT_ID) + .map(str::to_string) + .collect(); + let route = Route { + name: name.to_string(), + harness: harness_id.to_string(), + model: native.to_string(), + free: native.ends_with("-free"), + efforts, + }; + let index = match models.iter().position(|model| model.id == id) { + Some(index) => index, + None => { + models.push(Model { + id, + routes: Vec::new(), + }); + models.len() - 1 + } + }; + let routes = &mut models[index].routes; + match routes + .iter_mut() + .find(|existing| existing.name == route.name) + { + // A paid listing beats the same provider's free tier. + Some(existing) if existing.free && !route.free => *existing = route, + Some(_) => {} + None => routes.push(route), + } + } + } + for model in &mut models { + let id = model.id.clone(); + model.routes.sort_by_key(|route| rank(&id, route)); + } + models.sort_by(|a, b| a.id.cmp(&b.id)); + models +} + +/// The route a delegate runs on. Errors are written for the calling agent. +pub fn resolve(models: &[Model], id: &str, route: Option<&str>) -> Result { + let wanted = canonical(id); + let Some(model) = models.iter().find(|model| model.id == wanted) else { + let query = id.trim().to_ascii_lowercase(); + let similar: Vec<&str> = models + .iter() + .map(|model| model.id.as_str()) + .filter(|candidate| candidate.contains(&query) || query.contains(*candidate)) + .collect(); + return Err(if similar.is_empty() { + format!("No route can run `{id}`. Call `models` for the versioned models available.") + } else { + format!("Name a versioned model: {}.", similar.join(", ")) + }); + }; + match route { + None => Ok(model.routes[0].clone()), + Some(name) => model + .routes + .iter() + .find(|candidate| candidate.name == name) + .cloned() + .ok_or_else(|| { + let names: Vec<&str> = model.routes.iter().map(|r| r.name.as_str()).collect(); + format!("`{}` runs only on: {}.", model.id, names.join(", ")) + }), + } +} + +/// One line per model, routes in default order, for the agent to read. +pub fn listing(models: &[Model]) -> String { + models + .iter() + .map(|model| { + let routes: Vec = model + .routes + .iter() + .map(|route| { + if route.free { + format!("{} (free)", route.name) + } else { + route.name.clone() + } + }) + .collect(); + let efforts = &model.routes[0].efforts; + if efforts.is_empty() { + format!("{} {}", model.id, routes.join(" · ")) + } else { + format!( + "{} {} effort: {}", + model.id, + routes.join(" · "), + efforts.join(" ") + ) + } + }) + .collect::>() + .join("\n") +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn routes_spell_one_model_differently() { + for (native, id) in [ + ("claude-opus-5-5", "claude-opus-5.5"), + ("anthropic/claude-opus-5.5", "claude-opus-5.5"), + ("openrouter/anthropic/claude-opus-5.5", "claude-opus-5.5"), + ("claude-haiku-4-5-20251001", "claude-haiku-4.5"), + ("claude-fable-5[1m]", "claude-fable-5"), + ("gpt-6.1-sol", "gpt-6.1-sol"), + ("opencode/deepseek-v4.1-flash-free", "deepseek-v4.1-flash"), + ("deepseek/deepseek-v4-pro-0813", "deepseek-v4-pro"), + ( + "moonshotai/kimi-k3.1-pro-highspeed", + "kimi-k3.1-pro-highspeed", + ), + ("meta/llama-3-1-70b", "llama-3.1-70b"), + ] { + assert_eq!(canonical(native), id, "{native}"); + } + } + + fn catalog() -> Value { + json!({"harnesses": [ + {"id": "claude-code", "agentReady": true, + "options": {"reasoningLevels": [{"id": "default"}, {"id": "low"}, {"id": "max"}]}, + "models": [{"id": "opus[1m]", "resolvedModel": "claude-opus-5-5"}]}, + {"id": "codex", "agentReady": true, + "options": {"reasoningLevels": [{"id": "default"}, {"id": "low"}]}, + "models": [{"id": "gpt-6-luna", "reasoningLevels": [{"id": "high"}, {"id": "xhigh"}]}]}, + {"id": "opencode", "agentReady": true, "models": [ + {"id": "openrouter/anthropic/claude-opus-5.5"}, + {"id": "opencode/deepseek-v4.1-flash-free"}, + {"id": "opencode-go/deepseek-v4.1-flash"}, + {"id": "opencode/gpt-6-luna"}, + ]}, + {"id": "cursor", "agentReady": false, "models": [{"id": "claude-opus-5-5"}]}, + {"id": "acp:1", "name": "OpenCode (ACP)", "agentReady": true, "models": [ + {"id": "opencode/deepseek-v4.1-flash-free"}, + ]}, + {"id": "acp:2", "name": "opencode acp", "agentReady": true, "models": [ + {"id": "opencode/deepseek-v4.1-flash-free"}, + ]}, + ]}) + } + + #[test] + fn default_order_prefers_the_vendor_harness_then_plans_then_aggregators() { + let models = models(&catalog()); + let names = |id: &str| -> Vec { + let model = models.iter().find(|model| model.id == id).unwrap(); + model + .routes + .iter() + .map(|route| route.name.clone()) + .collect() + }; + assert_eq!(names("claude-opus-5.5"), ["claude-code", "openrouter"]); + assert_eq!( + names("deepseek-v4.1-flash"), + ["opencode-go", "opencode", "opencode-acp", "acp:2"] + ); + assert_eq!(names("gpt-6-luna"), ["codex", "opencode"]); + let listing = listing(&models); + assert!(listing + .contains("deepseek-v4.1-flash opencode-go · opencode (free) · opencode-acp (free)")); + assert!( + listing.contains("gpt-6-luna codex · opencode effort: high xhigh"), + "a model's own levels beat its harness's" + ); + assert!(listing.contains("claude-opus-5.5 claude-code · openrouter effort: low max")); + } + + #[test] + fn resolution_translates_to_the_route_and_asks_for_a_version() { + let models = models(&catalog()); + let route = resolve(&models, "claude-opus-5.5", None).unwrap(); + assert_eq!( + (route.harness.as_str(), route.model.as_str()), + ("claude-code", "opus[1m]") + ); + let route = resolve(&models, "claude-opus-5.5", Some("openrouter")).unwrap(); + assert_eq!(route.model, "openrouter/anthropic/claude-opus-5.5"); + assert_eq!( + resolve(&models, "deepseek", None).unwrap_err(), + "Name a versioned model: deepseek-v4.1-flash." + ); + assert!(resolve(&models, "claude-opus-5.5", Some("codex")) + .unwrap_err() + .contains("claude-code, openrouter")); + } +} diff --git a/src/local/opencode.rs b/src/local/opencode.rs index de7fdaf6e..684c9919b 100644 --- a/src/local/opencode.rs +++ b/src/local/opencode.rs @@ -90,10 +90,13 @@ pub fn agent_log_path() -> PathBuf { } /// Chat-server config; native questions are answered through the dashboard. +/// With orx's MCP server present, native sub-agents are off: delegation goes +/// through orx, which can reach any model. fn opencode_config_json( model: Option<&str>, instructions: &str, plugin: Option<&str>, + mcp: Option<&crate::local::chat::delegation::McpServer>, ) -> Result { let mut cfg = json!({ "$schema": "https://opencode.ai/config.json", @@ -125,6 +128,24 @@ fn opencode_config_json( for tool in crate::commands::alphaxiv_mcp::WRITE_TOOLS { cfg["permission"][format!("orx_alphaxiv_{tool}")] = json!("ask"); } + if let Some(server) = mcp { + // Side chats and delegates share this file with their parent's + // worktree, so it names the env vars and each chat's serve child + // supplies its own values (OpenCode substitutes `{env:…}`). + let environment: serde_json::Map = server + .env + .iter() + .map(|(name, _)| (name.to_string(), json!(format!("{{env:{name}}}")))) + .collect(); + cfg["mcp"]["orx"] = json!({ + "type": "local", + "command": [server.command.as_str(), server.args[0]], + "environment": environment, + "enabled": true, + "timeout": crate::local::chat::delegation::TOOL_TIMEOUT_SECONDS * 1000, + }); + cfg["permission"]["task"] = json!("deny"); + } Ok(serde_json::to_string_pretty(&cfg)?) } @@ -356,6 +377,7 @@ fn write_agent_files( project: &LocalProject, model: Option<&str>, session_id: &str, + up_port: Option, protocol: Protocol, ) -> Result<(PathBuf, Option)> { // Source of truth for the session-skills dir is the harness trait. @@ -373,6 +395,9 @@ fn write_agent_files( } else { None }; + let mcp = up_port + .map(|port| crate::local::chat::delegation::mcp_server(session_id, port)) + .transpose()?; let config_override = if git::is_tracked(&repo, "opencode.json") { // Out-of-root config: absolute instructions path (no root to anchor it). let path = repo @@ -381,14 +406,19 @@ fn write_agent_files( .join("opencode.json"); std::fs::write( &path, - opencode_config_json(model, &playbook.to_string_lossy(), plugin.as_deref())?, + opencode_config_json( + model, + &playbook.to_string_lossy(), + plugin.as_deref(), + mcp.as_ref(), + )?, ) .map_err(|e| anyhow!("Could not write {}: {}", path.display(), e))?; Some(path) } else { std::fs::write( repo.join("opencode.json"), - opencode_config_json(model, PLAYBOOK_REL, plugin.as_deref())?, + opencode_config_json(model, PLAYBOOK_REL, plugin.as_deref(), mcp.as_ref())?, ) .map_err(|e| anyhow!("Could not write opencode.json: {}", e))?; None @@ -456,7 +486,7 @@ async fn spawn_agent( let session = session_id.to_string(); let protocol = binary.protocol; tokio::task::spawn_blocking(move || { - write_agent_files(&project, model.as_deref(), &session, protocol) + write_agent_files(&project, model.as_deref(), &session, up_port, protocol) }) .await .map_err(|e| anyhow!("agent file task failed: {e}"))?? @@ -477,6 +507,11 @@ async fn spawn_agent( // be explicitly subscribed to. One serve child per session; set after the // synced-env loop so it isn't shadowed. crate::local::chat::set_chat_session_env(&mut cmd, session_id, "opencode", up_port); + if let Some(port) = up_port { + for (name, value) in crate::local::chat::delegation::mcp_server(session_id, port)?.env { + cmd.env(name, value); + } + } if let Some(config) = &config_override { // The repo tracks its own opencode.json; ours rides OPENCODE_CONFIG. // Project configs load after OPENCODE_CONFIG and would override our @@ -993,7 +1028,7 @@ mod tests { #[test] fn alphaxiv_server_has_its_own_name_and_asks_before_writes() { let cfg: Value = - serde_json::from_str(&opencode_config_json(None, "p.md", None).unwrap()).unwrap(); + serde_json::from_str(&opencode_config_json(None, "p.md", None, None).unwrap()).unwrap(); assert!(cfg["mcp"].get("alphaxiv").is_none()); assert_eq!(cfg["mcp"]["orx_alphaxiv"]["command"][1], "alphaxiv-mcp"); assert_eq!(cfg["permission"]["orx_alphaxiv_*"], "allow"); @@ -1004,6 +1039,23 @@ mod tests { ); } + #[test] + fn shared_config_names_the_orx_server_env_without_any_chats_values() { + let server = crate::local::chat::delegation::mcp_server("chat_a", 4900).unwrap(); + let config: Value = + serde_json::from_str(&opencode_config_json(None, "p.md", None, Some(&server)).unwrap()) + .unwrap(); + let environment = &config["mcp"]["orx"]["environment"]; + assert_eq!(environment["ORX_SESSION_ID"], "{env:ORX_SESSION_ID}"); + assert_eq!(environment["ORX_AGENT_TOKEN"], "{env:ORX_AGENT_TOKEN}"); + assert!(!config.to_string().contains("chat_a")); + assert_eq!(config["permission"]["task"], "deny"); + let without: Value = + serde_json::from_str(&opencode_config_json(None, "p.md", None, None).unwrap()).unwrap(); + assert_eq!(without["permission"]["task"], "allow"); + assert!(without["mcp"].get("orx").is_none()); + } + #[test] fn resident_selection_keeps_cloud_session_ahead_of_host_default() { let host = AgentHost::new(Some("host/default".into())); diff --git a/src/main.rs b/src/main.rs index 569e9a461..a6aa9c96a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -80,9 +80,6 @@ enum Command { /// Operate on one local project. Project(ProjectArgs), - /// Create independent project chats. - Agent(AgentArgs), - /// List a project's runs. Runs(RunsArgs), @@ -175,12 +172,12 @@ enum Command { #[command(name = "invocation-gate", hide = true)] InvocationGate, - /// Internal: the plan-mode permission bridge. A stdio MCP server Claude - /// Code spawns (`--mcp-config`) and consults (`--permission-prompt-tool`); - /// relays each permission request to the running `orx up`, which surfaces - /// an approval card and blocks until answered. Not a user command. - #[command(name = "mcp-gate", hide = true)] - McpGate, + /// Internal: orx's stdio MCP server, which every agent harness spawns: + /// Claude's permission bridge and the orchestration tools, relayed to the + /// running `orx up`. `mcp-gate`, its old name, stays for configs an older + /// `orx up` still writes. Not a user command. + #[command(name = "mcp", alias = "mcp-gate", hide = true)] + Mcp, #[command(name = "alphaxiv-mcp", hide = true)] AlphaxivMcp, @@ -424,33 +421,6 @@ pub struct InstanceDeleteArgs { pub sandbox_id: String, } -#[derive(Args, Debug)] -pub struct AgentArgs { - #[command(subcommand)] - pub command: AgentCommand, -} - -#[derive(Subcommand, Debug)] -pub enum AgentCommand { - /// Create an independent chat using your saved New Chat settings. - #[command( - after_help = "New chats use your saved New Chat settings. --harness, --model, and --no-wake are no longer supported; created chats never wake the creator." - )] - Spawn { - /// Opening message for the new chat; it starts with an empty transcript. - task: Option, - /// Read the task from stdin instead, for long multi-paragraph briefs. - #[arg(long)] - stdin: bool, - /// Name the session in the sidebar. Defaults to an auto-generated title. - #[arg(long)] - title: Option, - /// Project ID (defaults to the current OpenResearch chat's project). - #[arg(long)] - project: Option, - }, -} - #[derive(Args, Debug)] pub struct ExpArgs { #[command(subcommand)] @@ -1025,19 +995,6 @@ pub struct PaperArgs { pub full: bool, } -fn explain_removed_spawn_flags(mut error: clap::Error) -> clap::Error { - use clap::error::{ContextKind, ContextValue, ErrorKind}; - if error.kind() == ErrorKind::UnknownArgument - && error.to_string().contains(" agent spawn") - && matches!(error.get(ContextKind::InvalidArg), Some(ContextValue::String(flag)) if ["--harness", "--model", "--no-wake"].contains(&flag.split('=').next().unwrap_or(flag))) - { - error.insert(ContextKind::Suggested, ContextValue::StyledStrs(vec![ - "New chats use your saved New Chat settings and never wake the creator. Configure the agent and model in OpenResearch.".into() - ])); - } - error -} - // The default multi-thread runtime is load-bearing for desktop app mode: it // blocks the main thread in the window's run loop while the dashboard server runs // on worker threads. A `current_thread` flavor would deadlock. See commands::app. @@ -1101,7 +1058,7 @@ async fn main() { return; } - let cli = Cli::try_parse().unwrap_or_else(|error| explain_removed_spawn_flags(error).exit()); + let cli = Cli::parse(); // Double-clicked from Explorer: open the desktop app instead of a console session. #[cfg(windows)] if cli.command.is_none() && owns_its_console() { @@ -1140,11 +1097,11 @@ async fn main() { } return; } - // `mcp-gate` is Claude's stdio MCP child for the turn: stdout is the MCP + // `orx mcp` is the agent's stdio MCP child for the turn: stdout is the MCP // channel (nothing else may write to it) and startup must be instant or // Claude times the server out — skip the update check and telemetry. if matches!(command, Command::AntigravityGate) { - if let Err(error) = commands::mcp_gate::run_antigravity().await { + if let Err(error) = commands::mcp::run_antigravity().await { eprintln!("orx antigravity-gate: {error}"); std::process::exit(1); } @@ -1157,10 +1114,10 @@ async fn main() { } return; } - if matches!(command, Command::McpGate) { - if let Err(err) = commands::mcp_gate::run().await { + if matches!(command, Command::Mcp) { + if let Err(err) = commands::mcp::run().await { // stderr only; a failed bridge degrades plan mode, never the CLI. - eprintln!("orx mcp-gate: {err}"); + eprintln!("orx mcp: {err}"); std::process::exit(1); } return; @@ -1367,7 +1324,6 @@ fn command_name(command: &Command) -> &'static str { Command::Projects(_) => "projects", Command::Orgs(_) => "orgs", Command::Project(_) => "project", - Command::Agent(_) => "agent", Command::Runs(_) => "runs", Command::Logs(_) => "logs", Command::Tensorboard(_) => "tensorboard", @@ -1395,7 +1351,7 @@ fn command_name(command: &Command) -> &'static str { Command::Feedback(_) => "feedback", Command::PlanGate => "plan-gate", Command::InvocationGate => "invocation-gate", - Command::McpGate => "mcp-gate", + Command::Mcp => "mcp", Command::AlphaxivMcp => "alphaxiv-mcp", Command::AntigravityGate => "antigravity-gate", Command::PublishBranch(_) => "publish-branch", @@ -1423,7 +1379,6 @@ async fn dispatch(command: Command) -> error::Result<()> { Command::Projects(args) => commands::projects::run(args).await, Command::Orgs(args) => commands::orgs::run(args).await, Command::Project(args) => commands::project::run(args).await, - Command::Agent(args) => commands::agent::run(args).await, Command::Runs(args) => commands::runs::run(args).await, Command::Logs(args) => commands::logs::run(args).await, Command::Tensorboard(args) => commands::tensorboard::run(args).await, @@ -1458,8 +1413,8 @@ async fn dispatch(command: Command) -> error::Result<()> { // Handled before dispatch (fast path, no telemetry/update check). Command::PlanGate => commands::plan_gate::run().await, Command::InvocationGate => commands::invocation_gate::run().await, - Command::McpGate => commands::mcp_gate::run().await, - Command::AntigravityGate => commands::mcp_gate::run_antigravity().await, + Command::Mcp => commands::mcp::run().await, + Command::AntigravityGate => commands::mcp::run_antigravity().await, Command::AlphaxivMcp => unreachable!("handled before dispatch"), Command::PublishBranch(_) => unreachable!("handled before dispatch"), Command::RemoteHost(_) => unreachable!("handled before dispatch"), @@ -1482,7 +1437,7 @@ fn command_uses_lifecycle_lock(command: &Command) -> bool { | Command::PlanGate | Command::InvocationGate | Command::AlphaxivMcp - | Command::McpGate + | Command::Mcp | Command::AntigravityGate | Command::PublishBranch(_) | Command::RemoteHost(_) @@ -1579,21 +1534,6 @@ mod cli_tests { } } - #[test] - fn agent_spawn_rejects_removed_settings_flags() { - for program in ["orx", "orx.exe"] { - for flag in ["--harness", "--model", "--model=legacy", "--no-wake"] { - let error = Cli::try_parse_from([program, "agent", "spawn", "task", flag]) - .expect_err("removed flag"); - assert_eq!(error.kind(), clap::error::ErrorKind::UnknownArgument); - assert!(explain_removed_spawn_flags(error) - .to_string() - .contains("saved New Chat settings")); - } - } - assert!(Cli::try_parse_from(["orx", "agent", "spawn", "task", "--project", "p1"]).is_ok()); - } - #[test] fn run_accepts_only_supervised_backend_flags() { for flag in ["--gpu", "--cpu", "--sandbox"] { diff --git a/src/store.rs b/src/store.rs index 4380f56d7..6441eb6f1 100644 --- a/src/store.rs +++ b/src/store.rs @@ -418,6 +418,67 @@ pub enum RunWakeupRegistration { AlreadyDelivered, } +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Delegation { + pub depth: u32, + /// The chat that delegated to this one; `None` for a chat the user started. + pub parent: Option, + pub may_delegate: bool, +} + +/// One chat's standing request to hear from another. A paused one, which the +/// user stopped, tells nothing. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ChatSubscription { + pub subscriber_session_id: String, + pub target_session_id: String, + pub paused: bool, + pub told_prompt_id: Option, + /// The target is working, or idle after a turn the subscriber was not told. + pub outstanding: bool, +} + +/// What a subscription tells: a finished turn, or a question its target asked. +#[derive(Debug, Clone, Copy)] +pub enum ToldEvent<'a> { + Turn(&'a str), + Prompt(&'a str), +} + +/// A chat whose latest turn has ended since its subscriber was last told. +#[derive(Debug, Clone)] +pub struct ReadyChatSubscription { + pub subscriber_session_id: String, + pub target_session_id: String, + pub turn_id: String, + pub turn_state: String, + pub assistant_message_id: String, + subscribed_at: i64, + told_turn_id: Option, +} + +/// Each subscription with its target's latest turn and whether the target is +/// idle after it: done, and with nothing queued unless a stop held the queue. +const LATEST_SUBSCRIBED_TURNS: &str = "subscribed AS ( + SELECT s.subscriber_session_id, s.target_session_id, s.paused, s.told_turn_id, + s.told_prompt_id, s.claim_token, s.claimed_at, s.created_at, + t.id AS turn_id, t.state, + t.assistant_message_id, t.updated_at, + t.state = 'interrupted' + OR (t.state IN ('completed', 'failed') AND NOT EXISTS ( + SELECT 1 FROM chat_queued_messages q + WHERE q.session_id = s.target_session_id + )) AS idle + FROM chat_subscriptions s + LEFT JOIN chat_turns t ON t.id = ( + SELECT id FROM chat_turns WHERE session_id = s.target_session_id + ORDER BY created_at DESC, rowid DESC LIMIT 1 + ) +), +latest AS ( + SELECT *, NOT (idle IS 1 AND told_turn_id IS turn_id) AS pending FROM subscribed +)"; + const RUN_WAKEUP_CLAIM_TTL_MS: i64 = 60 * 1000; pub(crate) const CHAT_TURN_LEASE_TTL_MS: i64 = 60 * 1000; @@ -853,6 +914,25 @@ impl Store { ); CREATE INDEX IF NOT EXISTS idx_chat_run_wakeups_requested ON chat_run_wakeups(requested_at); + CREATE TABLE IF NOT EXISTS chat_delegates ( + session_id TEXT PRIMARY KEY, + parent_session_id TEXT NOT NULL, + may_delegate INTEGER NOT NULL, + created_at INTEGER NOT NULL + ); + CREATE TABLE IF NOT EXISTS chat_subscriptions ( + subscriber_session_id TEXT NOT NULL, + target_session_id TEXT NOT NULL, + created_at INTEGER NOT NULL, + paused INTEGER NOT NULL DEFAULT 0, + told_turn_id TEXT, + told_prompt_id TEXT, + claim_token TEXT, + claimed_at INTEGER, + PRIMARY KEY (subscriber_session_id, target_session_id) + ); + CREATE INDEX IF NOT EXISTS idx_chat_subscriptions_target + ON chat_subscriptions(target_session_id); CREATE TABLE IF NOT EXISTS chat_turn_leases ( chat_session_id TEXT PRIMARY KEY, claim_token TEXT NOT NULL, @@ -955,6 +1035,7 @@ impl Store { "ALTER TABLE ui_state ADD COLUMN preferred_service_tier TEXT", "ALTER TABLE ui_state ADD COLUMN workspace_state_json TEXT", "ALTER TABLE ui_state ADD COLUMN preferred_autonomy TEXT", + "ALTER TABLE ui_state ADD COLUMN nested_delegation INTEGER NOT NULL DEFAULT 0", "ALTER TABLE chat_messages ADD COLUMN completed_at INTEGER", "ALTER TABLE runs ADD COLUMN cancel_reason TEXT", ] { @@ -968,6 +1049,9 @@ impl Store { conn.execute_batch("CREATE TRIGGER IF NOT EXISTS delete_chat_steer_receipts AFTER DELETE ON chat_sessions BEGIN DELETE FROM chat_steer_receipts WHERE session_id = OLD.id; END;")?; conn.execute_batch("CREATE TRIGGER IF NOT EXISTS delete_chat_invocation_identities AFTER DELETE ON chat_sessions BEGIN DELETE FROM native_invocation_identities WHERE session_id = OLD.id; END;")?; conn.execute_batch("CREATE TRIGGER IF NOT EXISTS delete_acp_session AFTER DELETE ON chat_sessions BEGIN DELETE FROM acp_sessions WHERE session_id = OLD.id; END;")?; + conn.execute_batch("CREATE TRIGGER IF NOT EXISTS delete_chat_subscriptions AFTER DELETE ON chat_sessions BEGIN DELETE FROM chat_subscriptions WHERE subscriber_session_id = OLD.id OR target_session_id = OLD.id; END;")?; + // A delegate that outlives its delegator, in a worktree of its own, stands as the user's. + conn.execute_batch("CREATE TRIGGER IF NOT EXISTS delete_chat_delegates AFTER DELETE ON chat_sessions BEGIN DELETE FROM chat_delegates WHERE session_id = OLD.id OR parent_session_id = OLD.id; END;")?; conn.execute( "DELETE FROM native_invocation_identities WHERE session_id IS NULL AND created_at < ?1", [now_ms() - 7 * 24 * 60 * 60 * 1000], @@ -1198,7 +1282,7 @@ impl Store { "SELECT onboarding_completed, tour_completed, preferred_harness, preferred_model, preferred_service_tier, preferred_permission_mode, preferred_reasoning_level, workspace_state_json, - preferred_autonomy + preferred_autonomy, nested_delegation FROM ui_state WHERE id = 1", [], |row| { @@ -1225,6 +1309,7 @@ impl Store { .get::<_, Option>(8)? .as_deref() .and_then(Autonomy::from_id), + nested_delegation: row.get(9)?, }) }, )?) @@ -1276,6 +1361,14 @@ impl Store { Ok(()) } + pub fn set_nested_delegation(&self, allowed: bool) -> Result<()> { + self.conn.execute( + "UPDATE ui_state SET nested_delegation = ?1 WHERE id = 1", + params![allowed], + )?; + Ok(()) + } + pub fn set_preferred_autonomy(&self, autonomy: Autonomy) -> Result<()> { self.conn.execute( "UPDATE ui_state SET preferred_autonomy = ?1 WHERE id = 1", @@ -1583,21 +1676,6 @@ impl Store { Ok((claimed == 1).then_some(token)) } - pub fn renew_run_wakeup_claim( - &self, - run_id: &str, - chat_session_id: &str, - token: &str, - ) -> Result { - let renewed = self.conn.execute( - "UPDATE chat_run_wakeups SET claimed_at = ?4 - WHERE run_id = ?1 AND chat_session_id = ?2 - AND state = 'claimed' AND claim_token = ?3", - params![run_id, chat_session_id, token, now_ms()], - )?; - Ok(renewed == 1) - } - pub fn release_run_wakeup( &self, run_id: &str, @@ -1630,6 +1708,256 @@ impl Store { Ok(delivered == 1) } + /// Record `child` as a delegate of `parent`; recording it again, as a + /// retried start does, changes nothing. + pub fn record_chat_delegate( + &self, + child: &str, + parent: &str, + may_delegate: bool, + ) -> Result<()> { + self.conn.execute( + "INSERT OR IGNORE INTO chat_delegates (session_id, parent_session_id, may_delegate, created_at) + VALUES (?1, ?2, ?3, ?4)", + params![child, parent, may_delegate, now_ms()], + )?; + Ok(()) + } + + /// Forget who delegated to `id`; it stands as a chat the user started. + pub fn remove_chat_delegate(&self, id: &str) -> Result { + Ok(self + .conn + .execute("DELETE FROM chat_delegates WHERE session_id = ?1", [id])? + == 1) + } + + /// The chats `parent` delegated to, oldest first. + pub fn chat_delegates_of(&self, parent: &str) -> Result> { + let mut stmt = self.conn.prepare( + "SELECT session_id FROM chat_delegates WHERE parent_session_id = ?1 + ORDER BY created_at, session_id", + )?; + let rows = stmt.query_map([parent], |row| row.get(0))?; + Ok(rows.collect::, _>>()?) + } + + /// How many delegations deep `id` is, who delegated to it, and whether it + /// may delegate. A chat the user started is at depth 0 and may. + pub fn delegation(&self, id: &str) -> Result { + Ok(self.conn.query_row( + "WITH RECURSIVE chain(id, depth) AS ( + SELECT ?1, 0 + UNION ALL + SELECT d.parent_session_id, chain.depth + 1 FROM chain + JOIN chat_delegates d ON d.session_id = chain.id + ) + SELECT (SELECT MAX(depth) FROM chain), d.parent_session_id, + COALESCE(d.may_delegate, 1) + FROM (SELECT 1) LEFT JOIN chat_delegates d ON d.session_id = ?1", + params![id], + |row| { + Ok(Delegation { + depth: row.get(0)?, + parent: row.get(1)?, + may_delegate: row.get(2)?, + }) + }, + )?) + } + + /// Subscribe `subscriber` to `target`; an existing subscription, paused + /// or not, stays as it is. `told_turn_id` names a turn of `target` the + /// subscriber already knows. + pub fn subscribe_chat( + &self, + subscriber: &str, + target: &str, + told_turn_id: Option<&str>, + ) -> Result<()> { + self.conn.execute( + "INSERT OR IGNORE INTO chat_subscriptions + (subscriber_session_id, target_session_id, told_turn_id, created_at) + VALUES (?1, ?2, ?3, ?4)", + params![subscriber, target, told_turn_id, now_ms()], + )?; + Ok(()) + } + + /// Stop `target` telling `subscriber` anything; subscribing again keeps it + /// stopped. + pub fn pause_chat_subscription(&self, subscriber: &str, target: &str) -> Result { + Ok(self.conn.execute( + "UPDATE chat_subscriptions SET paused = 1 + WHERE subscriber_session_id = ?1 AND target_session_id = ?2", + params![subscriber, target], + )? == 1) + } + + /// A subscription the user paused stays, so subscribing again cannot undo + /// the user's choice. + pub fn unsubscribe_chat(&self, subscriber: &str, target: &str) -> Result { + Ok(self.conn.execute( + "DELETE FROM chat_subscriptions + WHERE subscriber_session_id = ?1 AND target_session_id = ?2 AND paused = 0", + params![subscriber, target], + )? == 1) + } + + /// Every subscription, or one subscriber's. + pub fn list_chat_subscriptions( + &self, + subscriber: Option<&str>, + ) -> Result> { + let mut stmt = self.conn.prepare(&format!( + "WITH {LATEST_SUBSCRIBED_TURNS} + SELECT subscriber_session_id, target_session_id, paused, told_prompt_id, pending + FROM latest + WHERE ?1 IS NULL OR subscriber_session_id = ?1 + ORDER BY created_at, target_session_id" + ))?; + let rows = stmt.query_map([subscriber], |row| { + Ok(ChatSubscription { + subscriber_session_id: row.get(0)?, + target_session_id: row.get(1)?, + paused: row.get(2)?, + told_prompt_id: row.get(3)?, + outstanding: row.get(4)?, + }) + })?; + Ok(rows.collect::, _>>()?) + } + + /// Subscriptions whose target is idle after a turn the subscriber has not + /// been told about. A delegate is still working while delegates of its own + /// have not answered it: a turn that ends waiting on them is not its answer. + pub fn list_ready_chat_subscriptions(&self) -> Result> { + let mut stmt = self.conn.prepare(&format!( + "WITH {LATEST_SUBSCRIBED_TURNS} + SELECT subscriber_session_id, target_session_id, turn_id, state, + assistant_message_id, created_at, told_turn_id + FROM latest l + WHERE l.idle AND l.paused = 0 + AND l.told_turn_id IS NOT l.turn_id + AND (l.claim_token IS NULL OR l.claimed_at < ?1) + AND NOT EXISTS ( + SELECT 1 FROM latest own + JOIN chat_delegates d ON d.session_id = own.target_session_id + AND d.parent_session_id = own.subscriber_session_id + WHERE own.subscriber_session_id = l.target_session_id + AND own.pending + ) + ORDER BY l.updated_at" + ))?; + let rows = stmt.query_map([now_ms() - RUN_WAKEUP_CLAIM_TTL_MS], |row| { + Ok(ReadyChatSubscription { + subscriber_session_id: row.get(0)?, + target_session_id: row.get(1)?, + turn_id: row.get(2)?, + turn_state: row.get(3)?, + assistant_message_id: row.get(4)?, + subscribed_at: row.get(5)?, + told_turn_id: row.get(6)?, + }) + })?; + Ok(rows.collect::, _>>()?) + } + + /// The answers of turns the target finished since the subscriber was last + /// told, before the one it is told now: a later turn started before the + /// subscriber was free to hear them. Oldest first. + pub fn untold_chat_answers(&self, ready: &ReadyChatSubscription) -> Result> { + let mut stmt = self.conn.prepare( + "SELECT e.assistant_message_id FROM chat_turns e + JOIN chat_turns now ON now.id = ?2 + WHERE e.session_id = ?1 AND e.id != now.id + AND e.state IN ('completed', 'failed', 'interrupted') + AND e.updated_at >= ?3 + AND (e.created_at, e.rowid) < (now.created_at, now.rowid) + AND NOT EXISTS ( + SELECT 1 FROM chat_turns told WHERE told.id = ?4 + AND (e.created_at, e.rowid) <= (told.created_at, told.rowid) + ) + ORDER BY e.created_at, e.rowid", + )?; + let rows = stmt.query_map( + params![ + ready.target_session_id, + ready.turn_id, + ready.subscribed_at, + ready.told_turn_id + ], + |row| row.get(0), + )?; + Ok(rows.collect::, _>>()?) + } + + /// Lease a subscription to tell `event`, unless it was told already or + /// another sweep holds the lease. + pub fn claim_chat_subscription( + &self, + subscriber: &str, + target: &str, + event: ToldEvent, + ) -> Result> { + let token = uuid::Uuid::new_v4().to_string(); + // A turn older than the one told already would rewind the cursor and + // tell the newer one twice. + let (told, id, newer) = match event { + ToldEvent::Turn(id) => ( + "told_turn_id", + id, + "AND NOT EXISTS ( + SELECT 1 FROM chat_turns e JOIN chat_turns t ON t.id = told_turn_id + WHERE e.id = ?3 AND (e.created_at, e.rowid) <= (t.created_at, t.rowid) + )", + ), + ToldEvent::Prompt(id) => ("told_prompt_id", id, ""), + }; + let claimed = self.conn.execute( + &format!( + "UPDATE chat_subscriptions SET claim_token = ?4, claimed_at = ?5 + WHERE subscriber_session_id = ?1 AND target_session_id = ?2 + AND {told} IS NOT ?3 {newer} + AND (claim_token IS NULL OR claimed_at < ?6)" + ), + params![ + subscriber, + target, + id, + token, + now_ms(), + now_ms() - RUN_WAKEUP_CLAIM_TTL_MS + ], + )?; + Ok((claimed == 1).then_some(token)) + } + + /// Release a claim. `told` records the event as told; without it the + /// event is retried on a later sweep. + pub fn settle_chat_subscription( + &self, + subscriber: &str, + target: &str, + token: &str, + told: Option, + ) -> Result { + let (turn, prompt) = match told { + Some(ToldEvent::Turn(id)) => (Some(id), None), + Some(ToldEvent::Prompt(id)) => (None, Some(id)), + None => (None, None), + }; + let settled = self.conn.execute( + "UPDATE chat_subscriptions + SET claim_token = NULL, claimed_at = NULL, + told_turn_id = COALESCE(?4, told_turn_id), + told_prompt_id = COALESCE(?5, told_prompt_id) + WHERE subscriber_session_id = ?1 AND target_session_id = ?2 AND claim_token = ?3", + params![subscriber, target, token, turn, prompt], + )?; + Ok(settled == 1) + } + pub fn chat_turn_leased(&self, chat_session_id: &str) -> Result { Ok(self.conn.query_row( "SELECT EXISTS(SELECT 1 FROM chat_turn_leases WHERE chat_session_id = ?1 AND heartbeat_at >= ?2)", @@ -2825,20 +3153,21 @@ impl Store { Ok(rows.collect::, _>>()?) } - /// The session whose worktree `id` runs in: its side-chat parent while that - /// parent exists, else itself. + /// The session whose worktree `id` runs in: the top of its chain of + /// existing side-chat parents (a delegate can delegate again), else itself. pub fn chat_worktree_owner(&self, id: &str) -> Result { - let owner: Option = self - .conn - .query_row( - "SELECT parent.id FROM chat_sessions side + Ok(self.conn.query_row( + "WITH RECURSIVE chain(id, depth) AS ( + SELECT ?1, 0 + UNION ALL + SELECT parent.id, chain.depth + 1 FROM chain + JOIN chat_sessions side ON side.id = chain.id JOIN chat_sessions parent ON parent.id = side.side_parent_session_id - WHERE side.id = ?1", - params![id], - |row| row.get(0), - ) - .optional()?; - Ok(owner.unwrap_or_else(|| id.to_string())) + ) + SELECT id FROM chain ORDER BY depth DESC LIMIT 1", + params![id], + |row| row.get(0), + )?) } pub fn list_chat_session_project_ids(&self) -> Result> { @@ -3566,6 +3895,40 @@ impl Store { .optional()?) } + /// The turn a user message started. + pub fn chat_turn_for_user_message( + &self, + session_id: &str, + message_id: &str, + ) -> Result> { + Ok(self + .conn + .query_row( + &format!( + "SELECT {CHAT_TURN_COLS} FROM chat_turns + WHERE session_id = ?1 AND user_message_id = ?2 + ORDER BY created_at, rowid LIMIT 1" + ), + params![session_id, message_id], + row_to_chat_turn, + ) + .optional()?) + } + + pub fn latest_chat_turn(&self, session_id: &str) -> Result> { + Ok(self + .conn + .query_row( + &format!( + "SELECT {CHAT_TURN_COLS} FROM chat_turns WHERE session_id = ?1 + ORDER BY created_at DESC, rowid DESC LIMIT 1" + ), + params![session_id], + row_to_chat_turn, + ) + .optional()?) + } + pub(crate) fn steer_receipt( &self, session_id: &str, @@ -3974,14 +4337,23 @@ impl Store { } pub fn list_chat_messages(&self, session_id: &str) -> Result> { + self.list_chat_messages_since(session_id, i64::MIN) + } + + /// A chat's messages created at or after `since`, oldest first. + pub fn list_chat_messages_since( + &self, + session_id: &str, + since: i64, + ) -> Result> { let mut stmt = self.conn.prepare( // rowid tiebreak: a user message and its reply can share a millisecond. "SELECT id, session_id, role, parts_json, created_at, parent_id, base_native_session_id, result_native_session_id, completed_at FROM chat_messages - WHERE session_id = ?1 ORDER BY created_at ASC, rowid ASC", + WHERE session_id = ?1 AND created_at >= ?2 ORDER BY created_at ASC, rowid ASC", )?; - let rows = stmt.query_map(params![session_id], |row| { + let rows = stmt.query_map(params![session_id, since], |row| { Ok(StoredChatMessage { id: row.get(0)?, session_id: row.get(1)?, @@ -4005,6 +4377,19 @@ impl Store { )?) } + /// Message ids that start with `msg_` and `hex`, at most two: enough to + /// tell a unique match from an ambiguous one. + pub fn chat_message_ids_with_prefix(&self, hex: &str) -> Result> { + if !hex.bytes().all(|b| b.is_ascii_hexdigit()) { + return Ok(Vec::new()); + } + let mut stmt = self + .conn + .prepare("SELECT id FROM chat_messages WHERE id GLOB ?1 LIMIT 2")?; + let rows = stmt.query_map([format!("msg_{hex}*")], |row| row.get(0))?; + Ok(rows.collect::, _>>()?) + } + /// A single chat message by id (used to reconcile a message's persisted /// state against an in-memory copy mid-turn). `None` if it doesn't exist. pub fn get_chat_message(&self, id: &str) -> Result> { @@ -4197,8 +4582,8 @@ pub struct StoredChatSession { pub native_session_id: Option, pub title: Option, /// Who wrote `title`: `"fallback"` (first-line placeholder), `"generated"` - /// (harness auto-title), `"user"` (explicitly chosen — a rename, or an - /// agent's `orx agent spawn --title`, neither of which auto-titling may + /// (harness auto-title), `"user"` (explicitly chosen — a rename, or the + /// title a delegating agent gave, neither of which auto-titling may /// overwrite). NULL on legacy rows, which the conditional setter treats as /// "unknown, don't overwrite". pub title_source: Option, @@ -4230,8 +4615,6 @@ pub struct StoredChatSession { /// Tip of the branch the UI is currently showing. Forked turns make the /// transcript a tree; this picks which path through it is live. pub active_leaf_id: Option, - /// Session that spawned this one with `orx agent spawn`. `None` for - /// sessions the user started from the dashboard. /// Chat this side chat branched from. Side chats share that chat's /// worktree, stay out of history, and are deleted with it. pub side_parent_session_id: Option, @@ -4259,6 +4642,9 @@ pub struct StoredUiState { pub preferred_agent: Option, pub workspace: Option, pub preferred_autonomy: Option, + /// Whether delegates may delegate in turn unless a `delegate` call says + /// otherwise. Off: only chats the user started delegate. + pub nested_delegation: bool, } /// Normalized transcript entry; `parts_json` is the wire-format parts array @@ -5653,6 +6039,7 @@ mod tests { preferred_agent: None, workspace: None, preferred_autonomy: None, + nested_delegation: false, } ); @@ -5676,6 +6063,7 @@ mod tests { preferred_agent: Some(selection), workspace: None, preferred_autonomy: Some(Autonomy::Copilot), + nested_delegation: false, } ); let _ = std::fs::remove_dir_all(&dir); @@ -6947,6 +7335,14 @@ mod tests { store.chat_worktree_owner("chat_side").unwrap(), "chat_parent" ); + let mut nested = chat_session_fixture("chat_nested"); + nested.side_parent_session_id = Some("chat_side".into()); + store.create_chat_session(&nested).unwrap(); + assert_eq!( + store.chat_worktree_owner("chat_nested").unwrap(), + "chat_parent" + ); + store.delete_chat_session("chat_nested").unwrap(); assert_eq!(store.chat_worktree_owner("chat_gone").unwrap(), "chat_gone"); assert!(store.delete_chat_session("chat_parent").is_err()); assert!(store.get_chat_session("chat_parent").unwrap().is_some()); @@ -7591,6 +7987,267 @@ mod tests { std::fs::remove_dir_all(dir).unwrap(); } + #[test] + fn news_of_a_turn_names_the_answers_it_overtook() { + let dir = std::env::temp_dir().join(format!("orx-store-untold-{}", uuid::Uuid::new_v4())); + let store = Store::open_at(dir.clone()).unwrap(); + for id in ["chat_parent", "chat_child"] { + store + .create_chat_session(&chat_session_fixture(id)) + .unwrap(); + } + let finish = |id: &str, created_at: i64| { + let mut turn = chat_turn_fixture(id, &format!("client-{id}")); + turn.session_id = "chat_child".into(); + turn.created_at = created_at; + store.admit_chat_turn(None, &turn).unwrap(); + store.complete_chat_turn(id).unwrap(); + }; + finish("history", 1); + store + .subscribe_chat("chat_parent", "chat_child", Some("history")) + .unwrap(); + finish("one", 2); + finish("two", 3); + + let ready = store.list_ready_chat_subscriptions().unwrap(); + assert_eq!(ready[0].turn_id, "two"); + assert_eq!( + store.untold_chat_answers(&ready[0]).unwrap(), + ["assistant_one"], + "the subscriber was never told of `one`, and `history` came before it subscribed" + ); + let told = store + .claim_chat_subscription("chat_parent", "chat_child", ToldEvent::Turn("two")) + .unwrap() + .unwrap(); + store + .settle_chat_subscription( + "chat_parent", + "chat_child", + &told, + Some(ToldEvent::Turn("two")), + ) + .unwrap(); + assert!( + store + .claim_chat_subscription("chat_parent", "chat_child", ToldEvent::Turn("one")) + .unwrap() + .is_none(), + "a turn older than the one told cannot rewind the subscription" + ); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn chat_subscriptions_tell_each_finished_turn_once_after_the_queue_drains() { + let dir = std::env::temp_dir().join(format!("orx-store-sub-{}", uuid::Uuid::new_v4())); + let store = Store::open_at(dir.clone()).unwrap(); + for id in ["chat_parent", "chat_child"] { + store + .create_chat_session(&chat_session_fixture(id)) + .unwrap(); + } + store + .record_chat_delegate("chat_child", "chat_parent", false) + .unwrap(); + store + .subscribe_chat("chat_parent", "chat_child", None) + .unwrap(); + store + .subscribe_chat("chat_parent", "chat_child", None) + .unwrap(); + assert_eq!(store.list_chat_subscriptions(None).unwrap().len(), 1); + let ready = || store.list_ready_chat_subscriptions().unwrap(); + let outstanding = || { + store + .list_chat_subscriptions(Some("chat_parent")) + .unwrap() + .into_iter() + .filter(|sub| sub.outstanding) + .map(|sub| sub.target_session_id) + .collect::>() + }; + let turn = |session: &str, id: &str, created_at: i64| { + let mut turn = chat_turn_fixture(id, &format!("client-{id}")); + turn.session_id = session.into(); + turn.created_at = created_at; + store.admit_chat_turn(None, &turn).unwrap(); + }; + let claim = |ready: &ReadyChatSubscription| { + store.claim_chat_subscription( + &ready.subscriber_session_id, + &ready.target_session_id, + ToldEvent::Turn(&ready.turn_id), + ) + }; + let tell = |ready: &ReadyChatSubscription| { + let token = claim(ready).unwrap().unwrap(); + assert!(store + .settle_chat_subscription( + &ready.subscriber_session_id, + &ready.target_session_id, + &token, + Some(ToldEvent::Turn(&ready.turn_id)), + ) + .unwrap()); + }; + + assert_eq!( + outstanding(), + ["chat_child"], + "a new delegate owes an answer" + ); + turn("chat_child", "one", 2); + assert!(ready().is_empty(), "a running turn has nothing to tell"); + store.complete_chat_turn("one").unwrap(); + let first = ready(); + assert_eq!(first.len(), 1); + assert_eq!(first[0].turn_id, "one"); + let token = claim(&first[0]).unwrap().unwrap(); + assert!(claim(&first[0]).unwrap().is_none()); + assert!(ready().is_empty(), "a claimed answer is in flight"); + store + .settle_chat_subscription("chat_parent", "chat_child", &token, None) + .unwrap(); + assert_eq!(ready().len(), 1, "an untold answer is retried"); + tell(&first[0]); + assert!(ready().is_empty(), "each turn is told once"); + assert!(outstanding().is_empty()); + + turn("chat_child", "two", 3); + store.complete_chat_turn("two").unwrap(); + store + .insert_queued_chat_message(&StoredQueuedChatMessage { + id: "queued".into(), + session_id: "chat_child".into(), + client_turn_id: "client-queued".into(), + request_hash: "hash".into(), + payload_json: "{}".into(), + created_at: 4, + }) + .unwrap(); + assert!(ready().is_empty(), "a queued message means more work first"); + store.delete_queued_chat_message("queued").unwrap(); + assert_eq!(ready()[0].turn_id, "two"); + tell(&ready()[0]); + + // The child delegates in turn: its turn ending while its own delegate + // works is not an answer for the parent. An unrelated subscription of + // the child does not hold its answer back. + for id in ["chat_grandchild", "chat_elsewhere"] { + store + .create_chat_session(&chat_session_fixture(id)) + .unwrap(); + store.subscribe_chat("chat_child", id, None).unwrap(); + } + store + .record_chat_delegate("chat_grandchild", "chat_child", false) + .unwrap(); + turn("chat_child", "three", 5); + store.complete_chat_turn("three").unwrap(); + assert!(ready().is_empty(), "its delegate has not run yet"); + turn("chat_grandchild", "four", 6); + assert!(ready().is_empty(), "its delegate is still working"); + store.complete_chat_turn("four").unwrap(); + let waiting = ready(); + assert_eq!(waiting.len(), 1); + assert_eq!(waiting[0].subscriber_session_id, "chat_child"); + tell(&waiting[0]); + assert_eq!( + ready()[0].turn_id, + "three", + "answered, the child's turn is its answer" + ); + + // The user stopped the child telling its parent: neither subscribing + // again nor unsubscribing first undoes that. + assert!(store + .pause_chat_subscription("chat_parent", "chat_child") + .unwrap()); + assert!(ready() + .iter() + .all(|ready| ready.subscriber_session_id != "chat_parent")); + store.unsubscribe_chat("chat_parent", "chat_child").unwrap(); + store + .subscribe_chat("chat_parent", "chat_child", None) + .unwrap(); + assert!(ready() + .iter() + .all(|ready| ready.subscriber_session_id != "chat_parent")); + + store.delete_chat_session("chat_child").unwrap(); + assert!(store + .list_chat_subscriptions(None) + .unwrap() + .iter() + .all(|sub| sub.subscriber_session_id != "chat_child" + && sub.target_session_id != "chat_child")); + assert!(store.chat_delegates_of("chat_parent").unwrap().is_empty()); + assert_eq!( + store.delegation("chat_grandchild").unwrap().parent, + None, + "a delegate outliving its delegator is the user's" + ); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn delegation_depth_follows_delegate_links_not_side_chats() { + let dir = std::env::temp_dir().join(format!("orx-store-depth-{}", uuid::Uuid::new_v4())); + let store = Store::open_at(dir.clone()).unwrap(); + let chat = |id: &str, side_parent: Option<&str>| { + let mut session = chat_session_fixture(id); + session.side_parent_session_id = side_parent.map(str::to_string); + store.create_chat_session(&session).unwrap(); + }; + chat("chat_root", None); + chat("chat_side", Some("chat_root")); + chat("chat_one", Some("chat_side")); + chat("chat_two", None); + store + .record_chat_delegate("chat_one", "chat_side", true) + .unwrap(); + store + .record_chat_delegate("chat_two", "chat_one", false) + .unwrap(); + store + .subscribe_chat("chat_root", "chat_side", None) + .unwrap(); + let at = |id: &str| store.delegation(id).unwrap(); + let user = Delegation { + depth: 0, + parent: None, + may_delegate: true, + }; + assert_eq!(at("chat_root"), user); + assert_eq!( + at("chat_side"), + user, + "a side chat the user opened is not a delegate, subscribed or not" + ); + assert_eq!( + at("chat_one"), + Delegation { + depth: 1, + parent: Some("chat_side".into()), + may_delegate: true + } + ); + assert_eq!( + at("chat_two"), + Delegation { + depth: 2, + parent: Some("chat_one".into()), + may_delegate: false + }, + "a delegate in its own worktree is still one level deeper" + ); + assert_eq!(store.chat_worktree_owner("chat_one").unwrap(), "chat_root"); + assert_eq!(store.chat_worktree_owner("chat_two").unwrap(), "chat_two"); + let _ = std::fs::remove_dir_all(dir); + } + #[test] fn run_wakeups_are_idempotent_ready_only_at_success_or_failure_and_pruned() { let dir = std::env::temp_dir().join(format!("orx-store-wake-{}", uuid::Uuid::new_v4())); @@ -7775,9 +8432,13 @@ mod tests { assert!(!first .mark_run_wakeup_delivered("run_done", "chat_A", &stale_token) .unwrap()); - assert!(second - .renew_run_wakeup_claim("run_done", "chat_A", ¤t_token) - .unwrap()); + assert!( + first + .claim_run_wakeup("run_done", "chat_A") + .unwrap() + .is_none(), + "a stale token releases nothing" + ); second .release_run_wakeup("run_done", "chat_A", ¤t_token) .unwrap(); diff --git a/src/store/telemetry.rs b/src/store/telemetry.rs index 5aa60eb2a..abf671aeb 100644 --- a/src/store/telemetry.rs +++ b/src/store/telemetry.rs @@ -858,7 +858,7 @@ mod tests { for step in [3, 5] { let payload = serde_json::json!({"conversationId": "c", "initialNumSteps": step, "modelName": "gemini-3.8-flash-high", "transcriptPath": transcript}); - crate::commands::mcp_gate::record_post_invocation(&store, &payload, Some("e")).unwrap(); + crate::commands::mcp::record_post_invocation(&store, &payload, Some("e")).unwrap(); } let samples: Vec<(String, Option)> = store .conn diff --git a/ui/messages/ar.json b/ui/messages/ar.json index 9f6fe05b2..dd9113a18 100644 --- a/ui/messages/ar.json +++ b/ui/messages/ar.json @@ -340,6 +340,24 @@ "settings_page_add_one_with": "أضِف واحدًا عبر", "settings_page_add_variable": "إضافة متغيّر", "settings_page_agent_models": "نماذج الوكيل", + "settings_nested_subagents": "السماح بالوكلاء الفرعيين المتداخلين", + "settings_nested_subagents_description": "يتيح للوكلاء الفرعيين تشغيل وكلاء فرعيين خاصين بهم. لا يزال بإمكان الوكلاء تغيير ذلك لكل مهمة.", + "subagents_heading": "الوكلاء الفرعيون", + "subagents_finished": "{count} مكتمل", + "subagents_failed": "{count} فشل", + "subagent_status_finished": "مكتمل", + "subagent_status_stopped": "متوقف", + "chat_notify_parent": "إشعار الوكيل الأصلي عند الانتهاء", + "agent_message_other_chat": "محادثة أخرى", + "agent_message_openresearch": "OpenResearch", + "agent_message_runs_unmonitored": "انقطع الاتصال بعمليات التشغيل هذه", + "run_done_in": "اكتمل خلال {duration}", + "run_failed_after": "فشل بعد {duration}", + "chat_cited_message": "الرسالة {ref}", + "chat_cited_message_missing": "تعذر العثور على تلك الرسالة", + "subagent_status_asking": "يحتاج إلى إجابة", + "subagent_status_approval": "يحتاج إلى موافقة", + "subagent_open": "فتح محادثة الوكيل الفرعي", "settings_page_anonymous_usage_analytics": "تحليلات استخدام مجهولة الهوية", "settings_page_auth": "المصادقة", "settings_page_authentication": "المصادقة", diff --git a/ui/messages/en.json b/ui/messages/en.json index 4f7edfed6..cac9b7c7b 100644 --- a/ui/messages/en.json +++ b/ui/messages/en.json @@ -340,6 +340,24 @@ "settings_page_add_one_with": "Add one with", "settings_page_add_variable": "Add variable", "settings_page_agent_models": "Agent models", + "settings_nested_subagents": "Allow nested sub-agents", + "settings_nested_subagents_description": "Let sub-agents start sub-agents of their own. Agents can still change this for each task.", + "subagents_heading": "Sub-agents", + "subagents_finished": "{count} finished", + "subagents_failed": "{count} failed", + "subagent_status_finished": "Finished", + "subagent_status_stopped": "Stopped", + "chat_notify_parent": "Notify the parent agent on completion", + "agent_message_other_chat": "Another chat", + "agent_message_openresearch": "OpenResearch", + "agent_message_runs_unmonitored": "Lost contact with these runs", + "run_done_in": "Done in {duration}", + "run_failed_after": "Failed after {duration}", + "chat_cited_message": "Message {ref}", + "chat_cited_message_missing": "Couldn't find that message", + "subagent_status_asking": "Needs an answer", + "subagent_status_approval": "Needs approval", + "subagent_open": "Open sub-agent chat", "settings_page_anonymous_usage_analytics": "Anonymous usage analytics", "settings_page_auth": "Auth", "settings_free_models_no_sign_in": "Free models · No sign-in required", diff --git a/ui/messages/es.json b/ui/messages/es.json index 1c155371c..af8ea12e2 100644 --- a/ui/messages/es.json +++ b/ui/messages/es.json @@ -340,6 +340,24 @@ "settings_page_add_one_with": "Añade una con", "settings_page_add_variable": "Añadir variable", "settings_page_agent_models": "Modelos de los agentes", + "settings_nested_subagents": "Permitir subagentes anidados", + "settings_nested_subagents_description": "Permite que los subagentes inicien sus propios subagentes. Los agentes pueden cambiarlo en cada tarea.", + "subagents_heading": "Subagentes", + "subagents_finished": "{count} terminados", + "subagents_failed": "{count} con error", + "subagent_status_finished": "Terminado", + "subagent_status_stopped": "Detenido", + "chat_notify_parent": "Avisar al agente principal al terminar", + "agent_message_other_chat": "Otro chat", + "agent_message_openresearch": "OpenResearch", + "agent_message_runs_unmonitored": "Se perdió el contacto con estas ejecuciones", + "run_done_in": "Completado en {duration}", + "run_failed_after": "Falló tras {duration}", + "chat_cited_message": "Mensaje {ref}", + "chat_cited_message_missing": "No se encontró ese mensaje", + "subagent_status_asking": "Necesita respuesta", + "subagent_status_approval": "Necesita aprobación", + "subagent_open": "Abrir chat del subagente", "settings_page_anonymous_usage_analytics": "Estadísticas de uso anónimas", "settings_page_auth": "Autenticación", "settings_free_models_no_sign_in": "Modelos gratuitos · No es necesario iniciar sesión", diff --git a/ui/messages/fa.json b/ui/messages/fa.json index cb0cd1fba..04f92dabe 100644 --- a/ui/messages/fa.json +++ b/ui/messages/fa.json @@ -340,6 +340,24 @@ "settings_page_add_one_with": "یکی با این فرمان اضافه کنید:", "settings_page_add_variable": "افزودن متغیر", "settings_page_agent_models": "مدل‌های عامل", + "settings_nested_subagents": "اجازهٔ عامل‌های فرعی تودرتو", + "settings_nested_subagents_description": "عامل‌های فرعی می‌توانند عامل‌های فرعی خودشان را آغاز کنند. عامل‌ها همچنان می‌توانند این را برای هر کار تغییر دهند.", + "subagents_heading": "عامل‌های فرعی", + "subagents_finished": "{count} پایان‌یافته", + "subagents_failed": "{count} ناموفق", + "subagent_status_finished": "پایان‌یافته", + "subagent_status_stopped": "متوقف‌شده", + "chat_notify_parent": "اطلاع به عامل والد پس از پایان", + "agent_message_other_chat": "گفت‌وگوی دیگر", + "agent_message_openresearch": "OpenResearch", + "agent_message_runs_unmonitored": "ارتباط با این اجراها قطع شد", + "run_done_in": "در {duration} انجام شد", + "run_failed_after": "پس از {duration} ناموفق شد", + "chat_cited_message": "پیام {ref}", + "chat_cited_message_missing": "آن پیام پیدا نشد", + "subagent_status_asking": "نیاز به پاسخ", + "subagent_status_approval": "نیاز به تأیید", + "subagent_open": "باز کردن گفت‌وگوی عامل فرعی", "settings_page_anonymous_usage_analytics": "تحلیل ناشناس استفاده", "settings_page_auth": "احراز هویت", "settings_free_models_no_sign_in": "مدل‌های رایگان · بدون نیاز به ورود", diff --git a/ui/messages/hi.json b/ui/messages/hi.json index 9bebfbf73..b5d7ed0e6 100644 --- a/ui/messages/hi.json +++ b/ui/messages/hi.json @@ -340,6 +340,24 @@ "settings_page_add_one_with": "इसके साथ एक जोड़ें", "settings_page_add_variable": "वेरिएबल जोड़ें", "settings_page_agent_models": "एजेंट मॉडल", + "settings_nested_subagents": "नेस्टेड सब-एजेंट की अनुमति दें", + "settings_nested_subagents_description": "सब-एजेंट को अपने सब-एजेंट शुरू करने दें। एजेंट हर काम के लिए इसे अब भी बदल सकते हैं।", + "subagents_heading": "सब-एजेंट", + "subagents_finished": "{count} पूरे हुए", + "subagents_failed": "{count} विफल", + "subagent_status_finished": "पूरा हुआ", + "subagent_status_stopped": "रोका गया", + "chat_notify_parent": "पूरा होने पर मूल एजेंट को सूचित करें", + "agent_message_other_chat": "दूसरी चैट", + "agent_message_openresearch": "OpenResearch", + "agent_message_runs_unmonitored": "इन रन से संपर्क टूट गया", + "run_done_in": "{duration} में पूरा हुआ", + "run_failed_after": "{duration} बाद विफल हुआ", + "chat_cited_message": "संदेश {ref}", + "chat_cited_message_missing": "वह संदेश नहीं मिला", + "subagent_status_asking": "जवाब चाहिए", + "subagent_status_approval": "मंज़ूरी चाहिए", + "subagent_open": "सब-एजेंट चैट खोलें", "settings_page_anonymous_usage_analytics": "अनाम उपयोग एनालिटिक्स", "settings_page_auth": "ऑथ", "settings_free_models_no_sign_in": "मुफ़्त मॉडल · साइन-इन ज़रूरी नहीं", diff --git a/ui/messages/ja.json b/ui/messages/ja.json index 46a9d8c68..a4e6ca837 100644 --- a/ui/messages/ja.json +++ b/ui/messages/ja.json @@ -340,6 +340,24 @@ "settings_page_add_one_with": "次のコマンドで追加", "settings_page_add_variable": "変数を追加", "settings_page_agent_models": "エージェントのモデル", + "settings_nested_subagents": "ネストしたサブエージェントを許可", + "settings_nested_subagents_description": "サブエージェントが独自のサブエージェントを開始できるようにします。エージェントはタスクごとにこの設定を変更できます。", + "subagents_heading": "サブエージェント", + "subagents_finished": "完了 {count}", + "subagents_failed": "失敗 {count}", + "subagent_status_finished": "完了", + "subagent_status_stopped": "停止", + "chat_notify_parent": "完了時に親エージェントへ通知", + "agent_message_other_chat": "別のチャット", + "agent_message_openresearch": "OpenResearch", + "agent_message_runs_unmonitored": "これらの実行との接続が切れました", + "run_done_in": "{duration}で完了", + "run_failed_after": "{duration}後に失敗", + "chat_cited_message": "メッセージ {ref}", + "chat_cited_message_missing": "そのメッセージが見つかりませんでした", + "subagent_status_asking": "回答待ち", + "subagent_status_approval": "承認待ち", + "subagent_open": "サブエージェントのチャットを開く", "settings_page_anonymous_usage_analytics": "匿名の利用状況分析", "settings_page_auth": "認証", "settings_free_models_no_sign_in": "無料モデル · サインイン不要", diff --git a/ui/messages/ko.json b/ui/messages/ko.json index e0d7a8a8e..ae66f2246 100644 --- a/ui/messages/ko.json +++ b/ui/messages/ko.json @@ -340,6 +340,24 @@ "settings_page_add_one_with": "다음 명령으로 추가", "settings_page_add_variable": "변수 추가", "settings_page_agent_models": "에이전트 모델", + "settings_nested_subagents": "중첩 하위 에이전트 허용", + "settings_nested_subagents_description": "하위 에이전트가 자체 하위 에이전트를 시작할 수 있습니다. 에이전트는 작업마다 이 설정을 바꿀 수 있습니다.", + "subagents_heading": "하위 에이전트", + "subagents_finished": "완료 {count}", + "subagents_failed": "실패 {count}", + "subagent_status_finished": "완료", + "subagent_status_stopped": "중지됨", + "chat_notify_parent": "완료 시 상위 에이전트에 알림", + "agent_message_other_chat": "다른 채팅", + "agent_message_openresearch": "OpenResearch", + "agent_message_runs_unmonitored": "이 실행과의 연결이 끊겼습니다", + "run_done_in": "{duration} 만에 완료", + "run_failed_after": "{duration} 후 실패", + "chat_cited_message": "메시지 {ref}", + "chat_cited_message_missing": "해당 메시지를 찾을 수 없습니다", + "subagent_status_asking": "답변 필요", + "subagent_status_approval": "승인 필요", + "subagent_open": "하위 에이전트 채팅 열기", "settings_page_anonymous_usage_analytics": "익명 사용 분석", "settings_page_auth": "인증", "settings_free_models_no_sign_in": "무료 모델 · 로그인 불필요", diff --git a/ui/messages/pl.json b/ui/messages/pl.json index dfc11dc20..a640db719 100644 --- a/ui/messages/pl.json +++ b/ui/messages/pl.json @@ -340,6 +340,24 @@ "settings_page_add_one_with": "Dodaj klucz za pomocą", "settings_page_add_variable": "Dodaj zmienną", "settings_page_agent_models": "Modele agentów", + "settings_nested_subagents": "Zezwalaj na zagnieżdżone podagenty", + "settings_nested_subagents_description": "Pozwala podagentom uruchamiać własne podagenty. Agenci nadal mogą to zmienić dla każdego zadania.", + "subagents_heading": "Podagenty", + "subagents_finished": "Zakończone: {count}", + "subagents_failed": "Nieudane: {count}", + "subagent_status_finished": "Zakończony", + "subagent_status_stopped": "Zatrzymany", + "chat_notify_parent": "Powiadom agenta nadrzędnego po zakończeniu", + "agent_message_other_chat": "Inny czat", + "agent_message_openresearch": "OpenResearch", + "agent_message_runs_unmonitored": "Utracono kontakt z tymi uruchomieniami", + "run_done_in": "Gotowe w {duration}", + "run_failed_after": "Niepowodzenie po {duration}", + "chat_cited_message": "Wiadomość {ref}", + "chat_cited_message_missing": "Nie znaleziono tej wiadomości", + "subagent_status_asking": "Czeka na odpowiedź", + "subagent_status_approval": "Czeka na zgodę", + "subagent_open": "Otwórz czat podagenta", "settings_page_anonymous_usage_analytics": "Anonimowe statystyki użytkowania", "settings_page_auth": "Uwierzytelnianie", "settings_free_models_no_sign_in": "Darmowe modele · Logowanie nie jest wymagane", diff --git a/ui/messages/ru.json b/ui/messages/ru.json index 8ccbcf400..f6c259336 100644 --- a/ui/messages/ru.json +++ b/ui/messages/ru.json @@ -340,6 +340,24 @@ "settings_page_add_one_with": "Добавьте его командой", "settings_page_add_variable": "Добавить переменную", "settings_page_agent_models": "Модели агентов", + "settings_nested_subagents": "Разрешить вложенных субагентов", + "settings_nested_subagents_description": "Субагенты смогут запускать собственных субагентов. Агенты по-прежнему могут изменить это для каждой задачи.", + "subagents_heading": "Субагенты", + "subagents_finished": "Завершено: {count}", + "subagents_failed": "Ошибок: {count}", + "subagent_status_finished": "Завершён", + "subagent_status_stopped": "Остановлен", + "chat_notify_parent": "Уведомить родительского агента по завершении", + "agent_message_other_chat": "Другой чат", + "agent_message_openresearch": "OpenResearch", + "agent_message_runs_unmonitored": "Связь с этими запусками потеряна", + "run_done_in": "Готово за {duration}", + "run_failed_after": "Сбой через {duration}", + "chat_cited_message": "Сообщение {ref}", + "chat_cited_message_missing": "Не удалось найти это сообщение", + "subagent_status_asking": "Ждёт ответа", + "subagent_status_approval": "Ждёт одобрения", + "subagent_open": "Открыть чат субагента", "settings_page_anonymous_usage_analytics": "Анонимная статистика использования", "settings_page_auth": "Авторизация", "settings_free_models_no_sign_in": "Бесплатные модели · Вход не нужен", diff --git a/ui/messages/tr.json b/ui/messages/tr.json index 7f545fa8c..4d7e4cf02 100644 --- a/ui/messages/tr.json +++ b/ui/messages/tr.json @@ -340,6 +340,24 @@ "settings_page_add_one_with": "Şununla ekleyin:", "settings_page_add_variable": "Değişken ekle", "settings_page_agent_models": "Ajan modelleri", + "settings_nested_subagents": "İç içe alt ajanlara izin ver", + "settings_nested_subagents_description": "Alt ajanların kendi alt ajanlarını başlatmasına izin verin. Ajanlar bunu her görev için yine de değiştirebilir.", + "subagents_heading": "Alt ajanlar", + "subagents_finished": "{count} tamamlandı", + "subagents_failed": "{count} başarısız", + "subagent_status_finished": "Tamamlandı", + "subagent_status_stopped": "Durduruldu", + "chat_notify_parent": "Tamamlanınca üst ajana haber ver", + "agent_message_other_chat": "Başka bir sohbet", + "agent_message_openresearch": "OpenResearch", + "agent_message_runs_unmonitored": "Bu çalıştırmalarla bağlantı kesildi", + "run_done_in": "{duration} içinde tamamlandı", + "run_failed_after": "{duration} sonra başarısız oldu", + "chat_cited_message": "Mesaj {ref}", + "chat_cited_message_missing": "Bu mesaj bulunamadı", + "subagent_status_asking": "Yanıt bekliyor", + "subagent_status_approval": "Onay gerekiyor", + "subagent_open": "Alt ajan sohbetini aç", "settings_page_anonymous_usage_analytics": "Anonim kullanım analitiği", "settings_page_auth": "Kimlik doğrulama", "settings_free_models_no_sign_in": "Ücretsiz modeller · Giriş gerekmez", diff --git a/ui/messages/zh-CN.json b/ui/messages/zh-CN.json index d1c1fa8c2..31b5ceeb5 100644 --- a/ui/messages/zh-CN.json +++ b/ui/messages/zh-CN.json @@ -340,6 +340,24 @@ "settings_page_add_one_with": "使用以下命令添加:", "settings_page_add_variable": "添加变量", "settings_page_agent_models": "智能体模型", + "settings_nested_subagents": "允许嵌套子智能体", + "settings_nested_subagents_description": "允许子智能体启动自己的子智能体。智能体仍可针对每个任务更改此设置。", + "subagents_heading": "子智能体", + "subagents_finished": "已完成 {count}", + "subagents_failed": "失败 {count}", + "subagent_status_finished": "已完成", + "subagent_status_stopped": "已停止", + "chat_notify_parent": "完成后通知父代理", + "agent_message_other_chat": "另一个对话", + "agent_message_openresearch": "OpenResearch", + "agent_message_runs_unmonitored": "与这些运行失去联系", + "run_done_in": "用时 {duration} 完成", + "run_failed_after": "{duration} 后失败", + "chat_cited_message": "消息 {ref}", + "chat_cited_message_missing": "找不到该消息", + "subagent_status_asking": "需要回答", + "subagent_status_approval": "需要批准", + "subagent_open": "打开子智能体聊天", "settings_page_anonymous_usage_analytics": "匿名使用情况分析", "settings_page_auth": "身份验证", "settings_free_models_no_sign_in": "免费模型 · 无需登录", diff --git a/ui/src/App.tsx b/ui/src/App.tsx index 9747a5548..89df18f38 100644 --- a/ui/src/App.tsx +++ b/ui/src/App.tsx @@ -24,7 +24,7 @@ import { import { listChatSessionsQuery, getChatMessagesQuery } from "./queries/chat"; import { listProjectsQuery, getUiStateQuery, listRunsQuery, listExperimentsQuery } from "./queries/projects"; -import { deleteExperiment, openSideChat, sendChatMessage, setExperimentArchived } from "./api"; +import { citedMessage, deleteExperiment, openSideChat, sendChatMessage, setExperimentArchived } from "./api"; import { getArtifactsQuery } from "./queries/files"; import { readHarnesses } from "./queries/settings"; import { useBlocker, useRouter, useRouterState } from "@tanstack/react-router"; @@ -114,7 +114,7 @@ import { WorkspaceTools } from "./components/WorkspaceTools"; import { ProjectTerminal } from "./components/ProjectTerminal"; import { SettingsCommandTerminal } from "./components/SshConnectTerminal"; import { isWindowsDrivePath } from "./markdownTarget"; -import { ChatPanel, findPartById, spawnRowTitle } from "./components/ChatPanel"; +import { ChatPanel, findPartById, spawnRowTitle, type FocusedMessage } from "./components/ChatPanel"; import { OptionPicker, usePopover } from "./components/ModelPicker"; import { SubagentTab } from "./components/SubagentTab"; import { CodeTab, type CodeView } from "./components/CodeTab"; @@ -146,6 +146,7 @@ import { appHotkeys, tabJumpHotkeys } from "./hotkeys"; import { Button, IconButton, MenuItem, SEGMENTED_CLASS_NAME, showAlert, Spinner, Tooltip } from "./components/ui"; import { CodeTabBody, TabBody } from "./components/layout/TabBody"; import { RemoteStatus } from "./components/RemoteStatus"; +import { delegateModelLabel } from "./delegates"; const EMPTY_STATE_CLASS_NAME = [ "empty-state absolute inset-0 flex flex-col items-center", @@ -1122,6 +1123,21 @@ export default function App({ runtime, projectId, pane }: { runtime: RuntimeInfo return matches.length === 1 ? matches[0][1] : ""; }, [runExperimentNames]); + // Rebuilt only when a title or harness changes, so transcripts do not re-render on every session update. + const chatSessionsRef = useRef(sessionsQuery.data); + chatSessionsRef.current = sessionsQuery.data; + const chatInfoKey = (sessionsQuery.data ?? []) + .map((session) => `${session.id}\u0000${session.title ?? ""}\u0000${session.model ?? ""}\u0000${session.harness}`) + .join("\u0001"); + const chatInfo = useMemo(() => { + void chatInfoKey; + const chats = new Map((chatSessionsRef.current ?? []).map((session) => [ + session.id, + { title: session.title?.trim() || delegateModelLabel(session), harness: session.harness }, + ])); + return (sessionId: string) => chats.get(sessionId); + }, [chatInfoKey]); + const experimentName = useCallback((experimentId: string) => { const exact = experimentNames.get(experimentId); if (exact) return exact; @@ -1366,6 +1382,24 @@ export default function App({ runtime, projectId, pane }: { runtime: RuntimeInfo openSideTab(sessionId); }, [openSideTab]); + // A delegate with its own worktree is a chat of its own, not a side chat. + const openDelegate = useCallback((sessionId: string) => { + const session = sessionsQuery.data?.find((row) => row.id === sessionId); + if (session && !session.sideParentSessionId) onActiveSessionChange(sessionId); + else focusSideTab(sessionId); + }, [sessionsQuery.data, onActiveSessionChange, focusSideTab]); + + const [focusedMessage, setFocusedMessage] = useState(null); + const openMessage = useCallback((cited: string) => { + const missing = () => showAlert(m.chat_cited_message_missing(), "error"); + void citedMessage(cited).then(({ projectId: owner, sessionId, messageId }) => { + if (owner && owner !== projectId) onActiveSessionChange(sessionId, { projectId: owner }); + else if (sessionsQuery.data?.some((session) => session.id === sessionId)) openDelegate(sessionId); + else return missing(); + setFocusedMessage({ sessionId, messageId, nonce: Date.now() }); + }, missing); + }, [projectId, sessionsQuery.data, openDelegate, onActiveSessionChange]); + const forgetSideTab = useCallback( (tab: SideChatViewDef) => { if (!sideTabs.some((t) => t.sessionId === tab.sessionId)) return; @@ -1997,11 +2031,15 @@ export default function App({ runtime, projectId, pane }: { runtime: RuntimeInfo onOpenFile={openChatFile} onOpenRun={openRunLogs} runExperimentName={runExperimentName} + chatInfo={chatInfo} + onOpenMessage={openMessage} + focusedMessage={focusedMessage} onOpenExperiment={openExperimentNotes} experimentName={experimentName} onOpenPlan={openPlanTab} onOpenSubagent={openSubagentTab} onOpenSideChat={(parentSessionId, question) => void startSideChat(parentSessionId, question)} + onOpenDelegate={openDelegate} onRunSetup={runtime.kind === "ssh" ? undefined : runSetup} composerFocusNonce={composerFocusNonce} runtime={runtime} @@ -2047,6 +2085,7 @@ export default function App({ runtime, projectId, pane }: { runtime: RuntimeInfo onSideChat={activeSessionId ? () => void startSideChat(activeSessionId, "") : undefined} sessions={sessionsQuery.data ?? []} onSelectSideChat={focusSideTab} + onOpenDelegate={openDelegate} /> )} {mainView === "chat" && panelOpen && ( @@ -2437,6 +2476,9 @@ export default function App({ runtime, projectId, pane }: { runtime: RuntimeInfo } onOpenRun={(runId, intent) => openFromRightTab(sideTab, () => openRunLogs(runId, intent))} runExperimentName={runExperimentName} + chatInfo={chatInfo} + onOpenMessage={openMessage} + focusedMessage={focusedMessage} onOpenExperiment={(experimentId, intent) => openFromRightTab(sideTab, () => openExperimentNotes(experimentId, intent)) } @@ -2451,6 +2493,7 @@ export default function App({ runtime, projectId, pane }: { runtime: RuntimeInfo activeSessionId={sideTab.sessionId} sideParentSessionId={sideTab.sessionId === null ? activeSessionId ?? undefined : undefined} onOpenSideChat={(parentSessionId, question) => void startSideChat(parentSessionId, question)} + onOpenDelegate={openDelegate} onActiveSessionChange={(sessionId, options) => { if (sideTab.sessionId === null && sessionId !== null) { const session = queryClient.getQueryData(listChatSessionsQuery(projectId).queryKey) diff --git a/ui/src/agentMessages.ts b/ui/src/agentMessages.ts new file mode 100644 index 000000000..fb7006325 --- /dev/null +++ b/ui/src/agentMessages.ts @@ -0,0 +1,14 @@ +/** A message's ref (`msg_` and the start of its id) or a chat's id, as agents write them. */ +export const CITED_ID = /(? `#${cited.slice("msg_".length)}`; + +/** A message's first line as plain text, for a one-line preview. */ +export function firstLine(text: string): string { + const line = text.split("\n").find((candidate) => candidate.trim()) ?? ""; + return line + .replace(/^[\s#>*_-]+/, "") + .replace(/\*+|__|`/g, "") + .trim(); +} diff --git a/ui/src/api.ts b/ui/src/api.ts index ffc6348ae..1b45de8e9 100644 --- a/ui/src/api.ts +++ b/ui/src/api.ts @@ -235,6 +235,8 @@ export interface UiState { tourCompleted: boolean; preferredAgent: AgentSelection | null; preferredAutonomy: Autonomy | null; + /** Whether sub-agents may start their own unless a delegation says otherwise. */ + nestedDelegation: boolean; } /** How much of the research the agent owns before checking in. */ @@ -256,6 +258,7 @@ export const updateUiState = (body: { tourCompleted?: boolean; preferredAgent?: AgentSelection; preferredAutonomy?: Autonomy; + nestedDelegation?: boolean; }) => post("/api/settings/ui-state", body); export const completeOnboarding = (selection: OnboardingSelection, profile: Profile) => @@ -2076,6 +2079,8 @@ export interface ChatPrompt { approved?: boolean; note?: string; annotations?: ChatTextAnnotation[]; + /** The chat whose agent answered for the user. */ + answeredBy?: string; /** Backend resume routing id. Presence marks a HELD mid-turn card (the * turn is blocked open waiting on this answer); absent on end-turn cards. */ nativeId?: string; @@ -2094,6 +2099,15 @@ export interface ChatPart { /** Nested transcript of a sub-agent this part spawned (Codex `subagent` * tool). Streams live and recurses for sub-agents that spawn their own. */ children?: ChatPart[]; + /** Set on a message orx or another chat's agent wrote: what it is, and the chat or run it comes from. */ + orx?: OrxSource; +} + +export interface OrxSource { + kind: "task" | "message" | "answer" | "question" | "run" | "monitoring"; + from?: string; + /** A run's status, or the state a chat's turn ended in. */ + status?: string; } export interface ChatMessage { @@ -2122,8 +2136,8 @@ export interface ChatSession { nativeConfiguration?: unknown; title: string | null; /** Who wrote `title`: `"fallback"` (first-line placeholder), `"generated"` - * (harness auto-title), `"user"` (explicitly chosen — a rename, or an agent's - * `orx agent spawn --title`). Null on legacy sessions. */ + * (harness auto-title), `"user"` (explicitly chosen — a rename, or the title a + * delegating agent gave). Null on legacy sessions. */ titleSource?: string | null; model: string | null; serviceTier: string | null; @@ -2139,6 +2153,17 @@ export interface ChatSession { /** Chat this side chat branched from. Side chats share its worktree and * stay out of top-level history; deleting the parent deletes its side chats. */ sideParentSessionId?: string | null; + /** Set on a chat another chat delegated to: who delegated, how deep it is, whether it tells + * that chat when it finishes, how its latest turn ended, and what it waits on. */ + delegate?: { + parentId: string; + depth: number; + notifies: boolean; + state: string | null; + answer: string | null; + error: string | null; + asking: "question" | "permission" | "plan" | null; + } | null; createdAt: number; updatedAt: number; busy: boolean; @@ -2218,6 +2243,18 @@ export const setChatSessionArchived = (sessionId: string, archived: boolean) => (r) => r.session, ); +/** Keep a delegate for the user: it stops telling the chat that started it and becomes a side chat. */ +export const releaseDelegate = (sessionId: string) => + patch<{ session: ChatSession }>(`/api/chat/sessions/${sessionId}`, { notifyParent: false }).then( + (r) => r.session, + ); + +/** The message an agent cited by ref: where it lives, the agent that wrote it if one did, and its first words. */ +export const citedMessage = (cited: string) => + get<{ projectId: string | null; sessionId: string; messageId: string; harness: HarnessId | null; preview: string }>( + `/api/chat/messages/${encodeURIComponent(cited)}`, + ); + /** Rename a session. The title is trimmed server-side; empty titles are rejected. */ export const renameChatSession = (sessionId: string, title: string) => patch<{ session: ChatSession }>(`/api/chat/sessions/${sessionId}`, { title }).then( diff --git a/ui/src/chatRendering.ts b/ui/src/chatRendering.ts index cae38d212..2edeeeb4d 100644 --- a/ui/src/chatRendering.ts +++ b/ui/src/chatRendering.ts @@ -70,6 +70,8 @@ export function questionReplies(messages: ChatMessage[]): QuestionReplies { const questionById = new Map(); const prompts = new Set(); const pending = new Map(); + // A held card an agent answered is followed by that chat's steered answer. + const answeredBy = new Map(); const originalQuestions = new Map(); for (const part of messages.flatMap((message) => message.parts)) { const questions = part.type === "tool" && part.state?.input?.questions; @@ -99,9 +101,14 @@ export function questionReplies(messages: ChatMessage[]): QuestionReplies { if (prompt?.kind === "question" && prompt.question) { questionById.set(part.id, originalQuestions.get(prompt.question) ?? prompt.question); } - if (part.type === "prompt" && prompt?.kind === "question" && prompt.resolved && !prompt.nativeId && prompt.question) { + if (part.type === "prompt" && prompt?.resolved && prompt.nativeId && prompt.answeredBy) { + answeredBy.set(prompt.answeredBy, part.id); + } else if (part.type === "prompt" && prompt?.kind === "question" && prompt.resolved && !prompt.nativeId && prompt.question) { const answer = [(prompt.answers ?? []).join(", "), prompt.note].filter(Boolean).join("\n\n"); if (answer) pending.set(`In response to: ${prompt.question}\n\n${answer}`, { id: part.id, answer, question: prompt.question }); + } else if (part.type === "steer" && part.orx?.from && answeredBy.has(part.orx.from)) { + prompts.add(answeredBy.get(part.orx.from)!); + answeredBy.delete(part.orx.from); } else if (part.type === "steer" && part.text) { matchReply(part.id, part.text); } @@ -125,7 +132,7 @@ export function partIsVisible(part: ChatPart, activePermissionId?: string | null } // Hidden reasoning must not displace a visible tool tail during brief thinking bursts. if (part.type === "reasoning") return false; - if (part.type === "text") return Boolean(part.text); + if (part.type === "text") return Boolean(part.text) || Boolean(part.orx); return true; } diff --git a/ui/src/components/AgentMessageCard.tsx b/ui/src/components/AgentMessageCard.tsx new file mode 100644 index 000000000..d8af5cab2 --- /dev/null +++ b/ui/src/components/AgentMessageCard.tsx @@ -0,0 +1,132 @@ +import { useContext, useState, type ComponentProps } from "react"; +import { ChevronDown, CircleAlert, CircleCheck, CircleX, MessagesSquare, TriangleAlert } from "lucide-react"; +import { useQuery } from "@tanstack/react-query"; + +import { fmtDuration, type ChatPart, type OrxSource } from "../api"; +import { listRunsQuery } from "../queries/projects"; +import { CITED_ID, firstLine } from "../agentMessages"; +import { m } from "../paraglide/messages.js"; +import { tabOpenGestureHandlers } from "../tabPreview"; +import { ChatLinksContext, CitedWords } from "./ChatLinks"; +import { FileScopeContext } from "./FileReference"; +import { HarnessLogo } from "./HarnessLogo"; +import { Md } from "./Md"; + +type Props = { + part: ChatPart & { orx: OrxSource }; + runExperimentName?: (runId: string) => string; + onOpenFile?: ComponentProps["onOpenFile"]; + onOpenRun?: ComponentProps["onOpenRun"]; +}; + +/** A message orx or another chat's agent wrote, on the left under its sender. */ +export function AgentMessageCard(props: Props) { + return props.part.orx.kind === "run" ? : ; +} + +/** A run that ended: its experiment, outcome and how long it ran, opening its logs. */ +function RunCard({ part, runExperimentName, onOpenRun }: Props) { + const { from: runId, status } = part.orx; + const scope = useContext(FileScopeContext); + const { data: run } = useQuery({ + ...listRunsQuery(scope?.projectId ?? ""), + enabled: Boolean(scope && runId), + select: (runs) => runs.find((candidate) => candidate.id === runId), + }); + const took = run?.endedAt ? fmtDuration(run.endedAt - run.createdAt) : null; + const [Icon, label, tone] = status === "done" + ? [CircleCheck, took ? m.run_done_in({ duration: took }) : m.status_done(), "bg-accent-green-subtle [&_.tone]:text-accent-green"] + : status === "failed" + ? [CircleX, took ? m.run_failed_after({ duration: took }) : m.status_failed(), "bg-accent-red-subtle [&_.tone]:text-accent-red"] + : [CircleAlert, m.status_lost(), "bg-accent-amber-subtle [&_.tone]:text-accent-amber"]; + const name = (runId && runExperimentName?.(runId)) || m.tree_experiment(); + return ( + + ); +} + +/** A task, message, answer or question from another chat, or orx's warning + * about runs: its sender opens that chat, the rest opens the whole message. */ +function SentCard({ part, onOpenFile, onOpenRun }: Props) { + const [open, setOpen] = useState(false); + const links = useContext(ChatLinksContext); + const { kind, from } = part.orx; + const text = part.text ?? ""; + const chat = kind === "monitoring" || !from ? undefined : links?.chat(from); + const sender = kind === "monitoring" + ? m.agent_message_openresearch() + : chat?.title || m.agent_message_other_chat(); + const icon = kind === "monitoring" + ?