diff --git a/README.md b/README.md index 1655ab8..fbd23fc 100644 --- a/README.md +++ b/README.md @@ -15,11 +15,18 @@ Every session runs in m4code's native chat view over the [Agent Client Protocol] | **Claude Code** | `claude` CLI, Node, npm | Runs through the [Claude Agent SDK](https://code.claude.com/docs/en/agent-sdk/overview) (installed into m4code's data folder on first run) using whatever sign-in your `claude` has (subscription, API key, Bedrock, or Vertex). Disables `claude.ai`-only tools (scheduled tasks, push notifications, connectors) for m4code sessions only. Includes a Claude in Chrome toggle. | | **Codex** | Node, `codex login` | Runs through its ACP adapter from npm (downloaded on first run). | | **OpenCode** | `opencode` on `PATH` | Uses the providers configured in OpenCode. | -| **Google Antigravity** | `agy` CLI, signed in | Opt-in for subagent use. | +| **Google Antigravity** | `agy` CLI, signed in | Interactive only: see the terms note below. Opt-in for subagent use. | When upgrading from a version with multiple Claude accounts, resumed sessions use the login configured for the Claude CLI. Expired logins offer **Sign in** and **Retry session** in the conversation. Failed sessions retain their history and queued messages. A session that stops reporting progress offers Stop and Reconnect; reconnecting does not automatically repeat the last prompt. -> **Antigravity terms note**: Google's [Antigravity terms](https://antigravity.google/terms) and [FAQ](https://antigravity.google/docs/faq) forbid using another company's agent (such as Claude Code) with a personal Google sign-in (Free, AI Plus, Pro, or Ultra), and Google can suspend or terminate accounts that do. Turn Antigravity subagents on at your own risk. +> **Antigravity terms note**: Google's [Antigravity terms](https://antigravity.google/terms) and [FAQ](https://antigravity.google/docs/faq) forbid using another company's agent (such as Claude Code) with a personal Google sign-in (Free, AI Plus, Pro, or Ultra), and Google can suspend or terminate accounts that do. m4code keeps Antigravity to sessions you type in: +> +> - Rewind and fork are off in Antigravity sessions, and m4code doesn't compact one itself. Only Antigravity's own `/compact` runs, when Antigravity lists it. +> - Conversations from other models can't be handed to Antigravity. You can hand an Antigravity conversation to another model yourself, but auto-handoff and an agent's `set_model` can't. +> - Antigravity can't be the text generation model. A saved choice switches back to the local summary. +> - **Allow subagent delegation** and **Allow cross-harness subagents** start off for Antigravity. Turn them on at your own risk. +> - Antigravity sessions don't get `start_code_session` or `read_code_session`, so they can't start sessions or read other ones. +> - Antigravity's usage meter updates only when you press refresh. ## Features @@ -57,13 +64,14 @@ When upgrading from a version with multiple Claude accounts, resumed sessions us - Right sidebar with cards for actions, the turn outline, session status, subagents, GitHub issues and pull requests, and linked sessions, plus inline visual cards agents draw in chat. - GitHub labels, assignees, edits, and comments update immediately while saving. Failed edits restore the previous content and retain the draft. If a comment posts but closing the item fails, retry close/reopen separately to avoid posting twice. - **Ask Agent** in the GitHub pane sends the request to the active agent if it is running in the repository. When it starts a new session, it uses the model selected in the Welcome composer. - - Usage meters in the sidebar footer for connected harnesses with a limits adapter (Claude Code and Codex 5-hour/7-day limits). Usage dashboard links for OpenCode and Antigravity are shown only when their harnesses are enabled. - - Configurable text generation model (**Settings → General**) for automatic new-session titles, Regenerate title and Commit & Push—pick any enabled model or keep local summary. + - Usage meters in the sidebar footer for connected harnesses with a limits adapter (Claude Code, Codex and Antigravity 5-hour/7-day limits). Antigravity's meter updates only when you press refresh. The usage dashboard link for OpenCode is shown only when its harness is enabled. + - Configurable text generation model (**Settings → General**) for automatic new-session titles, Regenerate title and Commit & Push—pick any enabled model except Antigravity, or keep local summary. ### Cross-agent subagents - **Shared MCP subagent tools**: Sessions across all harnesses share `spawn_subagent`, `list_subagents`, `send_subagent_message`, `wait_subagent`, and `stop_subagent` (targeting adapters enabled for subagent use in Settings). Children run in the parent's working folder without stealing focus, appear in the right sidebar, and fold their report back into the parent chat. Follow-ups reuse the child session, stopping a parent stops its children, and a read-only parent cannot grant edits. Sessions are conversations for the user and are created only when the user wants one. Subagents are workers the model uses to delegate work within its current session. - **Claude Code native subagents**: Claude Code can also start Codex, OpenCode, and (opt-in) Antigravity subagents directly. These plugin-run children receive the shared workspace context tool. Desktop-managed children have their own records and can use the session tools. Each streams its work in its own task view with configurable effort (`max` maps to Codex's `xhigh`; Antigravity caps at the model's highest thinking level) and supports live or queued follow-ups. +- **Cross-harness subagents**: **Allow cross-harness subagents** (**Settings → Harnesses**) decides whether other harnesses can run a harness as a subagent and whether its sessions can start subagents or sessions on other harnesses, or move a conversation to them on their own, through `set_model` or auto-handoff. A subagent on another harness needs it on for both. It starts on for every harness except Antigravity. - **Edit permissions**: With **Allow edits** enabled, a subagent acts without Claude Code's permission rules. Read-only Antigravity runs in an isolated folder under m4code's data directory with a hook that permits only reading and searching (your personal Antigravity rules, skills, and MCP servers do not load there). ### Skills diff --git a/src/app/act.rs b/src/app/act.rs index 4475918..5fb4200 100644 --- a/src/app/act.rs +++ b/src/app/act.rs @@ -364,7 +364,7 @@ impl Workspace { let list_focus = cx.focus_handle(); window.focus(&list_focus, cx); let custom = &self.store.data.settings.custom_subagents; - let form = |c: &harness::subagents::AgentChoice| AgentForm { on: c.on, models: c.models.clone(), edits: c.edits }; + let form = |c: &harness::subagents::AgentChoice| AgentForm { on: c.on, models: c.models.clone(), edits: c.edits, cross_harness: c.cross_harness }; let subagents = Box::new(HarnessesForm { enabled: self.store.data.settings.enabled_harnesses_list(), agents: harness::subagents::AgentMap::from_fn(|agent| form(custom.get(agent))), diff --git a/src/app/agent_handoff.rs b/src/app/agent_handoff.rs index c6dd209..10c772d 100644 --- a/src/app/agent_handoff.rs +++ b/src/app/agent_handoff.rs @@ -50,7 +50,11 @@ impl Workspace { let refusal = if !self.store.data.settings.harness_enabled(to) { Some(format!("{} is unavailable for this session.", to.name())) } else { - capabilities::handoff(thread.read(cx).harness, to, initiator).refusal().map(String::from) + let from = thread.read(cx).harness; + // An agent's switch checks "Allow cross-harness subagents" again here: either may have been turned off since + // `set_model` accepted it. + let crossing = if by_agent { capabilities::crossing(&self.store.data.settings, from, to) } else { capabilities::Capability::Allowed }; + capabilities::handoff(from, to, initiator).refusal().or(crossing.refusal()).map(String::from) }; if let Some(refusal) = refusal { if !by_agent { diff --git a/src/app/cross.rs b/src/app/cross.rs index e98197d..1dae631 100644 --- a/src/app/cross.rs +++ b/src/app/cross.rs @@ -103,6 +103,13 @@ impl Workspace { /// Check what the request needs. A new session's folder, or the worktree to switch to, is resolved into `req.args["folder"]`. fn prepare(&self, req: &mut Request, cx: &App) -> Result<(), String> { + // The tool isn't offered to such a session at all; this refuses a call that reaches m4code anyway. + let asking = req.from.split_once(':').map_or(req.from.as_str(), |(_, id)| id); + if let Some(harness) = self.store.session(asking).and_then(SessionRecord::harness) + && harness.adapter().mcp_off.contains(&req.tool.as_str()) + { + return Err(format!("{} sessions can't use {}.", harness.name(), req.tool)); + } if req.tool == "switch_worktree" { return self.prepare_switch(req); } @@ -305,6 +312,12 @@ impl Workspace { "start_code_session" => { let cwd = folder.ok_or("No folder.")?; let harness = req.args["harness"].as_str().and_then(|key| crate::harness::Harness::registered().find(|h| h.key() == key)).unwrap_or_else(|| self.store.data.settings.default_model().harness); + let asking = req.from.split_once(':').map_or(req.from.as_str(), |(_, id)| id); + if let Some(from) = self.store.session(asking).and_then(SessionRecord::harness) + && let Some(refusal) = crate::harness::capabilities::crossing(&self.store.data.settings, from, harness).refusal() + { + return Err(refusal.into()); + } // The model may pick the model and effort; the permission mode stays the user's default for new // sessions (`Starter::OtherSession` never starts with full access). let mut options = vec![]; @@ -349,7 +362,9 @@ impl Workspace { match model { Some(model) if req.args["cross"].as_bool() == Some(true) => { let from = thread.read(cx).harness; - if let Some(refusal) = crate::harness::capabilities::handoff(from, model.harness, crate::harness::capabilities::Initiator::Automatic).refusal() { + let handoff = crate::harness::capabilities::handoff(from, model.harness, crate::harness::capabilities::Initiator::Automatic); + let crossing = crate::harness::capabilities::crossing(&self.store.data.settings, from, model.harness); + if let Some(refusal) = handoff.refusal().or(crossing.refusal()) { return Err(refusal.into()); } let message = req.args["message"].as_str().map(str::trim).filter(|m| !m.is_empty()).map_or_else(|| "Carry on with the task from where the conversation left off.".into(), String::from); diff --git a/src/app/headless/agents.rs b/src/app/headless/agents.rs index aae2b06..10015d2 100644 --- a/src/app/headless/agents.rs +++ b/src/app/headless/agents.rs @@ -65,21 +65,21 @@ r#" send({"jsonrpc": "2.0", "id": i, "result": {"modes": session_modes()} assert!(ws.new_session_from_home(Harness::Claude, None, work.path().to_path_buf(), Some("initial task".into()), None, Some(Permission::Auto), window, cx)); }); let id = ws.read_with(&cx, |ws, _| ws.active_id().unwrap().clone()); - let wait = |cx: &mut TestAppContext, harness| { + let wait = |cx: &mut TestAppContext, id: &str, harness| { let until = std::time::Instant::now() + Duration::from_secs(10); loop { cx.run_until_parked(); if ws.read_with(cx, |ws, app| { - ws.pending_handoffs.is_empty() && ws.live_view(&id).and_then(|v| v.thread()).is_some_and(|view| { + ws.pending_handoffs.is_empty() && ws.live_view(id).and_then(|v| v.thread()).is_some_and(|view| { let view = view.read(app); view.harness == harness && !view.is_loading() && !view.is_working() && view.thread.entries.iter().any(|e| matches!(e, Entry::Agent(text) if text == "ok")) }) }) { break; } if std::time::Instant::now() >= until { ws.read_with(cx, |ws, app| { - let view = ws.live_view(&id).and_then(SessionView::thread).map(|view| view.read(app)); + let view = ws.live_view(id).and_then(SessionView::thread).map(|view| view.read(app)); panic!("handoff to {harness:?} never settled: pending={}, view={:?}, toast={:?}", - ws.pending_handoffs.contains_key(&id), + ws.pending_handoffs.contains_key(id), view.map(|view| (view.harness, view.is_loading(), view.is_working(), view.start_error(), &view.thread.entries)), ws.toast.as_ref().map(|toast| &toast.text)); }); @@ -87,7 +87,7 @@ r#" send({"jsonrpc": "2.0", "id": i, "result": {"modes": session_modes()} std::thread::yield_now(); } }; - wait(&mut cx, Harness::Claude); + wait(&mut cx, &id, Harness::Claude); for (harness, message, expected) in [ (Harness::OpenCode, "continue on B", Permission::FullAccess), (Harness::Claude, "continue on A", Permission::Auto), @@ -99,7 +99,7 @@ r#" send({"jsonrpc": "2.0", "id": i, "result": {"modes": session_modes()} cx.update_window(window, |_, window, app| window.draw(app).clear(app)).unwrap(); let mut visual = VisualTestContext::from_window(window, &cx); assert!(visual.debug_bounds("thread-mode").is_some(), "the permission chip stays visible through the handoff"); - wait(&mut cx, harness); + wait(&mut cx, &id, harness); ws.read_with(&cx, |ws, app| { let view = ws.live_view(&id).unwrap().thread().unwrap().read(app); assert_eq!(view.permission(), Some(expected)); @@ -144,7 +144,7 @@ r#" send({"jsonrpc": "2.0", "id": i, "result": {"modes": session_modes()} ws.acp_server = Some(failed_server.clone()); ws.dynamic_handoff(&id, Harness::Codex, None, "keep this draft".into(), false, None, window, cx); }); - wait(&mut cx, Harness::Claude); + wait(&mut cx, &id, Harness::Claude); ws.read_with(&cx, |ws, app| { assert_eq!(ws.store.session(&id).unwrap().agent.as_ref().unwrap().harness, Harness::Claude); let view = ws.live_view(&id).unwrap().thread().unwrap().read(app); @@ -154,30 +154,43 @@ r#" send({"jsonrpc": "2.0", "id": i, "result": {"modes": session_modes()} Entry::Notice { text, error: true, .. } if text.contains("handshake failed"))).count(), 1); assert!(view.thread.active_notice(crate::harness::thread::NoticeKind::Handoff).is_none()); }); + // Antigravity takes no conversation from another model (Google's terms), so the session stays on Claude Code. step(&mut cx, &|ws, window, cx| { ws.acp_server = Some(server_for("antigravity")); ws.dynamic_handoff(&id, Harness::Antigravity, None, "continue on C".into(), false, None, window, cx); }); - wait(&mut cx, Harness::Antigravity); + wait(&mut cx, &id, Harness::Claude); + ws.read_with(&cx, |ws, app| { + assert_eq!(ws.store.session(&id).unwrap().agent.as_ref().unwrap().harness, Harness::Claude); + let view = ws.live_view(&id).unwrap().thread().unwrap().read(app); + assert!(view.thread.entries.iter().any(|entry| matches!(entry, + Entry::Notice { text, error: true, .. } if text.contains("Antigravity terms"))), "the refusal says why"); + }); + // A session that starts on Antigravity relaunches it for a permission change and keeps its provider session. + step(&mut cx, &|ws, window, cx| { + assert!(ws.new_session_from_home(Harness::Antigravity, None, work.path().to_path_buf(), Some("continue on C".into()), None, Some(Permission::Auto), window, cx)); + }); + let antigravity = ws.read_with(&cx, |ws, _| ws.active_id().unwrap().clone()); + wait(&mut cx, &antigravity, Harness::Antigravity); for permission in [Permission::FullAccess, Permission::ReadOnly] { step(&mut cx, &|ws, _, cx| { - let view = ws.live_view(&id).unwrap().thread().unwrap().clone(); + let view = ws.live_view(&antigravity).unwrap().thread().unwrap().clone(); view.update(cx, |view, cx| view.set_permission(permission, cx)); }); - wait(&mut cx, Harness::Antigravity); + wait(&mut cx, &antigravity, Harness::Antigravity); step(&mut cx, &|ws, window, cx| { - let meta = ws.store.session(&id).unwrap().agent.as_ref().unwrap(); + let meta = ws.store.session(&antigravity).unwrap().agent.as_ref().unwrap(); assert_eq!(meta.session_id, "fake-session"); assert_eq!(meta.launched_full_access, permission == Permission::FullAccess); - let view = ws.live_view(&id).unwrap().thread().unwrap().clone(); + let view = ws.live_view(&antigravity).unwrap().thread().unwrap().clone(); assert_eq!(view.read(cx).permission(), Some(permission)); - assert_eq!(view.read(cx).draft(cx), "keep this draft"); view.update(cx, |view, cx| view.send("check permission".into(), window, cx)); }); - wait(&mut cx, Harness::Antigravity); + wait(&mut cx, &antigravity, Harness::Antigravity); } let permissions = std::fs::read_to_string(work.path().join("fake_agent.py.permissions")).unwrap(); assert!(permissions.ends_with("antigravity:auto:False\nantigravity:default:True\nantigravity:plan:False\n")); + step(&mut cx, &|ws, window, cx| ws.end_live(&antigravity, window, cx)); step(&mut cx, &|ws, window, cx| ws.end_live(&id, window, cx)); } diff --git a/src/app/ingest.rs b/src/app/ingest.rs index f483325..0386680 100644 --- a/src/app/ingest.rs +++ b/src/app/ingest.rs @@ -89,11 +89,10 @@ impl Workspace { let now_instant = Instant::now(); let now_unix = crate::store::now(); for harness in Harness::registered() { - let Some(usage) = &harness.adapter().usage else { continue }; + let Some(every) = harness.adapter().usage.as_ref().and_then(|usage| usage.every) else { continue }; if !self.limits_harness_active(harness) { continue; } - let every = usage.every; let state = self.limits_state.get(harness); if state.loading || state.authentication_required { continue; @@ -212,6 +211,7 @@ impl Workspace { let now = crate::store::now(); let enabled = self.store.data.settings.enabled_harnesses_list(); let all = self.store.data.settings.aggregated_models(); + // `None` when nothing reports this harness's usage: unknown, not unused. let max_util = |h: Harness, model_id: Option<&str>| { self.usage_for_harness_model(h, model_id) .and_then(|u| { @@ -222,14 +222,13 @@ impl Workspace { .filter_map(|l| l.utilization) .reduce(f32::max) }) - .unwrap_or(0.0) }; let may_take_over = |h: Harness| h != excluded && handoff(excluded, h, Initiator::Automatic).allowed(); if let Some(pref) = &self.store.data.settings.auto_handoff_model && may_take_over(pref.harness) && enabled.contains(&pref.harness) && self.harness_probably_available(pref.harness) - && max_util(pref.harness, (!pref.id.is_empty()).then_some(pref.id.as_str())) < 0.95 + && max_util(pref.harness, (!pref.id.is_empty()).then_some(pref.id.as_str())).is_none_or(|util| util < 0.95) { let name = all .iter() @@ -237,7 +236,7 @@ impl Workspace { .map_or_else(|| pref.id.clone(), |m| m.name.clone()); return Some(crate::harness::CatalogModel { harness: pref.harness, id: pref.id.clone(), name }); } - let mut candidates: Vec<(f32, crate::harness::CatalogModel)> = enabled + let mut candidates: Vec<(Option, crate::harness::CatalogModel)> = enabled .into_iter() .filter(|&h| may_take_over(h) && self.harness_probably_available(h)) .filter_map(|h| { @@ -245,10 +244,11 @@ impl Workspace { crate::harness::CatalogModel { harness: h, id: String::new(), name: h.name().into() } }); let util = max_util(h, (!model.id.is_empty()).then_some(model.id.as_str())); - (util < 0.95).then_some((util, model)) + util.is_none_or(|util| util < 0.95).then_some((util, model)) }) .collect(); - candidates.sort_by(|a, b| a.0.total_cmp(&b.0)); + // The least used first, and a harness whose usage is unknown after every one that is known. + candidates.sort_by(|a, b| a.0.is_none().cmp(&b.0.is_none()).then(a.0.unwrap_or(0.0).total_cmp(&b.0.unwrap_or(0.0)))); candidates.into_iter().next().map(|(_, model)| model) } diff --git a/src/app/mod.rs b/src/app/mod.rs index 1cd9a48..f97779e 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -245,6 +245,7 @@ pub struct AgentForm { /// The ids of the models switched on. pub models: Vec, pub edits: bool, + pub cross_harness: bool, } impl HarnessesForm { @@ -253,7 +254,7 @@ impl HarnessesForm { None => self.claude_subagents, Some(agent) => { let form = self.get(agent); - harness::SubagentAccess { on: form.on, edits: form.edits } + harness::SubagentAccess { on: form.on, edits: form.edits, cross_harness: form.cross_harness } } } } @@ -265,6 +266,7 @@ impl HarnessesForm { let form = self.get_mut(agent); form.on = access.on; form.edits = access.edits; + form.cross_harness = access.cross_harness; } } } @@ -843,6 +845,7 @@ impl Workspace { ws.store.add_project(&path); } ws.discover_executables(cx); + ws.drop_refused_text_generation(cx); ws.refresh_git_async(cx); cx.background_executor().spawn(async { lifecycle::tidy_leftovers() }).detach(); ws.ingest_usage(cx); diff --git a/src/app/modal.rs b/src/app/modal.rs index d6b7c13..9bb80b8 100644 --- a/src/app/modal.rs +++ b/src/app/modal.rs @@ -286,7 +286,7 @@ impl Workspace { let form = subagents.get(agent); let catalog = s.custom_subagents.get(agent).catalog.clone(); let models = if form.on && form.models.is_empty() { catalog.iter().map(|m| m.id.clone()).collect() } else { form.models.clone() }; - harness::subagents::AgentChoice { on: form.on, models, edits: form.edits, catalog } + harness::subagents::AgentChoice { on: form.on, models, edits: form.edits, catalog, cross_harness: form.cross_harness } })); let subagents_changed = s.custom_subagents != custom_subagents || s.claude_picked != subagents.claude_models || s.claude_subagents != subagents.claude_subagents; s.limits = limits; diff --git a/src/app/sessions.rs b/src/app/sessions.rs index daa4f24..923e2e2 100644 --- a/src/app/sessions.rs +++ b/src/app/sessions.rs @@ -142,7 +142,7 @@ impl Workspace { let settings = &self.store.data.settings; let adapter = meta.harness.adapter(); let mut plan = harness::SessionPlan { - off: mcp::tools_off(&settings.m4code_tools_off, &[]), + off: mcp::tools_off(&settings.m4code_tools_off, adapter.mcp_off), ..Default::default() }; if !adapter.fallback_question { @@ -177,7 +177,7 @@ impl Workspace { if let Some(parent) = &meta.parent_session { // A resumed or handed-off subagent asks again, as a new one does. let parent = self.store.session(parent).and_then(SessionRecord::harness); - if let Some(refusal) = harness::capabilities::subagent(parent, meta.harness).refusal() { + if let Some(refusal) = harness::capabilities::subagent(settings, parent, meta.harness).refusal() { self.toast(refusal, cx); return None; } @@ -198,7 +198,7 @@ impl Workspace { return None; } let targets: Vec<_> = settings.enabled_harnesses_list().into_iter() - .filter(|h| settings.subagent_access(*h).on && harness::capabilities::subagent(meta.harness, *h).allowed()) + .filter(|h| settings.subagent_access(*h).on && harness::capabilities::subagent(settings, meta.harness, *h).allowed()) .map(Harness::key).collect(); let project = self.store.project_for_cwd(cwd).and_then(|id| self.store.project(&id)).map(|p| p.path.as_path()); let tools = match mcp::session::SessionTools::new(record_id, cwd, project, &plan.off, &targets) { @@ -373,6 +373,8 @@ impl Workspace { self.store.mark_dirty(); } let view = cx.new(|cx| ThreadView::new(start, window, cx)); + let refusals = self.subagent_refusals(view.read(cx).harness); + view.update(cx, |v, _| v.subagent_refusals = refusals); if switching_harness { view.update(cx, |v, cx| v.hold_workspace_switch(true, cx)); } diff --git a/src/app/settings.rs b/src/app/settings.rs index ee7bde2..248022e 100644 --- a/src/app/settings.rs +++ b/src/app/settings.rs @@ -212,14 +212,25 @@ impl Workspace { } } - /// Keep every open chat thread's aggregated model list up to date. + /// Why a session on `parent` may not start a subagent on each harness, for the pickers that offer one. + pub(crate) fn subagent_refusals(&self, parent: Harness) -> harness::HarnessMap> { + let mut refusals = harness::HarnessMap::default(); + for child in Harness::ALL { + *refusals.get_mut(child) = harness::capabilities::subagent(&self.store.data.settings, parent, child).refusal(); + } + refusals + } + + /// Keep every open chat thread's aggregated model list, and the subagents it may start, up to date. pub(crate) fn push_models_to_threads(&self, cx: &mut Context) { let settings = &self.store.data.settings; let models = settings.aggregated_models(); for live in &self.live { if let Some(thread) = live.view.thread() { + let refusals = self.subagent_refusals(thread.read(cx).harness); thread.update(cx, |t, cx| { t.all_models = models.clone(); + t.subagent_refusals = refusals; t.picked = settings.picked_models(t.harness).to_vec(); cx.notify(); }); diff --git a/src/app/subagents.rs b/src/app/subagents.rs index 2215e5a..f58ecdf 100644 --- a/src/app/subagents.rs +++ b/src/app/subagents.rs @@ -195,7 +195,7 @@ impl Workspace { if !settings.harness_enabled(harness) || !access.on { return Err(format!("{} subagents are disabled in Settings.", harness.name())); } - crate::harness::capabilities::subagent(parent.harness(), harness).refusal().map_or(Ok(()), |refusal| Err(refusal.to_string()))?; + crate::harness::capabilities::subagent(settings, parent.harness(), harness).refusal().map_or(Ok(()), |refusal| Err(refusal.to_string()))?; let parent_read_only = self.live_view(&parent.id).and_then(|view| view.thread()).is_some_and(|view| { view.read(cx).permission() == Some(crate::harness::permission::Permission::ReadOnly) }); @@ -251,6 +251,10 @@ impl Workspace { "wait_subagent" => self.subagent_status(req, cx).map(|status| status.to_string()), "send_subagent_message" => { let record = self.owned_subagent(req)?; + // The settings may have changed since the subagent started. + if let Some(child) = record.harness() { + crate::harness::capabilities::subagent(&self.store.data.settings, parent.harness(), child).refusal().map_or(Ok(()), |refusal| Err(refusal.to_string()))?; + } let prompt = message(req)?; if let Some(view) = self.live_view(&record.id).and_then(|v| v.thread()).cloned() { view.update(cx, |v, cx| v.send(prompt, window, cx)); @@ -296,7 +300,7 @@ impl Workspace { self.toast(format!("{} is disabled in Settings.", model.harness.name()), cx); return; } - if let Some(refusal) = crate::harness::capabilities::subagent(parent.harness(), model.harness).refusal() { + if let Some(refusal) = crate::harness::capabilities::subagent(&self.store.data.settings, parent.harness(), model.harness).refusal() { self.toast(refusal, cx); return; } diff --git a/src/app/titles.rs b/src/app/titles.rs index b998a0e..09519ef 100644 --- a/src/app/titles.rs +++ b/src/app/titles.rs @@ -13,6 +13,17 @@ impl Workspace { chosen.harness.adapter().capabilities.text_generation.allowed().then_some(chosen) } + /// A saved text generation model whose adapter now refuses m4code's prompts goes back to the local summary. The + /// toast shows once, since the change is saved. + pub(super) fn drop_refused_text_generation(&mut self, cx: &mut Context) { + let Some(model) = self.store.data.settings.text_generation_model.as_ref().filter(|model| model.harness.is_registered()) else { return }; + let Some(refusal) = model.harness.adapter().capabilities.text_generation.refusal() else { return }; + let name = model.harness.name(); + self.store.data.settings.text_generation_model = None; + self.store.mark_dirty(); + self.toast(format!("{refusal} Titles, commit messages and summaries now use the local summary instead of {name}."), cx); + } + pub(super) fn text_generator(&self, cx: &App) -> Result, String> { let settings = &self.store.data.settings; let Some(model) = settings.text_generation_model.clone() else { return Ok(None) }; diff --git a/src/harness/antigravity/limits.rs b/src/harness/antigravity/limits.rs index 5f0276e..a69e359 100644 --- a/src/harness/antigravity/limits.rs +++ b/src/harness/antigravity/limits.rs @@ -1,6 +1,6 @@ //! Antigravity's 5-hour and weekly limits, from the CLI's own `agy -p /usage --output-format json`. Since agy 1.1.11 //! the CLI answers `/usage` itself, without a model turn, so a reading costs no tokens; it does ask Google's servers, -//! so the sidebar asks only every few minutes (`REFRESH_EVERY`). The JSON is agy's own and undocumented, so anything +//! and Google's terms allow it on request but not on a timer, so m4code asks only when the user refreshes. The JSON is agy's own and undocumented, so anything //! that doesn't parse leaves the last reading in the sidebar. //! //! Antigravity splits its models into groups ("Gemini Models", "Claude and GPT models"), each with its own limits, so a @@ -18,11 +18,9 @@ use serde_json::Value; use crate::store::{RateLimit, UsageLimits}; use crate::harness::limits::Pool; -/// Cache `agy --version` per executable path so periodic `/usage` polls don't spawn an extra process. +/// Cache `agy --version` per executable path so each `/usage` refresh doesn't spawn an extra process. static VERSION_OK: LazyLock>>> = LazyLock::new(Default::default); -/// How often the sidebar asks again while Antigravity subagents are on. -pub const REFRESH_EVERY: Duration = Duration::from_secs(300); /// `/usage` answers in well under a second; a CLI that hangs (an update, a sign-in prompt) is stopped. const TIMEOUT: Duration = Duration::from_secs(30); /// More than any reading needs, so a runaway child can't fill memory. diff --git a/src/harness/antigravity/mod.rs b/src/harness/antigravity/mod.rs index 374b6b8..cab945d 100644 --- a/src/harness/antigravity/mod.rs +++ b/src/harness/antigravity/mod.rs @@ -1,8 +1,6 @@ //! Google Antigravity, which speaks ACP itself (`agy acp`). It resumes a session without replaying it, as T3 Code //! found, so an old Antigravity conversation opens empty and carries on from where it was. -// Unused while usage polling is paused (see `ANTIGRAVITY` in `harness::subagents`); its tests still run. -#[allow(dead_code)] pub mod limits; pub mod read_only; @@ -17,6 +15,30 @@ use super::{Adapter, Reopen}; #[cfg(feature = "adapter-antigravity")] use self::background::{background_update, task_finished}; +/// Section 6 of Google's Antigravity terms (https://antigravity.google/terms) and Google's answers on the AI Developers +/// Forum: a client may host Antigravity while the user types the prompts and Antigravity keeps its own system +/// prompt, tools and history. So m4code doesn't seed it with another conversation, send it prompts of its own, or +/// move a conversation without the user asking. +#[cfg(feature = "adapter-antigravity")] +const CAPABILITIES: super::capabilities::Capabilities = { + use super::capabilities::{Capability::{Allowed, Refused}, Handoff}; + const REPLAY: &str = "Google's Antigravity terms don't allow seeding a new Antigravity session with an earlier conversation."; + super::capabilities::Capabilities { + rewind: Refused(REPLAY), + fork: Refused(REPLAY), + continue_fresh: Allowed, + compaction_fallback: Refused("Antigravity compacts only with its own /compact, and it doesn't list one in this session."), + text_generation: Refused(TEXT_GENERATION_REFUSED), + handoff_in: Handoff::Never("Google's Antigravity terms don't allow moving another model's conversation onto Antigravity."), + handoff_out: Handoff::UserOnly("Only you can move an Antigravity conversation to another model."), + subagent: Allowed, + spawns_subagents: Allowed, + } +}; + +#[cfg(feature = "adapter-antigravity")] +const TEXT_GENERATION_REFUSED: &str = "Google's Antigravity terms don't allow m4code's own prompts, such as titles, commit messages and summaries."; + #[cfg(feature = "adapter-antigravity")] pub const ADAPTER: Adapter = Adapter { name: "Antigravity", @@ -47,7 +69,8 @@ pub const ADAPTER: Adapter = Adapter { probe_env: super::no_probe_env, config_root: |home| home.join(".gemini").join("config"), project_skills: ".agents/skills", - hidden_commands: &["swarm", "teamwork", "grill-me", "browser", "goal", "schedule", "learn", "boost"], + // `/swarm` and `/teamwork` stay: they are how Google points multi-agent work on personal plans. + hidden_commands: &["grill-me", "browser", "goal", "schedule", "learn", "boost"], worktree: super::WorktreeHooks::DEFAULT, protocol: super::ProtocolHooks { background: Some(super::BackgroundHooks { from_update: background_update, finished: task_finished, live_execute_tools: true }), @@ -60,25 +83,27 @@ pub const ADAPTER: Adapter = Adapter { session_hint: "Run `agy` and sign in, then retry the session.", run_hint: "Antigravity isn't signed in. Run `agy` and sign in, then try again.", }, - // Off pending clarification of Google's terms for usage polling. Back on, it reads: - // usage: Some(super::UsageSource { - // read: |_| limits::read(&super::runner::locate(Agent::Antigravity).ok_or("agy was not found")?, &crate::datadir::data_dir()), - // every: limits::REFRESH_EVERY, - // after_turn: false, - // live: None, - // }), - usage: None, - text_generation_launch: |launch, data| { - let folder = read_only::prepare_text_generation(data).map_err(|e| format!("Could not disable Antigravity tools: {e}"))?; - launch.args.extend(["--gemini-dir".into(), folder.to_string_lossy().into_owned()]); - Ok(serde_json::Value::Null) - }, + // Google's terms allow running `/usage` when the user asks, not on a timer, so m4code reads it only on a refresh. + usage: Some(super::UsageSource { + read: |_| limits::read(&super::runner::locate(Agent::Antigravity).ok_or("agy was not found")?, &crate::datadir::data_dir()), + every: None, + after_turn: false, + live: None, + }), + text_generation_launch: |_, _| Err(TEXT_GENERATION_REFUSED.into()), probe_session_meta: None, copies_skills: true, - capabilities: super::capabilities::Capabilities::ALL, + capabilities: CAPABILITIES, + // Google points multi-agent work on personal plans to `/swarm` and `/teamwork`, so the instructions don't steer + // Antigravity away from them. Starting a session with a prompt it wrote, or reading another session into its + // context, would make it the coordinating agent Google's terms rule out. + mcp_off: &[crate::mcp::PREFER_OWN_TOOLS, "start_code_session", "read_code_session"], reports: None, native_sessions: None, - tidy: || {}, + // Text generation ran agy from this folder before Google's terms ruled it out. + tidy: || { + let _ = std::fs::remove_dir_all(crate::datadir::data_dir().join("antigravity-text-generation")); + }, }; #[cfg(feature = "adapter-antigravity")] @@ -147,7 +172,8 @@ pub const PROVIDER: Provider = Provider { missing: "agy was not found. Antigravity subagents need the Antigravity CLI installed.", // Google's FAQ names Claude Code among the third-party software barred from Antigravity logins, under Section 6 of // the Antigravity Additional Terms (https://antigravity.google/docs/faq, https://antigravity.google/terms). - warning: Some("Google's Antigravity terms forbid using another company's agent, such as Claude Code, with a personal Google sign-in. That covers the Free, AI Plus, Pro and Ultra plans. Google can suspend or terminate the Antigravity and Gemini CLI accounts of anyone who does. Switch this on at your own risk."), + warning: Some("Google's Antigravity terms forbid using another company's agent, such as Claude Code, with a personal Google sign-in. That covers the Free, AI Plus, Pro and Ultra plans. Google can suspend or terminate the Antigravity and Gemini CLI accounts of anyone who does. Switch these on at your own risk."), + cross_harness_default: false, task_args: super::runner::antigravity_args, environment: super::runner::no_env, config_options: super::runner::antigravity_options, diff --git a/src/harness/antigravity/read_only.rs b/src/harness/antigravity/read_only.rs index 84f27da..367cb42 100644 --- a/src/harness/antigravity/read_only.rs +++ b/src/harness/antigravity/read_only.rs @@ -48,16 +48,6 @@ pub fn prepare(data_dir: &Path, m4code: &Path) -> std::io::Result { prepare_with_hook(data_dir.join("antigravity-read-only"), &hook_script(m4code)) } -pub fn prepare_text_generation(data_dir: &Path) -> std::io::Result { - let denied = json!({"decision": "deny", "reason": "Tools are disabled for text generation."}).to_string(); - let script = if cfg!(windows) { - format!("@echo off\r\necho {denied}\r\n") - } else { - format!("#!/bin/sh\nprintf '%s\\n' '{denied}'\n") - }; - prepare_with_hook(data_dir.join("antigravity-text-generation"), &script) -} - fn prepare_with_hook(gemini: PathBuf, body: &str) -> std::io::Result { let config = gemini.join("config"); std::fs::create_dir_all(&config)?; diff --git a/src/harness/capabilities.rs b/src/harness/capabilities.rs index 69e5edc..6861355 100644 --- a/src/harness/capabilities.rs +++ b/src/harness/capabilities.rs @@ -28,6 +28,8 @@ impl Capability { pub enum Handoff { /// The user, the agent (`set_model`) and auto-handoff on a usage limit. Any, + /// Only a switch the user starts; the reason refuses the others. + UserOnly(&'static str), Never(&'static str), } @@ -40,11 +42,10 @@ pub enum Initiator { } impl Handoff { - /// `by` is part of the question so a rule that tells the user from the agent needs no change at the call sites. - pub fn allows(self, _by: Initiator) -> Capability { - match self { - Self::Any => Capability::Allowed, - Self::Never(reason) => Capability::Refused(reason), + pub fn allows(self, by: Initiator) -> Capability { + match (self, by) { + (Self::Any, _) | (Self::UserOnly(_), Initiator::User) => Capability::Allowed, + (Self::UserOnly(reason) | Self::Never(reason), _) => Capability::Refused(reason), } } } @@ -62,7 +63,8 @@ pub struct Capabilities { /// m4code's own compaction for a session whose agent doesn't list its compact command: a summary, then a new /// session seeded with it. pub compaction_fallback: Capability, - /// Answering m4code's own prompts: session titles, commit messages and summaries. + /// Answering m4code's own prompts: session titles, commit messages, summaries, and the note that a usage limit is + /// near. pub text_generation: Capability, /// Moving a conversation from another harness onto this one. pub handoff_in: Handoff, @@ -113,17 +115,55 @@ pub fn handoff(from: super::Harness, to: super::Harness, by: Initiator) -> Capab if out.allowed() { to.adapter().capabilities.handoff_in.allows(by) } else { out } } -/// Whether a session on `parent` may start a subagent on `child`. A parent that isn't an agent session asks only the -/// child. -pub fn subagent(parent: impl Into>, child: super::Harness) -> Capability { - let out = parent.into().map_or(Capability::Allowed, |parent| parent.adapter().capabilities.spawns_subagents); - if out.allowed() { child.adapter().capabilities.subagent } else { out } +/// Whether a session on `parent` may start a subagent on `child`: both adapters allow it, and a subagent on another +/// harness needs "Allow cross-harness subagents" on for both. A parent that isn't an agent session asks only the +/// child's adapter. +pub fn subagent(settings: &crate::store::Settings, parent: impl Into>, child: super::Harness) -> Capability { + let parent = parent.into(); + let out = parent.map_or(Capability::Allowed, |parent| parent.adapter().capabilities.spawns_subagents); + let adapters = if out.allowed() { child.adapter().capabilities.subagent } else { out }; + match parent { + Some(parent) if adapters.allowed() && parent != child => crossing(settings, parent, child), + _ => adapters, + } +} + +/// Whether a session on `from` may reach `to`, another harness, through m4code's tools: a subagent, or a session +/// it starts. Both need "Allow cross-harness subagents" on. +pub fn crossing(settings: &crate::store::Settings, from: super::Harness, to: super::Harness) -> Capability { + if from == to { + Capability::Allowed + } else if !settings.subagent_access(from).cross_harness { + Capability::Refused("Cross-harness subagents are off for this session's harness in Settings → Harnesses.") + } else if !settings.subagent_access(to).cross_harness { + Capability::Refused("Cross-harness subagents are off for this harness in Settings → Harnesses.") + } else { + Capability::Allowed + } } #[cfg(test)] mod tests { use super::*; + #[test] + fn a_user_only_handoff_refuses_only_automatic_switches() { + assert!(Handoff::UserOnly("Ask.").allows(Initiator::User).allowed()); + assert_eq!(Handoff::UserOnly("Ask.").allows(Initiator::Automatic).refusal(), Some("Ask.")); + } + + #[test] + fn a_cross_harness_subagent_needs_the_toggle_on_both_sides() { + use super::super::Harness::{Claude, Codex}; + let mut settings = crate::store::Settings::default(); + assert!(subagent(&settings, Claude, Codex).allowed()); + settings.custom_subagents.get_mut(super::super::subagents::Agent::Codex).cross_harness = false; + assert!(subagent(&settings, Claude, Codex).refusal().is_some(), "the child's toggle is off"); + assert!(subagent(&settings, Codex, Claude).refusal().is_some(), "the parent's toggle is off"); + assert!(subagent(&settings, Codex, Codex).allowed(), "staying on one harness doesn't cross"); + assert!(subagent(&settings, None, Codex).allowed(), "the user starting it isn't a harness crossing"); + } + #[test] fn a_refused_handoff_gives_its_reason_to_whoever_asks() { for by in [Initiator::User, Initiator::Automatic] { @@ -132,6 +172,23 @@ mod tests { } } + #[cfg(feature = "adapter-antigravity")] + #[test] + fn antigravity_takes_no_conversation_and_lets_only_the_user_move_one_off_it() { + use super::super::Harness::{Antigravity, Codex}; + for by in [Initiator::User, Initiator::Automatic] { + assert!(handoff(Codex, Antigravity, by).refusal().is_some()); + } + assert!(handoff(Antigravity, Codex, Initiator::User).allowed()); + assert!(handoff(Antigravity, Codex, Initiator::Automatic).refusal().is_some()); + let caps = Antigravity.adapter().capabilities; + assert!(caps.rewind.refusal().is_some() && caps.fork.refusal().is_some() && caps.text_generation.refusal().is_some()); + assert!(caps.compaction_fallback.refusal().is_some()); + let settings = crate::store::Settings::default(); + assert!(subagent(&settings, Codex, Antigravity).refusal().is_some(), "cross-harness starts off for Antigravity"); + assert!(subagent(&settings, Antigravity, Codex).refusal().is_some()); + } + #[test] fn staying_on_one_harness_is_never_a_handoff() { for harness in super::super::Harness::ALL { diff --git a/src/harness/claude/mod.rs b/src/harness/claude/mod.rs index 464c424..e0562f1 100644 --- a/src/harness/claude/mod.rs +++ b/src/harness/claude/mod.rs @@ -87,7 +87,7 @@ pub const ADAPTER: Adapter = Adapter { let exe = exe.ok_or("Could not find the `claude` CLI on PATH.")?; Ok(vec![super::limits::Pool { name: "Claude Code".into(), usage: limits::read(exe)? }]) }, - every: limits::REFRESH_EVERY, + every: Some(limits::REFRESH_EVERY), after_turn: true, live: None, }), @@ -101,6 +101,7 @@ pub const ADAPTER: Adapter = Adapter { probe_session_meta: Some(|| serde_json::json!({ "claudeCode": { "options": { "persistSession": false } } })), copies_skills: false, capabilities: super::capabilities::Capabilities::ALL, + mcp_off: &[], reports: Some(|| usage::read_snapshots(&usage::snapshot_dir())), native_sessions: Some(super::NativeSessions { statuses: native_statuses, @@ -236,7 +237,7 @@ pub fn prepare_session( env.push((usage::CTL_ENV.into(), usage::ctl_file(record_id).to_string_lossy().into_owned())); // The mod registers the agent types and answers their turns, so they go only where it loads. let targets: Vec<_> = settings.enabled_harnesses_list().into_iter() - .filter(|h| super::capabilities::subagent(super::Harness::Claude, *h).allowed()).collect(); + .filter(|h| super::capabilities::subagent(settings, super::Harness::Claude, *h).allowed()).collect(); if let Some(subagents) = settings.custom_subagents.env_for_edits(&targets, allow_subagent_edits) && let Ok(exe) = crate::platform::own_exe() { diff --git a/src/harness/codex/mod.rs b/src/harness/codex/mod.rs index f00fb48..215414a 100644 --- a/src/harness/codex/mod.rs +++ b/src/harness/codex/mod.rs @@ -187,7 +187,7 @@ pub const ADAPTER: Adapter = Adapter { }, usage: Some(super::UsageSource { read: |_| Ok(vec![Pool { name: "Codex".into(), usage: limits::probe()? }]), - every: limits::REFRESH_EVERY, + every: Some(limits::REFRESH_EVERY), after_turn: true, // Rollout logs are read again only after Codex writes to them: no network and no subprocess. live: Some(super::LiveUsage { @@ -199,6 +199,7 @@ pub const ADAPTER: Adapter = Adapter { probe_session_meta: None, copies_skills: false, capabilities: super::capabilities::Capabilities::ALL, + mcp_off: &[], reports: None, native_sessions: None, tidy: || {}, @@ -376,6 +377,7 @@ pub const PROVIDER: Provider = Provider { server: "codex-acp", missing: "npx was not found on PATH. Codex subagents need Node.js.", warning: None, + cross_harness_default: true, task_args: super::runner::no_args, environment: super::runner::codex_env, config_options: super::runner::no_options, diff --git a/src/harness/mod.rs b/src/harness/mod.rs index 2f25e03..ee6fbdc 100644 --- a/src/harness/mod.rs +++ b/src/harness/mod.rs @@ -41,11 +41,14 @@ pub enum Harness { pub struct SubagentAccess { pub on: bool, pub edits: bool, + /// "Allow cross-harness subagents": other harnesses may run this one as a subagent, and its sessions may start + /// other harnesses (`capabilities::crossing`). + pub cross_harness: bool, } impl Default for SubagentAccess { fn default() -> Self { - Self { on: true, edits: true } + Self { on: true, edits: true, cross_harness: true } } } @@ -117,6 +120,8 @@ pub struct Adapter { pub copies_skills: bool, /// The actions the core may take with this agent (`capabilities.rs`). pub capabilities: capabilities::Capabilities, + /// Parts of m4code's MCP server its sessions and subagents never get, such as `mcp::PREFER_OWN_TOOLS`. + pub mcp_off: &'static [&'static str], /// Reads the figures its sessions report outside ACP, such as the files Claude Code's mod writes. pub reports: Option Vec>, /// The agent's own record of its running sessions, for an agent that keeps one. @@ -170,7 +175,9 @@ pub struct SessionReport { pub struct UsageSource { /// Asks the agent's CLI, given the executable set in Settings. pub read: fn(Option<&Path>) -> Result, String>, - pub every: std::time::Duration, + /// How often m4code asks on its own. `None` asks only when the user refreshes, for an agent whose terms allow a + /// reading on request but not on a timer. + pub every: Option, /// Whether the end of a turn asks again. pub after_turn: bool, pub live: Option, @@ -399,6 +406,7 @@ static UNAVAILABLE_ADAPTER: Adapter = Adapter { probe_session_meta: None, copies_skills: false, capabilities: capabilities::Capabilities::NONE, + mcp_off: &[], reports: None, native_sessions: None, tidy: || {}, diff --git a/src/harness/opencode.rs b/src/harness/opencode.rs index b9b6361..32acb08 100644 --- a/src/harness/opencode.rs +++ b/src/harness/opencode.rs @@ -81,6 +81,7 @@ pub const ADAPTER: Adapter = Adapter { probe_session_meta: None, copies_skills: false, capabilities: super::capabilities::Capabilities::ALL, + mcp_off: &[], reports: None, native_sessions: None, tidy: || {}, @@ -110,6 +111,7 @@ pub const PROVIDER: Provider = Provider { server: "opencode", missing: "opencode was not found on PATH. OpenCode subagents need OpenCode installed.", warning: None, + cross_harness_default: true, task_args: super::runner::no_args, environment: super::runner::opencode_env, config_options: super::runner::no_options, diff --git a/src/harness/runner.rs b/src/harness/runner.rs index ef730f3..733692d 100644 --- a/src/harness/runner.rs +++ b/src/harness/runner.rs @@ -179,17 +179,20 @@ fn run_task(request: &Request, emit: &mut impl FnMut(Event)) -> Result = ["github", "sessions", "model", "ask_user", "visual"].into_iter().chain(adapter.mcp_off.iter().copied()).collect(); + let mut tools = crate::mcp::session::SessionTools::new("", &request.cwd, None, &off, &[])?; + tools.load_workspace(); (adapter.configure_mcp)(&tools, &mut plan)?; let env = plan.env.iter().map(|(key, value)| (key.as_str(), value.clone())).collect::>(); let connection = Connection::start(request.agent, &request.cwd, &args, &env)?; diff --git a/src/harness/subagents.rs b/src/harness/subagents.rs index 8cf6007..1bb6052 100644 --- a/src/harness/subagents.rs +++ b/src/harness/subagents.rs @@ -58,6 +58,9 @@ pub struct Provider { pub missing: &'static str, /// A risk the settings page shows before the agent is switched on, such as a sign-in its maker's terms forbid here. pub warning: Option<&'static str>, + /// Where "Allow cross-harness subagents" starts, before the user changes it. Kept here rather than in the + /// adapter's capabilities so a build without the adapter still saves the right default. + pub cross_harness_default: bool, /// Arguments after `args` for one task's server, made ready here. pub task_args: fn(&super::runner::Request) -> Result, String>, /// The environment the server starts with, for agents that take the model, effort and edits that way. @@ -159,6 +162,8 @@ pub struct AgentChoice { pub edits: bool, /// The models the agent offered when the page last asked, shown while it asks again. pub catalog: Vec, + /// "Allow cross-harness subagents" (`SubagentAccess::cross_harness`). + pub cross_harness: bool, } /// Keeps the flat provider keys used by existing state files. @@ -169,7 +174,8 @@ impl Default for CustomSubagents { fn default() -> Self { Self(AgentMap::from_fn(|agent| { let enabled = agent != Agent::Antigravity; - AgentChoice { on: enabled, edits: enabled, ..Default::default() } + let cross_harness = agent.provider().cross_harness_default; + AgentChoice { on: enabled, edits: enabled, cross_harness, ..Default::default() } })) } } @@ -184,6 +190,7 @@ impl Serialize for CustomSubagents { stored.insert(format!("{key}_models"), json!(choice.models)); stored.insert(format!("{key}_edits"), json!(choice.edits)); stored.insert(format!("{key}_catalog"), json!(choice.catalog)); + stored.insert(format!("{key}_cross_harness"), json!(choice.cross_harness)); } stored.serialize(serializer) } @@ -204,6 +211,7 @@ impl<'de> Deserialize<'de> for CustomSubagents { models: field::<_, D::Error>(&mut stored, &format!("{key}_models"), vec![])?, edits: field::<_, D::Error>(&mut stored, &format!("{key}_edits"), defaults.edits)?, catalog: field::<_, D::Error>(&mut stored, &format!("{key}_catalog"), vec![])?, + cross_harness: field::<_, D::Error>(&mut stored, &format!("{key}_cross_harness"), defaults.cross_harness)?, }; } Ok(result) @@ -365,7 +373,7 @@ mod tests { } fn on(models: &[&str], edits: bool) -> AgentChoice { - AgentChoice { on: true, models: ids(models), edits, catalog: vec![] } + AgentChoice { on: true, models: ids(models), edits, catalog: vec![], cross_harness: true } } #[test] @@ -471,7 +479,7 @@ mod tests { let loaded: CustomSubagents = serde_json::from_str(saved).unwrap(); assert_eq!( loaded, - choices(AgentChoice { on: true, models: ids(&["gpt-6.1-sol"]), edits: true, catalog: vec![AgentModel { id: "gpt-6.1-sol".into(), name: "6.1 Sol".into() }] }, CustomSubagents::default().get(Agent::OpenCode).clone()) + choices(AgentChoice { on: true, models: ids(&["gpt-6.1-sol"]), edits: true, catalog: vec![AgentModel { id: "gpt-6.1-sol".into(), name: "6.1 Sol".into() }], cross_harness: true }, CustomSubagents::default().get(Agent::OpenCode).clone()) ); let again: CustomSubagents = serde_json::from_str(&serde_json::to_string(&loaded).unwrap()).unwrap(); assert_eq!(again, loaded); diff --git a/src/mcp/mod.rs b/src/mcp/mod.rs index 61636af..7112d50 100644 --- a/src/mcp/mod.rs +++ b/src/mcp/mod.rs @@ -92,8 +92,9 @@ fn feature_of(tool: &str) -> Option<&'static str> { } } +/// Off as a whole feature, or by its own name for an adapter that turns off a single tool (`Adapter::mcp_off`). fn is_off(off: &[&str], tool: &str) -> bool { - feature_of(tool).is_some_and(|f| off.contains(&f)) + off.contains(&tool) || feature_of(tool).is_some_and(|f| off.contains(&f)) } /// Tools the model uses to tell m4code something about itself; none of them reads or starts another session. @@ -174,6 +175,17 @@ const INTRO: &str = "You are running inside m4code, a desktop app that hosts thi Treat m4code as your environment: link workspace files in Markdown as `[name](relative/path#L10-L20)` so the user can jump straight to them in the editor, \ prefer m4code's MCP tools over any provider-native swarm, workflow, or question tools, and never tell the user to run harness-specific CLI flags or slash commands such as `/swarm`, `/teamwork`, `/resume`, or `/login`."; +/// The opening for an agent that keeps its own multi-agent commands (`PREFER_OWN_TOOLS` off): the same, without +/// steering it away from them. +const INTRO_KEEPING_NATIVE: &str = "You are running inside m4code, a desktop app that hosts this coding-agent session. \ +Treat m4code as your environment: link workspace files in Markdown as `[name](relative/path#L10-L20)` so the user can jump straight to them in the editor, \ +and never tell the user to run harness-specific CLI flags or slash commands such as `/resume` or `/login`."; + +/// An entry in a session's off list, not a tool: the instructions stop telling the agent to prefer m4code's tools over +/// its own swarm and workflow commands. An adapter turns it off for an agent whose terms point multi-agent work to +/// those commands. +pub const PREFER_OWN_TOOLS: &str = "prefer_own_tools"; + /// Confirmation instructions shared by every provider before switching models. fn model_instructions() -> String { String::from( @@ -187,7 +199,7 @@ switching to another one hands this conversation over. After set_model, end your /// The `initialize` reply's instructions: the opening, then the text of each feature that is not off. fn instructions(off: &[&str]) -> String { let on = |name: &str| !off.contains(&name); - let mut text = INTRO.to_string(); + let mut text = if on(PREFER_OWN_TOOLS) { INTRO } else { INTRO_KEEPING_NATIVE }.to_string(); if on("visual") { text += VISUAL_INSTRUCTIONS; } @@ -203,6 +215,10 @@ fn instructions(off: &[&str]) -> String { if on("sessions") { text += BRIDGE_INSTRUCTIONS; text += SUBAGENT_INSTRUCTIONS; + let single: Vec<&str> = BRIDGE_TOOLS.iter().copied().filter(|tool| off.contains(tool)).collect(); + if !single.is_empty() { + text += &format!(" This session doesn't have {}.", single.join(" or ")); + } } if on("ask_user") { text += " To ask the user a multiple-choice question in m4code's UI, call ask_user with the question and options instead of any built-in question tool."; @@ -1010,6 +1026,22 @@ mod tests { assert_eq!(described(&[]), described(&["ask_user_question"])); } + #[test] + fn an_agent_keeping_its_own_swarm_commands_isnt_steered_away_from_them() { + assert!(instructions(&[]).contains("/swarm")); + let keeping = instructions(&[PREFER_OWN_TOOLS]); + assert!(!keeping.contains("swarm") && !keeping.contains("/teamwork"), "{keeping}"); + assert!(keeping.contains("/login"), "the other advice stays"); + } + + #[test] + fn a_single_tool_turned_off_is_neither_offered_nor_promised() { + let off = ["start_code_session", "read_code_session"]; + assert!(is_off(&off, "start_code_session") && is_off(&off, "read_code_session")); + assert!(!is_off(&off, "list_code_sessions"), "the rest of the feature stays"); + assert!(instructions(&off).contains("This session doesn't have read_code_session or start_code_session.")); + } + #[test] fn every_shared_subagent_tool_is_discoverable_in_session_instructions() { let (_, enabled) = offer(&[]); diff --git a/src/panels/settings_pages.rs b/src/panels/settings_pages.rs index 3c8edd9..a2e5b29 100644 --- a/src/panels/settings_pages.rs +++ b/src/panels/settings_pages.rs @@ -109,6 +109,13 @@ fn flip_harness_enabled(ws: &mut Workspace, harness: Harness, cx: &mut Context) { let Some(Modal::Settings { subagents, .. }) = ws.modal.as_mut() else { return }; let mut access = subagents.access(harness); @@ -285,6 +292,14 @@ impl Workspace { move |ws, _, cx| flip_subagent(ws, harness, cx), cx, ).disabled(refusal.is_some())); + controls = controls.child(switch_row( + SharedString::from(format!("agent-dialog-{key}-cross-harness")), + "Allow cross-harness subagents", + Some("Run as a subagent of other harnesses, and start subagents on them".into()), + access.cross_harness, + move |ws, _, _| flip_cross_harness(ws, harness), + cx, + )); if let Some(warning) = harness.agent().and_then(|agent| agent.provider().warning) { controls = controls.child(warn(warning)); } @@ -566,7 +581,7 @@ mod tests { fn harness_subtitles_use_the_same_subagent_status_for_every_provider() { let form = crate::app::HarnessesForm { enabled: Harness::ALL.to_vec(), - agents: crate::harness::subagents::AgentMap::from_fn(|_| crate::app::AgentForm { on: true, edits: true, models: vec![] }), + agents: crate::harness::subagents::AgentMap::from_fn(|_| crate::app::AgentForm { on: true, edits: true, models: vec![], cross_harness: true }), claude_models: vec![], claude_subagents: Default::default(), picking: None, }; for harness in Harness::registered() { diff --git a/src/panels/sidebar.rs b/src/panels/sidebar.rs index ebbf255..8247abe 100644 --- a/src/panels/sidebar.rs +++ b/src/panels/sidebar.rs @@ -1006,7 +1006,8 @@ impl Workspace { )); } } - None if state.loading || state.error.is_some() => { + // An adapter read only on request shows its row empty until the user refreshes. + None if state.loading || state.error.is_some() || harness.adapter().usage.as_ref().is_some_and(|usage| usage.every.is_none()) => { if !rows.is_empty() { rows.push(divider()); } diff --git a/src/screenshots.rs b/src/screenshots.rs index 55186b0..9c3bf5c 100644 --- a/src/screenshots.rs +++ b/src/screenshots.rs @@ -25,9 +25,9 @@ fn capture() -> Result<()> { let scenario = std::env::var("M4CODE_SCREENSHOT_SCENARIO").unwrap_or_else(|_| "home".into()); let session_scenario = matches!(scenario.as_str(), "session" | "session-short" | "session-done" | "session-auth" | "session-no-compact" | "session-scrolled" | "session-quotes" | "session-quotes-menu" | "session-events" | "toast" | "review" | "review-hover"); let shortcut = match scenario.as_str() { - "home" | "dashboards-disabled" | "picker" | "context-menu" | "github" | "github-wide" | "github-issues" | "editor" | "session" | "session-short" | "session-done" | "session-auth" | "session-no-compact" | "session-scrolled" | "session-quotes" | "session-quotes-menu" | "session-events" | "toast" | "harnesses" | "review" | "review-hover" => None, + "home" | "dashboards-disabled" | "picker" | "context-menu" | "github" | "github-wide" | "github-issues" | "editor" | "session" | "session-short" | "session-done" | "session-auth" | "session-no-compact" | "session-scrolled" | "session-quotes" | "session-quotes-menu" | "session-events" | "toast" | "harnesses" | "harness-dialog" | "review" | "review-hover" => None, "settings" => Some(Keystroke::parse("secondary-,").expect("Settings shortcut")), - _ => anyhow::bail!("unknown screenshot scenario {scenario:?}; use home, dashboards-disabled, settings, picker, context-menu, github, github-wide, editor, session, session-short, session-done, session-no-compact, session-scrolled, toast, harnesses, review or review-hover"), + _ => anyhow::bail!("unknown screenshot scenario {scenario:?}; use home, dashboards-disabled, settings, picker, context-menu, github, github-wide, editor, session, session-short, session-done, session-no-compact, session-scrolled, toast, harnesses, harness-dialog, review or review-hover"), }; let fixture = tempfile::tempdir()?; @@ -186,10 +186,14 @@ fn capture() -> Result<()> { }))?; cx.run_until_parked(); } - if scenario == "harnesses" { + if scenario == "harnesses" || scenario == "harness-dialog" { cx.update_window(window, |_, window, app| workspace.update(app, |ws, cx| { ws.act(crate::app::Act::OpenSettings, window, cx); ws.settings_page = crate::app::SettingsPage::Harnesses; + // Antigravity's popup: its subagent switches, which start off, and the terms warning. + if scenario == "harness-dialog" { + ws.open_harness_dialog(crate::harness::Harness::Antigravity, window, cx); + } }))?; cx.run_until_parked(); } diff --git a/src/store.rs b/src/store.rs index 335a3e6..8ec3630 100644 --- a/src/store.rs +++ b/src/store.rs @@ -160,6 +160,12 @@ impl Store { } /// Load tolerant of missing/corrupt files: a corrupt file is moved aside, never overwritten silently. + /// The settings in the state file at `path`, for another process that only reads them: nothing is moved or + /// migrated, and an unreadable file gives the defaults. + pub fn read_settings(path: &Path) -> Settings { + fs::read_to_string(path).ok().and_then(|text| serde_json::from_str::(&text).ok()).map(|data| data.settings).unwrap_or_default() + } + pub fn load(path: PathBuf) -> Self { let mut data = Data { version: 1, layout: Layout { sidebar_visible: true, ..Default::default() }, ..Default::default() }; if let Ok(text) = fs::read_to_string(&path) { diff --git a/src/store/settings.rs b/src/store/settings.rs index cca659a..502076d 100644 --- a/src/store/settings.rs +++ b/src/store/settings.rs @@ -223,7 +223,7 @@ impl Settings { None => self.claude_subagents, Some(agent) => { let choice = self.custom_subagents.get(agent); - crate::harness::SubagentAccess { on: choice.on, edits: choice.edits } + crate::harness::SubagentAccess { on: choice.on, edits: choice.edits, cross_harness: choice.cross_harness } } } } diff --git a/src/thread/mod.rs b/src/thread/mod.rs index e25110c..8d53843 100644 --- a/src/thread/mod.rs +++ b/src/thread/mod.rs @@ -374,6 +374,9 @@ pub struct ThreadView { pub all_models: Vec, /// The models of this session's harness ticked in Settings → Harnesses; they narrow the live model list too. pub picked: Vec, + /// Why this session may not start a subagent on each harness (`capabilities::subagent`), kept current by the + /// workspace. + pub subagent_refusals: crate::harness::HarnessMap>, /// The branch chip, when the session's folder is in a git repository. pub git: Option, /// Running child subagents / workspace background tasks attached to this session. @@ -663,6 +666,7 @@ impl ThreadView { harness: start.harness, all_models: start.all_models.clone(), picked: start.picked.clone(), + subagent_refusals: Default::default(), git: None, background: vec![], provider_shells: vec![], @@ -3613,7 +3617,9 @@ impl ThreadView { let cumulative_tokens = self.thread.cache_usage.input_tokens .saturating_add(self.thread.cache_usage.output_tokens) .max(self.thread.context.map(|(used, _)| used).unwrap_or(0)); + // The nudge is a prompt of m4code's own, so it goes only to an agent that answers those. if notify_on_limit + && self.capabilities().text_generation.allowed() && self.is_working() && let Some(nudge) = self.runway.observe(usage, cumulative_tokens, auto_handoff, now) { diff --git a/src/thread/review.rs b/src/thread/review.rs index 034c9e4..7fd2731 100644 --- a/src/thread/review.rs +++ b/src/thread/review.rs @@ -676,6 +676,7 @@ impl ThreadView { let models = review_model_choices(&self.unified_models(), self.harness); let has_other_harness = models.iter().any(|m| m.harness != self.harness); let current_harness = self.harness; + let refusals = self.subagent_refusals.clone(); Some(picker::model_dropdown_overlay( ("review-model-picker", "REVIEW WITH"), "review-model-list", @@ -686,7 +687,7 @@ impl ThreadView { &self.picker_nav, models, move |h| (h == current_harness && has_other_harness).then_some("current"), - move |h| crate::harness::capabilities::subagent(current_harness, h).refusal(), + move |h| *refusals.get(h), |v, choice, _, cx| v.start_cross_model_review(choice, cx), |v, _, cx| v.close_review_model_picker(cx), window,