Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions cmux-tui/crates/acpmux/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,7 @@ acpmux pending # every pending pe
acpmux session deny NAME # an allow is the cmux app's alone (the chat's permission card)
acpmux session rules NAME '{"autoDeny": ["rm -rf"], "ask": ["execute"], "default": "approve"}'
acpmux session limits NAME [--max N | --clear] # sub-sessions running at once (more wait), running and queued now
acpmux session turn-cap NAME [--minutes N | --off | --clear] # past it, other agents' messages wait for the next turn
acpmux session tag NAME task=review --ttl 3600; acpmux ls --tag task=review
acpmux ls --status running | --pending # filters; --json for the full records
acpmux ls --limit 20 --fields name,harness,model,status,cwd # newest sessions, selected fields
Expand Down
3 changes: 2 additions & 1 deletion cmux-tui/crates/acpmux/docs/acpmux-schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@
"_acpmux/permission_chat_revoke": {"params":{"sessionId":"string"}, "result":{"active":false}, "note":"Revokes future chat approvals; already accepted operations are not undone."},
"_acpmux/set_policy": {"params": {"sessionId": "string", "policy": "ask|approve-reads|approve-edits|approve-all|deny-all"}, "result": "SessionSummary"},
"_acpmux/set_rules": {"params": {"sessionId": "string", "rules": "{autoApprove?: string[], autoDeny?: string[], ask?: string[], default?: 'approve'|'deny'|'ask'} | null"}, "result": "SessionSummary"},
"_acpmux/set_turn_cap": {"params": {"sessionId": "string", "turnCapMs": "number? (ms; 0 turns the cap off) | null (clears the session's own value) | absent (reads it)"}, "result": {"sessionId": "string", "turnCapMs": "number? (the session's own value)", "effectiveTurnCapMs": "number? (the cap in force: its own, else the default its settings give; absent: no cap)"}, "errors": "data.reason permission.person_required: a write from anything but the app or the local unix socket with no agent caller", "note": "hub/turn_cap.rs. Past the cap, the running turn takes no other agent's steer: agent messages wait in the queue and the next turn takes them together (a steerOnly one is refused steer.unavailable with data.turnCap true). The person's own steers still go in. The hub steers one notice per turn (provenance kind turn_cap) once an agent message waits, and never cancels the turn."},
"_acpmux/set_tools": {"params": {"sessionId": "string", "id": "string (a ToolRow id)", "enabled": "boolean"}, "result": {"sessionId": "string", "tools": "ToolRow[]", "toolsMutable": "true", "applied": "now|afterTurn|nextStart (now: the idle chat's Claude Code restarted on it and resumed; afterTurn: a turn runs, and its process restarts when it ends; nextStart: no process runs, and the next start takes it)"}, "errors": "data.reason tools.immutable: the harness takes its tools when the chat starts (toolsMutable false: every ACP harness; refused without starting the chat); tools.fixed: canToggle false (a skill, a plugin, or a server the user's own Claude config turned off); tools.remote: a remote WebSocket connection (only the app or the unix socket); code -32002: no such row", "note": "Records the chat's choice for one MCP server: every start of its Claude Code gets --disallowedTools mcp__<server> for each server that is off, so it survives respawn, resume and daemon restart, and a fork keeps it. Claude Code's mcp_toggle is never sent (it persists into ~/.claude.json for every session in the folder). Watchers get _acpmux/session_changed kind tools. initialize lists the feature toolInventory (cx-thur3)."},
"_acpmux/mcp/reconnect": {"params": {"sessionId": "string", "server": "string (an MCP server's name, its ToolRow id without mcp:)"}, "result": "{}", "errors": "data.reason mcp.unsupported: the chat's harness is not Claude Code; tools.remote: a remote WebSocket connection (only the app or the unix socket); invalid params: no server, or the chat's Claude Code is not running (its servers connect when it starts); code -32002: the chat has no such server; internal: Claude Code refused (its error) or did not answer in 30 s", "note": "Sends Claude Code's mcp_reconnect control request (serverName = server) to the running process; never starts one. Once Claude Code reconnected it, its ToolRow status (and mcpServers) reads connected until the next system/init, and watchers get _acpmux/session_changed kind tools. initialize lists capability mcp-reconnect-v1."},
"_acpmux/archive": {"params": {"sessionId": "string", "archived": "boolean"}, "result": "SessionSummary", "note": "The chat menu's Archive (true: sets the `archived` tag to now in milliseconds; the lists hide the chat) or Unarchive (false: removes it). One tag with one value, so a page relay allows it without reading tag names (cx-jlzsf)."},
Expand Down Expand Up @@ -152,7 +153,7 @@
"turn_result": {"status": "completed|cancelled|failed", "stopReason": "string?", "turnId": "string (shared with turn_started)", "turnSeq": "number (seq of turn_started)", "promptId": "string", "error": "string?", "code": "number?", "errorText": "string? (why the turn failed; a terminal error the harness reported in-band, such as Codex _meta.codex.error without willRetry, fails the turn and the prompt is answered with that error)", "errorCode": "number|object|null", "errorSource": "agent|codex|acpmux (acpmux: a stalled turn acpmux ended)", "errorChunkSeqs": "number[]? (the trailing agent_message_chunk records whose text is exactly errorText: hide them, show the error)", "detail": "string? (outcome_unknown when the daemon restarted mid-turn; stalled when its model showed no sign of work for config stalledTurnEndMs, default 21600000, 0: never, four times that inside a tool call that had not ended, and nobody held the turn: hub/stalled_turn.rs)", "stalledMs": "number? (with detail stalled: how long the model had been silent)", "model": "string? (the session's model when an answered turn ended)", "costUsd|inputTokens|outputTokens|cacheReadTokens|cacheWriteTokens": "TurnUsage fields of an answered turn, as its harness reported them (a fork's log copies its parent's records before its forked record: count those once)", "gitBranch": "string? (the branch checked out in the session's cwd when the turn ended, answered or failed; absent on a detached HEAD, outside a repository, when git could not be read within 2 s, and in older logs)", "gitHead": "string? (the full HEAD commit at that moment, as gitBranch)"},
"git": {"gitBranch": "string|null (the branch the session's cwd has checked out now; null on a detached HEAD or outside a repository)", "note": "Written when the branch changes while a client holds the chat (a watch on the folder's HEAD, hub/git_watch.rs; no polling), and on the next attach for a change made while none did. Never for a branch the log's last git record already told, a daemon restart included. The branch the session started on (session.json gitBranch) never changes."},
"EventKinds": "string[]: each entry is a category or an exact record kind; a record passes when any entry matches. Categories: transcript (agent session/update except .replay, usage_update, available_commands_update, current_mode_update, config_option_update; plus mux user_message, queued, dequeued, turn_started, turn_silent, turn_heard, turn_result, permission_request, permission_auto, permission_decision, permission_group, permission_chat_allowance, message_superseded, failover, policy_unenforced, forked, imported, mode, model, stopped, exited), mux (every mux record), wire (in/out requests, responses, harness lines and .replay records), all.",
"user_message": {"text": "string", "client": "string", "promptId": "string", "turnId": "string", "steer": "boolean? (steered into the running turn)", "images": "[{id, mimeType, name?}]? (the prompt's images, kept under their ids; _acpmux/attachment reads one back)", "inlineParts": "[{kind: text, text, pasted?: true} | {kind: image, id, mimeType, name?, persisted?: false} | {kind: pasted|file, name, mimeType?, size?, text?} | {kind: document|audio, name, mimeType?, size?, pageCount?} | {kind: file, name, uri?, mimeType?}]? (ACP prompt blocks in original order; attachment data is never stored; text on file/pasted parts is copied from the corresponding ACP text block)", "pasted": "[{start: number, end: number}]? (each text block the client marked _meta.cmux.pasted, as UTF-16 code-unit offsets into text, so text.slice(start, end) is the paste; absent when nothing was pasted)", "_meta.provenance": "{kind: \"agent_message\", from, fromName?, to, msgId, threadId, replyTo?}? (the prompt's _meta.acpmux.provenance: an agent's message, not the person's words)"},
"user_message": {"text": "string", "client": "string", "promptId": "string", "turnId": "string", "steer": "boolean? (steered into the running turn)", "images": "[{id, mimeType, name?}]? (the prompt's images, kept under their ids; _acpmux/attachment reads one back)", "inlineParts": "[{kind: text, text, pasted?: true} | {kind: image, id, mimeType, name?, persisted?: false} | {kind: pasted|file, name, mimeType?, size?, text?} | {kind: document|audio, name, mimeType?, size?, pageCount?} | {kind: file, name, uri?, mimeType?}]? (ACP prompt blocks in original order; attachment data is never stored; text on file/pasted parts is copied from the corresponding ACP text block)", "pasted": "[{start: number, end: number}]? (each text block the client marked _meta.cmux.pasted, as UTF-16 code-unit offsets into text, so text.slice(start, end) is the paste; absent when nothing was pasted)", "_meta.provenance": "{kind: \"agent_message\", from, fromName?, to, msgId, threadId, replyTo?}? (the prompt's _meta.acpmux.provenance: an agent's message, not the person's words); hub-set {kind: \"turn_cap\", turnId, capMs} on the one notice steered into a turn past its turn cap (_acpmux/set_turn_cap), never a client's"},
"queued": {"text": "string", "client": "string", "position": "number", "promptId": "string", "turnId": "string", "images": "[{id, mimeType, name?}]? (as user_message: the prompt's images, kept under their ids when it was queued; an _acpmux/queue_edit update records its own on queue_updated)", "inlineParts": "as user_message.inlineParts (fresh ordered metadata from queued blocks)", "pasted": "[{start, end}]? (as user_message; an _acpmux/queue_edit update records its own on queue_updated)", "_meta.provenance": "object? (as user_message; a restart keeps it, an _acpmux/queue_edit update drops it)", "fromAgent": "string? (another agent's message: its sender)", "class": "block|question|result|fyi? (another agent's message: what it asks of the chat, session/prompt _meta.acpmux.class, result when it named none; a restart keeps it, an _acpmux/queue_edit update drops it)"},
"dequeued": {"promptId": "string", "turnId": "string", "queued": "number (still waiting)"},
"queue_removed": {"promptId": "string", "turnId": "string", "queued": "number (still waiting)", "reason": "withdrawn? (_acpmux/prompt_withdraw; absent for _acpmux/queue_remove)"},
Expand Down
6 changes: 6 additions & 0 deletions cmux-tui/crates/acpmux/spec/acpmux-protocol.json
Original file line number Diff line number Diff line change
Expand Up @@ -934,6 +934,12 @@
"params": true,
"result": true
},
{
"kind": "request",
"name": "_acpmux/set_turn_cap",
"params": true,
"result": true
},
{
"kind": "request",
"name": "_acpmux/person_enroll",
Expand Down
20 changes: 20 additions & 0 deletions cmux-tui/crates/acpmux/src/cli/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -438,6 +438,8 @@ pub enum Command {
#[command(hide = true)]
LimitsCmd { session: String, max: Option<u32>, clear: bool },
#[command(hide = true)]
TurnCapCmd { session: String, minutes: Option<u64>, off: bool, clear: bool },
#[command(hide = true)]
Schema,
#[command(hide = true)]
Models {
Expand Down Expand Up @@ -890,6 +892,21 @@ pub enum SessionCmd {
#[arg(long)]
clear: bool,
},
/// The turn cap: past it, the running turn takes no other agent's message (they wait for the
/// next turn, and the agent is told once to end its turn); the person's still go in. Omit
/// the flags to show it; setting it takes the app or this socket, never an agent.
TurnCap {
session: String,
/// The cap in minutes (1 to 1440).
#[arg(long, value_parser = clap::value_parser!(u64).range(1..=1440), conflicts_with_all = ["off", "clear"])]
minutes: Option<u64>,
/// No cap for this session, whatever its default.
#[arg(long, conflicts_with = "clear")]
off: bool,
/// Drop the session's own value: back to its default.
#[arg(long)]
clear: bool,
},
/// One line per turn.
History {
session: String,
Expand Down Expand Up @@ -1169,6 +1186,9 @@ pub fn flatten(c: Command) -> Command {
SessionCmd::Limits { session, max, clear } => {
Command::LimitsCmd { session, max, clear }
}
SessionCmd::TurnCap { session, minutes, off, clear } => {
Command::TurnCapCmd { session, minutes, off, clear }
}
SessionCmd::Rules { session, rules, clear } => {
Command::RulesCmd { session, rules, clear }
}
Expand Down
1 change: 1 addition & 0 deletions cmux-tui/crates/acpmux/src/cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ pub(crate) mod send_relay;
pub mod sender;
pub mod session_folder;
pub mod session_limits;
pub mod session_turn_cap;
pub mod shutdown;
pub mod stdio;
pub(crate) mod steer_reply;
Expand Down
11 changes: 11 additions & 0 deletions cmux-tui/crates/acpmux/src/cli/run/extra.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,17 @@ pub(super) async fn run(cmd: Command, json_out: bool, _suppress_reads: bool) ->
let client = connect(true).await?;
crate::cli::session_limits::run(&client, &session, max, clear, json_out).await
}
Command::TurnCapCmd { session, minutes, off, clear } => {
use crate::cli::session_turn_cap::Change;
let change = match (minutes, off, clear) {
(Some(m), _, _) => Change::Minutes(m),
(None, true, _) => Change::Off,
(None, false, true) => Change::Clear,
(None, false, false) => Change::Show,
};
let client = connect(true).await?;
crate::cli::session_turn_cap::run(&client, &session, change, json_out).await
}
Command::ResumeQueue { session } => {
let client = connect(true).await?;
let id = crate::cli::resolve::control_id(&client, &session).await?;
Expand Down
82 changes: 82 additions & 0 deletions cmux-tui/crates/acpmux/src/cli/session_turn_cap.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
//! `acpmux session turn-cap SESSION [--minutes N | --off | --clear]`: a session's turn cap
//! (`hub/turn_cap.rs`). Past it, the running turn takes no other agent's steer; their messages
//! wait for the next turn. With no flag it shows the cap; a write goes through
//! `_acpmux/set_turn_cap`, which takes the person (the app or this socket), never an agent.

use crate::cli::output::print_json;
use crate::cli::run::resolve_id;
use crate::client::Client;
use crate::rpc::method;
use anyhow::Result;
use serde_json::{Value, json};

/// What the command asks for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Change {
Show,
Minutes(u64),
Off,
Clear,
}

/// The request's params for `change`.
pub fn params(id: &str, change: Change) -> Value {
match change {
Change::Show => json!({"sessionId": id}),
Change::Minutes(m) => json!({"sessionId": id, "turnCapMs": m.saturating_mul(60_000)}),
Change::Off => json!({"sessionId": id, "turnCapMs": 0}),
Change::Clear => json!({"sessionId": id, "turnCapMs": Value::Null}),
}
}

pub async fn run(client: &Client, session: &str, change: Change, json_out: bool) -> Result<()> {
let id = resolve_id(client, session).await?;
let reply = client.request(method::MUX_SET_TURN_CAP, params(&id, change)).await?;
if json_out {
print_json(&reply);
} else {
println!("{}", describe(&reply));
}
Ok(())
}

/// The cap as a line a person reads.
pub fn describe(reply: &Value) -> String {
let own = reply["turnCapMs"].as_u64();
match reply["effectiveTurnCapMs"].as_u64() {
None if own == Some(0) => "no turn cap (turned off for this session)".to_owned(),
None => "no turn cap".to_owned(),
Some(ms) => {
let from = if own.is_some() { "this session's" } else { "default" };
format!("turn cap {} min ({from})", ms.div_ceil(60_000))
}
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn each_change_is_one_request_shape() {
assert_eq!(params("s", Change::Show), json!({"sessionId": "s"}));
assert_eq!(params("s", Change::Minutes(20))["turnCapMs"], 1_200_000);
assert_eq!(params("s", Change::Off)["turnCapMs"], 0);
assert!(params("s", Change::Clear)["turnCapMs"].is_null());
}

#[test]
fn describe_names_the_cap_and_where_it_comes_from() {
let r = |own: Value, eff: Value| json!({"turnCapMs": own, "effectiveTurnCapMs": eff});
assert_eq!(describe(&r(Value::Null, Value::Null)), "no turn cap");
assert_eq!(
describe(&r(json!(0), Value::Null)),
"no turn cap (turned off for this session)"
);
assert_eq!(
describe(&r(json!(600_000), json!(600_000))),
"turn cap 10 min (this session's)"
);
assert_eq!(describe(&r(Value::Null, json!(1_200_000))), "turn cap 20 min (default)");
}
}
3 changes: 3 additions & 0 deletions cmux-tui/crates/acpmux/src/hub/fork.rs
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,9 @@ impl Hub {
// A fork is the person's branch of the chat, never a spawn (`lineage.rs`).
lineage: None,
subagent_retry_open: false,
// The person's setting for the chat it came from, not for the fork.
turn_cap_ms: None,
turn_cap_noticed: None,
};
let new = self.make_session(meta);
match made {
Expand Down
1 change: 1 addition & 0 deletions cmux-tui/crates/acpmux/src/hub/handoff/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -609,6 +609,7 @@ impl Hub {
display_parts: None,
full_access_device: None,
no_queue: false,
send_now: false,
};
let (hub, session) = (self.clone(), target.clone());
let run =
Expand Down
5 changes: 5 additions & 0 deletions cmux-tui/crates/acpmux/src/hub/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ mod tap;
mod titles;
mod tool_paths;
mod tools;
pub(crate) mod turn_cap;
mod watch;
pub use new_request::{
NewRequest, declared_model_json, profile_takes_model_at_spawn, terminal_harness_refusal,
Expand Down Expand Up @@ -357,6 +358,9 @@ pub struct PromptOptions {
/// A person's subagent retry (`subagent_retry_manual.rs`): refused with `retry.busy` where it
/// would wait (behind a turn, the queue, the turn lock or a run slot), never queued.
pub no_queue: bool,
/// A queued prompt sent now (`queue.rs` `steer_queued`): it steers in even past the running
/// turn's cap (`turn_cap.rs`).
pub send_now: bool,
}

/// The outcome of one client prompt id, shared with a resend of it.
Expand Down Expand Up @@ -1092,6 +1096,7 @@ impl Hub {
stalled_gen: AtomicU64::new(0),
last_model_at: AtomicU64::new(0),
silent_turn: StdMutex::new(None),
turn_cap_timer: StdMutex::new(None),
last_active: AtomicU64::new(self.clock_now()),
hibernated_at: AtomicU64::new(hibernated_at),
wake_cause: StdMutex::new(None),
Expand Down
1 change: 1 addition & 0 deletions cmux-tui/crates/acpmux/src/hub/queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,7 @@ impl Hub {
class: run.class,
display_parts: run.display_parts.clone(),
full_access_device: run.full_access_device.clone(),
send_now: true,
..Default::default()
};
Box::pin(self.run_prompt(session, run.blocks.clone(), client, true, opts)).await
Expand Down
2 changes: 2 additions & 0 deletions cmux-tui/crates/acpmux/src/hub/resolve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -365,5 +365,7 @@ pub(super) fn draft_meta(d: Draft<'_>) -> SessionMeta {
subsession_limits: Default::default(),
lineage: None,
subagent_retry_open: false,
turn_cap_ms: None,
turn_cap_noticed: None,
}
}
2 changes: 2 additions & 0 deletions cmux-tui/crates/acpmux/src/hub/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,8 @@ pub struct Session {
pub(super) last_model_at: AtomicU64,
/// The turn that logged `turn_silent` and has not heard its model since (`silent_turn.rs`).
pub(super) silent_turn: StdMutex<Option<String>>,
/// The turn cap's timer for the running turn (`turn_cap.rs`); the next turn aborts it.
pub(super) turn_cap_timer: StdMutex<Option<tokio::task::AbortHandle>>,
/// The hub clock's time (`Hub::clock_now`) of the last record or
/// attach change; the idle harness exit counts from it (`idle.rs`).
pub(super) last_active: AtomicU64,
Expand Down
Loading
Loading