From 2361e4fa514ec43fa3a451922b96e3bbb154f2c8 Mon Sep 17 00:00:00 2001 From: wsp Date: Tue, 17 Nov 2026 14:58:08 +0800 Subject: [PATCH 1/5] refactor(agent): group collaboration tools under agent_collaboration --- docs/architecture/deep-review.md | 4 +- .../architecture/model-request-cache-reuse.md | 2 +- scripts/check-core-boundaries.test.mjs | 2 +- .../rules/source/forbidden-rules.mjs | 2 +- .../rules/source/required-rules.mjs | 12 +- scripts/core-boundaries/self-test.mjs | 14 +- src/crates/assembly/core/AGENTS-CN.md | 11 ++ src/crates/assembly/core/AGENTS.md | 8 +- .../agent_control.rs | 0 .../agent_control_tool.rs | 0 .../agent_list_tool.rs | 0 .../agent_wait_tool.rs | 0 .../background.rs | 0 .../deep_review.rs | 0 .../execution.rs | 0 .../{task => agent_collaboration}/input.rs | 0 .../launch_review_agent.rs | 0 .../agent_collaboration/legacy_task.rs | 154 +++++++++++++++++ .../{task => agent_collaboration}/mod.rs | 161 ++---------------- .../{task => agent_collaboration}/schema.rs | 0 .../{task => agent_collaboration}/tests.rs | 0 .../validation.rs | 0 .../src/agentic/tools/implementations/mod.rs | 15 +- .../agentic/tools/pipeline/tool_pipeline.rs | 2 +- 24 files changed, 205 insertions(+), 182 deletions(-) rename src/crates/assembly/core/src/agentic/tools/implementations/{task => agent_collaboration}/agent_control.rs (100%) rename src/crates/assembly/core/src/agentic/tools/implementations/{ => agent_collaboration}/agent_control_tool.rs (100%) rename src/crates/assembly/core/src/agentic/tools/implementations/{ => agent_collaboration}/agent_list_tool.rs (100%) rename src/crates/assembly/core/src/agentic/tools/implementations/{ => agent_collaboration}/agent_wait_tool.rs (100%) rename src/crates/assembly/core/src/agentic/tools/implementations/{task => agent_collaboration}/background.rs (100%) rename src/crates/assembly/core/src/agentic/tools/implementations/{task => agent_collaboration}/deep_review.rs (100%) rename src/crates/assembly/core/src/agentic/tools/implementations/{task => agent_collaboration}/execution.rs (100%) rename src/crates/assembly/core/src/agentic/tools/implementations/{task => agent_collaboration}/input.rs (100%) rename src/crates/assembly/core/src/agentic/tools/implementations/{task => agent_collaboration}/launch_review_agent.rs (100%) create mode 100644 src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/legacy_task.rs rename src/crates/assembly/core/src/agentic/tools/implementations/{task => agent_collaboration}/mod.rs (70%) rename src/crates/assembly/core/src/agentic/tools/implementations/{task => agent_collaboration}/schema.rs (100%) rename src/crates/assembly/core/src/agentic/tools/implementations/{task => agent_collaboration}/tests.rs (100%) rename src/crates/assembly/core/src/agentic/tools/implementations/{task => agent_collaboration}/validation.rs (100%) diff --git a/docs/architecture/deep-review.md b/docs/architecture/deep-review.md index 7b88737cdf..0ee225a90f 100644 --- a/docs/architecture/deep-review.md +++ b/docs/architecture/deep-review.md @@ -345,8 +345,8 @@ Packet support is not a general fan-out policy. New packets are admitted only wh The generic `Task` tool is adapted for DeepReview across: -- `src/crates/assembly/core/src/agentic/tools/implementations/task/mod.rs` -- `src/crates/assembly/core/src/agentic/tools/implementations/task/deep_review.rs` +- `src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/mod.rs` +- `src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/deep_review.rs` - `src/crates/assembly/core/src/agentic/deep_review/task_adapter.rs` - `src/crates/execution/agent-runtime/src/deep_review/task_execution.rs` - `src/crates/execution/agent-runtime/src/deep_review/queue.rs` diff --git a/docs/architecture/model-request-cache-reuse.md b/docs/architecture/model-request-cache-reuse.md index 38f5430ac2..bda773658a 100644 --- a/docs/architecture/model-request-cache-reuse.md +++ b/docs/architecture/model-request-cache-reuse.md @@ -146,7 +146,7 @@ Relevant code: - snapshot model: `src/crates/assembly/core/src/agentic/fork_agent/mod.rs` - request validation and tool contract: - `src/crates/assembly/core/src/agentic/tools/implementations/task/mod.rs` + `src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/mod.rs` - execution and prompt-cache cloning: `src/crates/assembly/core/src/agentic/coordination/coordinator.rs` diff --git a/scripts/check-core-boundaries.test.mjs b/scripts/check-core-boundaries.test.mjs index 42f8265084..5ec7fd6537 100644 --- a/scripts/check-core-boundaries.test.mjs +++ b/scripts/check-core-boundaries.test.mjs @@ -4024,7 +4024,7 @@ test('split core boundary check keeps self-test execution behavior', () => { test('Task execution boundary requires policy-aware child delegation', () => { const executionRule = requiredContentRules.find( (rule) => rule.path - === 'src/crates/assembly/core/src/agentic/tools/implementations/task/execution.rs' + === 'src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/execution.rs' && rule.patterns.some((pattern) => pattern.message.includes('background launches')), ); assert.ok(executionRule, 'Task execution must have a required-content rule'); diff --git a/scripts/core-boundaries/rules/source/forbidden-rules.mjs b/scripts/core-boundaries/rules/source/forbidden-rules.mjs index f81f7b9cef..ffe3a968e2 100644 --- a/scripts/core-boundaries/rules/source/forbidden-rules.mjs +++ b/scripts/core-boundaries/rules/source/forbidden-rules.mjs @@ -1140,7 +1140,7 @@ export const forbiddenContentRules = [ ], }, { - path: 'src/crates/assembly/core/src/agentic/tools/implementations/task/execution.rs', + path: 'src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/execution.rs', patterns: [ { regex: /\bDeepReviewIncrementalCache\b/, diff --git a/scripts/core-boundaries/rules/source/required-rules.mjs b/scripts/core-boundaries/rules/source/required-rules.mjs index cc25b59347..149cb8a226 100644 --- a/scripts/core-boundaries/rules/source/required-rules.mjs +++ b/scripts/core-boundaries/rules/source/required-rules.mjs @@ -2497,7 +2497,7 @@ export const requiredContentRules = [ ], }, { - path: 'src/crates/assembly/core/src/agentic/tools/implementations/task/deep_review.rs', + path: 'src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/deep_review.rs', reason: 'TaskTool must keep DeepReview retry/result presentation as a facade call instead of re-owning provider-neutral policy text or data shaping', patterns: [ @@ -2520,7 +2520,7 @@ export const requiredContentRules = [ ], }, { - path: 'src/crates/assembly/core/src/agentic/tools/implementations/task/execution.rs', + path: 'src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/execution.rs', reason: 'TaskTool execution must keep DeepReview retry/result presentation as facade calls instead of re-owning provider-neutral policy text or data shaping', patterns: [ @@ -7826,7 +7826,7 @@ export const requiredContentRules = [ ], }, { - path: 'src/crates/assembly/core/src/agentic/tools/implementations/task/input.rs', + path: 'src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/input.rs', reason: 'core Task input must continue owning fork-aware background subagent launch semantics until a reviewed agent-runtime port preserves delivery behavior', patterns: [ @@ -7845,7 +7845,7 @@ export const requiredContentRules = [ ], }, { - path: 'src/crates/assembly/core/src/agentic/tools/implementations/task/execution.rs', + path: 'src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/execution.rs', reason: 'core Task execution must continue owning background subagent launch semantics until a reviewed agent-runtime port preserves delivery behavior', patterns: [ @@ -7868,7 +7868,7 @@ export const requiredContentRules = [ ], }, { - path: 'src/crates/assembly/core/src/agentic/tools/implementations/task/background.rs', + path: 'src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/background.rs', reason: 'core Task background acknowledgement must remain assistant-visible and expose the task id needed for explicit result collection', patterns: [ @@ -7879,7 +7879,7 @@ export const requiredContentRules = [ ], }, { - path: 'src/crates/assembly/core/src/agentic/tools/implementations/task/tests.rs', + path: 'src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/tests.rs', reason: 'core Task tests must preserve background acknowledgement shape', patterns: [ diff --git a/scripts/core-boundaries/self-test.mjs b/scripts/core-boundaries/self-test.mjs index e4db04b876..c622ac8538 100644 --- a/scripts/core-boundaries/self-test.mjs +++ b/scripts/core-boundaries/self-test.mjs @@ -830,7 +830,7 @@ export function runManifestParserSelfTest({ } } const coreTaskToolRuleText = forbiddenRuleTextForPath( - 'src/crates/assembly/core/src/agentic/tools/implementations/task/execution.rs', + 'src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/execution.rs', ); if (!coreTaskToolRuleText) { throw new Error('missing core TaskTool DeepReview boundary rule'); @@ -4269,7 +4269,7 @@ export function runManifestParserSelfTest({ contracts: ['builtin_agent_specs', 'runtime_agents::default_model_id_for_builtin_agent'], }, { - path: 'src/crates/assembly/core/src/agentic/tools/implementations/task/input.rs', + path: 'src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/input.rs', contracts: [ 'fork_context', 'SubagentContextMode::Fork', @@ -4277,7 +4277,7 @@ export function runManifestParserSelfTest({ ], }, { - path: 'src/crates/assembly/core/src/agentic/tools/implementations/task/execution.rs', + path: 'src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/execution.rs', contracts: [ 'child_delegation_policy', 'start_background_subagent', @@ -4285,11 +4285,11 @@ export function runManifestParserSelfTest({ ], }, { - path: 'src/crates/assembly/core/src/agentic/tools/implementations/task/background.rs', + path: 'src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/background.rs', contracts: ['Background subagent started successfully'], }, { - path: 'src/crates/assembly/core/src/agentic/tools/implementations/task/tests.rs', + path: 'src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/tests.rs', contracts: [ 'background_subagent_start_acknowledgement_exposes_agent_wait_task_id', ' Self { + Self::new() + } +} + +impl TaskTool { + pub fn new() -> Self { + Self + } + + fn render_legacy_description() -> String { + AgentExecutionTool::new() + .render_description() + .replace("AgentSpawn", "Task") + .replace("AgentSendInput", "Task") + .replace("AgentControl", "Task") + } +} + +/// Compatibility implementation for custom agents that still explicitly list +/// the original combined collaboration tool. Built-in modes use the split +/// Agent* tools, while this entry point keeps existing custom-agent +/// definitions executable without a configuration migration. +#[async_trait] +impl Tool for TaskTool { + fn name(&self) -> &str { + "Task" + } + + fn manages_own_execution_timeout(&self) -> bool { + true + } + + async fn description(&self) -> OpenBitFunResult { + Ok(Self::render_legacy_description()) + } + + async fn is_available_in_context(&self, _context: Option<&ToolUseContext>) -> bool { + true + } + + fn short_description(&self) -> String { + "Delegate work to a subagent task and collect the result.".to_string() + } + + async fn description_with_context( + &self, + _context: Option<&ToolUseContext>, + ) -> OpenBitFunResult { + Ok(Self::render_legacy_description()) + } + + fn input_schema(&self) -> Value { + AgentExecutionTool::regular_input_schema() + } + + fn output_schema(&self) -> Value { + json!({ + "type": "object", + "properties": { + "status": {"type": "string"}, + "agent_id": {"type": "string"}, + "bg_task_id": {"type": "string"}, + "result": {"type": "string"}, + "error": {"type": "string"} + }, + "additionalProperties": true + }) + } + + async fn input_schema_for_model_with_context( + &self, + _context: Option<&ToolUseContext>, + ) -> Value { + AgentExecutionTool::regular_input_schema() + } + + fn is_readonly(&self) -> bool { + false + } + + fn is_concurrency_safe(&self, input: Option<&Value>) -> bool { + AgentExecutionTool::new().is_concurrency_safe(input) + } + + fn permission_intents( + &self, + input: &Value, + context: &ToolUseContext, + ) -> OpenBitFunResult> { + AgentExecutionTool::new().permission_intents(input, context) + } + + async fn validate_input( + &self, + input: &Value, + context: Option<&ToolUseContext>, + ) -> ValidationResult { + AgentExecutionTool::validate_invocation_input( + input, + false, + context.and_then(ToolUseContext::workspace_root), + ) + .await + } + + fn render_tool_use_message(&self, input: &Value, options: &ToolRenderOptions) -> String { + match TaskAction::parse(input).ok() { + Some(TaskAction::Cancel) => input + .get("agent_id") + .and_then(Value::as_str) + .map(|agent_id| format!("Cancelling background task: {agent_id}")) + .unwrap_or_else(|| "Cancelling background task".to_string()), + Some(TaskAction::SendInput) => input + .get("agent_id") + .and_then(Value::as_str) + .map(|agent_id| { + if options.verbose { + format!("Sending input to task: {agent_id}") + } else { + format!("Task input: {agent_id}") + } + }) + .unwrap_or_else(|| "Sending input to task".to_string()), + Some(TaskAction::Spawn) | None => input + .get("agent_id") + .and_then(Value::as_str) + .map(|agent_id| { + if options.verbose { + format!("Creating task: {agent_id}") + } else { + format!("Task: {agent_id}") + } + }) + .unwrap_or_else(|| "Creating task".to_string()), + } + } + + async fn call_impl( + &self, + input: &Value, + context: &ToolUseContext, + ) -> OpenBitFunResult> { + AgentExecutionTool::new() + .call_task_impl(input, context) + .await + } +} diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/task/mod.rs b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/mod.rs similarity index 70% rename from src/crates/assembly/core/src/agentic/tools/implementations/task/mod.rs rename to src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/mod.rs index 58f438ef55..07d3c1a6ad 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/task/mod.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/mod.rs @@ -1,3 +1,5 @@ +//! Agent collaboration tools and shared delegation execution. + use crate::agentic::agents::{ get_agent_registry, AgentInfo, SubagentListScope, SubagentQueryContext, }; @@ -36,17 +38,24 @@ use std::collections::HashMap; use std::time::Instant; mod agent_control; +pub mod agent_control_tool; +pub mod agent_list_tool; +pub mod agent_wait_tool; mod background; mod deep_review; mod execution; mod input; mod launch_review_agent; +mod legacy_task; mod schema; mod validation; +pub use agent_control_tool::AgentControlTool; +pub use agent_list_tool::AgentListTool; +pub use agent_wait_tool::AgentWaitTool; pub use launch_review_agent::LaunchReviewAgentTool; +pub use legacy_task::TaskTool; -pub struct TaskTool; pub(crate) struct AgentExecutionTool; pub struct AgentSpawnTool; pub struct AgentSendInputTool; @@ -54,26 +63,6 @@ pub struct AgentSendInputTool; const LARGE_TASK_PROMPT_SOFT_LINE_LIMIT: usize = 180; const LARGE_TASK_PROMPT_SOFT_BYTE_LIMIT: usize = 16 * 1024; -impl Default for TaskTool { - fn default() -> Self { - Self::new() - } -} - -impl TaskTool { - pub fn new() -> Self { - Self - } - - fn render_legacy_description() -> String { - AgentExecutionTool::new() - .render_description() - .replace("AgentSpawn", "Task") - .replace("AgentSendInput", "Task") - .replace("AgentControl", "Task") - } -} - impl Default for AgentExecutionTool { fn default() -> Self { Self::new() @@ -311,135 +300,5 @@ impl Tool for AgentExecutionTool { } } -/// Compatibility implementation for custom agents that still explicitly list -/// the original combined collaboration tool. Built-in modes use the split -/// Agent* tools above, while this entry point keeps existing custom-agent -/// definitions executable without a configuration migration. -#[async_trait] -impl Tool for TaskTool { - fn name(&self) -> &str { - "Task" - } - - fn manages_own_execution_timeout(&self) -> bool { - true - } - - async fn description(&self) -> OpenBitFunResult { - Ok(Self::render_legacy_description()) - } - - async fn is_available_in_context(&self, _context: Option<&ToolUseContext>) -> bool { - true - } - - fn short_description(&self) -> String { - "Delegate work to a subagent task and collect the result.".to_string() - } - - async fn description_with_context( - &self, - _context: Option<&ToolUseContext>, - ) -> OpenBitFunResult { - Ok(Self::render_legacy_description()) - } - - fn input_schema(&self) -> Value { - AgentExecutionTool::regular_input_schema() - } - - fn output_schema(&self) -> Value { - json!({ - "type": "object", - "properties": { - "status": {"type": "string"}, - "agent_id": {"type": "string"}, - "bg_task_id": {"type": "string"}, - "result": {"type": "string"}, - "error": {"type": "string"} - }, - "additionalProperties": true - }) - } - - async fn input_schema_for_model_with_context( - &self, - _context: Option<&ToolUseContext>, - ) -> Value { - AgentExecutionTool::regular_input_schema() - } - - fn is_readonly(&self) -> bool { - false - } - - fn is_concurrency_safe(&self, input: Option<&Value>) -> bool { - AgentExecutionTool::new().is_concurrency_safe(input) - } - - fn permission_intents( - &self, - input: &Value, - context: &ToolUseContext, - ) -> OpenBitFunResult> { - AgentExecutionTool::new().permission_intents(input, context) - } - - async fn validate_input( - &self, - input: &Value, - context: Option<&ToolUseContext>, - ) -> ValidationResult { - AgentExecutionTool::validate_invocation_input( - input, - false, - context.and_then(ToolUseContext::workspace_root), - ) - .await - } - - fn render_tool_use_message(&self, input: &Value, options: &ToolRenderOptions) -> String { - match TaskAction::parse(input).ok() { - Some(TaskAction::Cancel) => input - .get("agent_id") - .and_then(Value::as_str) - .map(|agent_id| format!("Cancelling background task: {agent_id}")) - .unwrap_or_else(|| "Cancelling background task".to_string()), - Some(TaskAction::SendInput) => input - .get("agent_id") - .and_then(Value::as_str) - .map(|agent_id| { - if options.verbose { - format!("Sending input to task: {agent_id}") - } else { - format!("Task input: {agent_id}") - } - }) - .unwrap_or_else(|| "Sending input to task".to_string()), - Some(TaskAction::Spawn) | None => input - .get("agent_id") - .and_then(Value::as_str) - .map(|agent_id| { - if options.verbose { - format!("Creating task: {agent_id}") - } else { - format!("Task: {agent_id}") - } - }) - .unwrap_or_else(|| "Creating task".to_string()), - } - } - - async fn call_impl( - &self, - input: &Value, - context: &ToolUseContext, - ) -> OpenBitFunResult> { - AgentExecutionTool::new() - .call_task_impl(input, context) - .await - } -} - #[cfg(test)] mod tests; diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/task/schema.rs b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/schema.rs similarity index 100% rename from src/crates/assembly/core/src/agentic/tools/implementations/task/schema.rs rename to src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/schema.rs diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/task/tests.rs b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/tests.rs similarity index 100% rename from src/crates/assembly/core/src/agentic/tools/implementations/task/tests.rs rename to src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/tests.rs diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/task/validation.rs b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/validation.rs similarity index 100% rename from src/crates/assembly/core/src/agentic/tools/implementations/task/validation.rs rename to src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/validation.rs diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/mod.rs b/src/crates/assembly/core/src/agentic/tools/implementations/mod.rs index 0b4a5bf0d8..dd16dc7587 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/mod.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/mod.rs @@ -1,8 +1,6 @@ //! Tool implementation module -pub mod agent_control_tool; -pub mod agent_list_tool; -pub mod agent_wait_tool; +pub mod agent_collaboration; #[cfg(feature = "tools-image-analysis")] pub mod analyze_image_tool; pub mod ask_user_question_tool; @@ -77,7 +75,6 @@ pub mod session_history_tool; pub mod session_message_tool; pub mod skill_tool; pub mod skills; -pub mod task; pub mod thread_goal_tools; pub mod todo_write_tool; pub mod util; @@ -90,9 +87,11 @@ pub mod worktree_tool; #[deprecated(note = "GetToolSpecTool is owned by the product tool runtime boundary")] pub use crate::agentic::tools::product_runtime::GetToolSpecTool; -pub use agent_control_tool::AgentControlTool; -pub use agent_list_tool::AgentListTool; -pub use agent_wait_tool::AgentWaitTool; +pub(crate) use agent_collaboration::AgentExecutionTool; +pub use agent_collaboration::{ + AgentControlTool, AgentListTool, AgentSendInputTool, AgentSpawnTool, AgentWaitTool, + LaunchReviewAgentTool, TaskTool, +}; #[cfg(feature = "tools-image-analysis")] pub use analyze_image_tool::AnalyzeImageTool; pub use ask_user_question_tool::AskUserQuestionTool; @@ -157,8 +156,6 @@ pub use session_control_tool::SessionControlTool; pub use session_history_tool::SessionHistoryTool; pub use session_message_tool::SessionMessageTool; pub use skill_tool::SkillTool; -pub(crate) use task::AgentExecutionTool; -pub use task::{AgentSendInputTool, AgentSpawnTool, LaunchReviewAgentTool, TaskTool}; pub use thread_goal_tools::{CreateGoalTool, GetGoalTool, UpdateGoalTool}; pub use todo_write_tool::TodoWriteTool; #[cfg(feature = "tools-image-analysis")] diff --git a/src/crates/assembly/core/src/agentic/tools/pipeline/tool_pipeline.rs b/src/crates/assembly/core/src/agentic/tools/pipeline/tool_pipeline.rs index a0de4b992d..0ef8cc41fa 100644 --- a/src/crates/assembly/core/src/agentic/tools/pipeline/tool_pipeline.rs +++ b/src/crates/assembly/core/src/agentic/tools/pipeline/tool_pipeline.rs @@ -3742,7 +3742,7 @@ mod tests { DialogRoundInjectionInterrupt, SessionRoundInjectionBuffer, }; use crate::agentic::tools::framework::{Tool, ToolResult, ValidationResult}; - use crate::agentic::tools::implementations::task::AgentExecutionTool; + use crate::agentic::tools::implementations::agent_collaboration::AgentExecutionTool; use crate::agentic::tools::tool_context_runtime::ToolUseContext; use crate::agentic::tools::ToolRuntimeRestrictions; use crate::agentic::WorkspaceBinding; From 8ab86b711265c9400b777230746e298755671be5 Mon Sep 17 00:00:00 2001 From: wsp Date: Tue, 17 Nov 2026 16:06:47 +0800 Subject: [PATCH 2/5] feat(agent): allow users to disable subagent model overrides Add a default-enabled configuration setting and execution settings toggle. Hide model selection parameters and guidance when disabled, and enforce the execution host policy before collaboration calls run. Refresh tool specifications when the policy changes and negotiate peer support. Cover configuration compatibility, tool catalogs, execution checks, and settings behavior. --- docs/interactive-capabilities/README.md | 12 +- .../capabilities.json | 86 ++++++- .../capabilities/setting.tools.execution.md | 3 + .../technical/product-control-open-audit.json | 2 +- .../technical/tauri-command-map.json | 2 +- .../agent_collaboration/agent_control.rs | 18 +- .../agent_collaboration/execution.rs | 1 + .../launch_review_agent.rs | 29 ++- .../agent_collaboration/legacy_task.rs | 22 +- .../agent_collaboration/mod.rs | 18 +- .../agent_collaboration/model_policy.rs | 105 +++++++++ .../agent_collaboration/schema.rs | 73 ++++-- .../agent_collaboration/tests.rs | 218 ++++++++++++++++++ .../agentic/tools/product_runtime/catalog.rs | 197 ++++++++-------- .../core/src/agentic/tools/registry.rs | 13 +- .../contracts/config-contracts/src/types.rs | 41 ++++ .../generated/product-control-catalog.json | 90 +++++++- .../generated/remote-surface-registry.json | 5 +- .../src/product_control_owner_registry.rs | 6 + .../src/remote_surface/capabilities.rs | 5 + .../execution/tool-contracts/src/framework.rs | 6 + .../interactive-capabilities/catalog.json | 29 +++ src/web-ui/README.md | 18 ++ .../generated/interactive-capabilities.json | 86 ++++++- .../pages/ai/ExecutionSettingsPage.tsx | 2 + .../ai/SubagentModelOverrideSection.test.tsx | 112 +++++++++ .../pages/ai/SubagentModelOverrideSection.tsx | 80 +++++++ .../pages/shared/RuntimeSettings.test.tsx | 1 + .../api/generated/productControl.ts | 4 +- .../api/generated/remoteSurface.ts | 5 +- .../config/services/subagentModelPolicy.ts | 26 +++ .../src/infrastructure/config/types/index.ts | 1 + .../peer-device/PeerConnectionManager.test.ts | 2 + .../peer-device/PeerConnectionManager.ts | 3 + .../locales/en-US/settings/agentic-tools.json | 11 +- .../locales/zh-CN/settings/agentic-tools.json | 11 +- .../locales/zh-TW/settings/agentic-tools.json | 11 +- 37 files changed, 1193 insertions(+), 161 deletions(-) create mode 100644 src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/model_policy.rs create mode 100644 src/web-ui/src/app/scenes/settings/pages/ai/SubagentModelOverrideSection.test.tsx create mode 100644 src/web-ui/src/app/scenes/settings/pages/ai/SubagentModelOverrideSection.tsx create mode 100644 src/web-ui/src/infrastructure/config/services/subagentModelPolicy.ts diff --git a/docs/interactive-capabilities/README.md b/docs/interactive-capabilities/README.md index c5a30fae11..91c15405ed 100644 --- a/docs/interactive-capabilities/README.md +++ b/docs/interactive-capabilities/README.md @@ -1,9 +1,9 @@ # OpenBitFun 功能与设置目录 / OpenBitFun Features & Settings -OpenBitFun Playbook 当前包含 **24 个功能**和 **23 个设置页**,共 **47 个**用户可理解的条目、**368 项**有源码证据的子能力。每个条目有独立 Markdown,并直接服务于说明书网站、OpenBitFun 全局搜索和 `OpenBitFunControl` 智能体工具。 +OpenBitFun Playbook 当前包含 **24 个功能**和 **23 个设置页**,共 **47 个**用户可理解的条目、**369 项**有源码证据的子能力。每个条目有独立 Markdown,并直接服务于说明书网站、OpenBitFun 全局搜索和 `OpenBitFunControl` 智能体工具。 -OpenBitFun Playbook currently contains **24 features**, **23 settings pages**, and **368** source-backed sub-capabilities across **47** user-facing entries. Every entry has its own Markdown page and directly powers the website, in-app global search, and the `OpenBitFunControl` agent tool. +OpenBitFun Playbook currently contains **24 features**, **23 settings pages**, and **369** source-backed sub-capabilities across **47** user-facing entries. Every entry has its own Markdown page and directly powers the website, in-app global search, and the `OpenBitFunControl` agent tool. ## 唯一事实源 / Single source of truth @@ -33,14 +33,14 @@ Docs, website, search, and agents see only features, settings, and documented su ## 控制边界 / Control boundary -- 每个子能力都明确标记为直接控制、委托给专用智能体工具、需交互打开或不支持;“打开页面”不会再被统计成“智能体已控制”。当前覆盖:直接 **63**、委托 **74**、需交互 **231**、不支持 **0**。 +- 每个子能力都明确标记为直接控制、委托给专用智能体工具、需交互打开或不支持;“打开页面”不会再被统计成“智能体已控制”。当前覆盖:直接 **64**、委托 **74**、需交互 **231**、不支持 **0**。 - 稳定行为声明为带 JSON 输入契约的 `operations` 或 `options`,并绑定原生产品控制 Provider;智能体不接触原始 Tauri Command。 -- `OpenBitFunControl list` 和 `search` 都返回带 `nextCursor` 的精简分页结果;目录可持续增长,不靠固定总量上限。完整目录和 368 项子能力都不会写入 system prompt。 +- `OpenBitFunControl list` 和 `search` 都返回带 `nextCursor` 的精简分页结果;目录可持续增长,不靠固定总量上限。完整目录和 369 项子能力都不会写入 system prompt。 - 目录发现与契约读取不依赖 React 或可见窗口。普通配置型 option 统一由 Product Assembly 的共享 ConfigService 执行器读、写并回读,因此 Desktop、CLI 与 Headless 表面走同一份实现;只有宿主原生 operation/provider option 和界面导航按表面注册适配器,缺失时必须明确返回不可用,禁止静默回退本机。只读智能体只能发现和读取目录。 -- Every documented item is classified as direct control, delegated Agent control, interactive opening, or unsupported; opening a page is never counted as direct control. Current coverage is **63 direct**, **74 delegated**, **231 interactive**, and **0 unsupported**. +- Every documented item is classified as direct control, delegated Agent control, interactive opening, or unsupported; opening a page is never counted as direct control. Current coverage is **64 direct**, **74 delegated**, **231 interactive**, and **0 unsupported**. - Stable behavior becomes a typed `operation` or `option` with a JSON input contract and a native product-control provider. Agents never receive raw Tauri commands. -- `OpenBitFunControl list` and `search` return compact pages with a `nextCursor`; the catalog can grow without a fixed total-size ceiling. Neither the full catalog nor its 368 documented items enters the system prompt. +- `OpenBitFunControl list` and `search` return compact pages with a `nextCursor`; the catalog can grow without a fixed total-size ceiling. Neither the full catalog nor its 369 documented items enters the system prompt. - Discovery and contract lookup do not depend on React or a visible window. Ordinary config-backed options are read, written, and read back by one Product Assembly ConfigService executor shared by Desktop, CLI, and headless surfaces. Only host-native operations/provider options and presentation routes install surface adapters; missing adapters return explicit unavailability without local fallback. Read-only agents may only discover and inspect entries. ## 防腐化门禁 / Anti-drift gates diff --git a/docs/interactive-capabilities/capabilities.json b/docs/interactive-capabilities/capabilities.json index 4120d733ef..a11868d258 100644 --- a/docs/interactive-capabilities/capabilities.json +++ b/docs/interactive-capabilities/capabilities.json @@ -4,8 +4,8 @@ "title": "OpenBitFun Playbook", "origin": "https://playbook.openbitfun.com", "source": "src/shared/interactive-capabilities/catalog.json", - "digest": "4b8a786017df37df61ff4c749771e0af19c851b6be51ed46504425c9bdf992bd", - "ownerDigest": "31d6371f7765bde7bee88e22a6a4f03c2c5370e138cf49975bdc88f3c5eeb052", + "digest": "fe4be08cb20c2d67857891380d223a77d420345b94e2733d0000d14485027697", + "ownerDigest": "1fdb9c49d404c02483c08e1e0fe9effa0aaa4f0f2914578bcaa63e04de16cc16", "searchAcceptance": [ { "id": "native-office-generation", @@ -187,9 +187,9 @@ "features": 24, "settings": 23, "userFacing": 47, - "documentedItems": 368, + "documentedItems": 369, "controlCoverage": { - "direct": 63, + "direct": 64, "delegated": 74, "interactive": 231, "unsupported": 0 @@ -17809,7 +17809,8 @@ "computer-use", "computer-use-permissions", "browser-auto-connect", - "browser-setup" + "browser-setup", + "subagent-model-override" ], "kind": "query", "risk": "read", @@ -18355,6 +18356,50 @@ "pageId": "tools.execution" } }, + { + "id": "setting.tools.execution:option:subagent-model-override", + "capabilityId": "setting.tools.execution", + "itemIds": [ + "subagent-model-override" + ], + "kind": "option", + "risk": "write", + "executionHost": "productHost", + "availability": { + "desktop": { + "available": true + }, + "cli": { + "available": true + }, + "peer": { + "available": true, + "requiredCapabilities": [ + "product_control_v1" + ] + }, + "remoteControl": { + "available": true + }, + "detachedDispatch": { + "available": true + } + }, + "inputSchema": { + "type": "boolean" + }, + "outputSchema": { + "type": "object", + "additionalProperties": true + }, + "valueSource": { + "kind": "static" + }, + "presentationTarget": { + "kind": "settings", + "pageId": "tools.execution" + } + }, { "id": "setting.tools.execution:open:question-timeout", "capabilityId": "setting.tools.execution", @@ -34993,6 +35038,25 @@ "reasonZh": "可用浏览器和 CDP 状态来自当前机器且可能要求重启确认;智能体可打开配置入口,实际网页操作则使用统一的 ControlHub 浏览器契约。", "reasonEn": "Available browsers and CDP state come from the current machine and may require restart confirmation; the Agent can open setup, while page automation uses the shared ControlHub browser contract." } + }, + { + "id": "subagent-model-override", + "titleZh": "允许 Agent 指定子 Agent 模型", + "titleEn": "Allow agents to choose subagent models", + "destination": { + "kind": "settings", + "pageId": "tools.execution", + "viewId": "advanced" + }, + "control": { + "kind": "direct", + "operations": [], + "options": [ + { + "id": "subagent-model-override" + } + ] + } } ], "stepsZh": [ @@ -35170,6 +35234,16 @@ "openui" ] } + }, + { + "id": "subagent-model-override", + "titleZh": "允许 Agent 指定子 Agent 模型", + "titleEn": "Allow agents to choose subagent models", + "descriptionZh": "控制 Agent 能否在启动或继续执行子 Agent 时指定模型。", + "descriptionEn": "Control whether agents can override subagent models when launching or continuing work.", + "valueSchema": { + "type": "boolean" + } } ], "searchTerms": [ @@ -35246,6 +35320,8 @@ "Choose whether OpenBitFun automatically connects to your CDP browser on startup", "发现并选择外部浏览器、开启默认 CDP 配置或按需重启连接", "Discover and choose an external browser, enable default CDP, or reconnect on demand", + "允许 Agent 指定子 Agent 模型", + "Allow agents to choose subagent models", "开启按需加载工具帮我节省初始上下文", "把子智能体最大并发改为 8,任务并行方式设为安全并行", "单次工具调用超时改成 600 秒", diff --git a/docs/interactive-capabilities/capabilities/setting.tools.execution.md b/docs/interactive-capabilities/capabilities/setting.tools.execution.md index 12eea869aa..75e9d45a76 100644 --- a/docs/interactive-capabilities/capabilities/setting.tools.execution.md +++ b/docs/interactive-capabilities/capabilities/setting.tools.execution.md @@ -94,6 +94,8 @@ Tune tool call and user-question timeouts, subagent default models and concurren - Discover and choose an external browser, enable default CDP, or reconnect on demand - 说明:前往“工具与集成 → 浏览器与桌面控制”选择 Chrome / Edge 并查看实时 CDP 端口连接状态。 - Why & how: Opens Tools & Integrations → Browser & Desktop Control to pick Chrome or Edge and manage live CDP connections. +- **智能体可直接控制 / Direct Agent control** · 允许 Agent 指定子 Agent 模型 + - Allow agents to choose subagent models ## 怎么用 / How to use it @@ -129,6 +131,7 @@ Tune tool call and user-question timeouts, subagent default models and concurren | 启动时自动连接浏览器 / Auto-connect browser on startup | `boolean` | 控制 OpenBitFun 启动时是否自动尝试连接外部 CDP 浏览器(默认关闭)。 | Choose whether OpenBitFun automatically tries to connect external CDP browser control on launch (off by default). | | 工具参数 JSON 安全修复 / Safe tool-argument JSON repair | `boolean` | 在严格安全边界内自动修复模型输出的轻微 JSON 语法瑕疵,减少因格式小错导致的调用失败。 | Automatically repair minor JSON syntax glitches in model tool arguments within strict safety bounds. | | 默认生成式 UI 组件库 / Default GenUI component library | `openbitfun` / `openui` | 指定新建交互式 GenUI 应用默认采用的组件库与设计规范(默认 openui);已有应用保留原有目标身份。 | Select the component library and bound design spec for newly generated GenUI apps (openui by default); existing apps keep their original target. | +| 允许 Agent 指定子 Agent 模型 / Allow agents to choose subagent models | `boolean` | 控制 Agent 能否在启动或继续执行子 Agent 时指定模型。 | Control whether agents can override subagent models when launching or continuing work. | ## 可以直接对智能体说 / Try saying diff --git a/docs/interactive-capabilities/technical/product-control-open-audit.json b/docs/interactive-capabilities/technical/product-control-open-audit.json index 30dda4b4e2..62f6abb135 100644 --- a/docs/interactive-capabilities/technical/product-control-open-audit.json +++ b/docs/interactive-capabilities/technical/product-control-open-audit.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "generatedFrom": "src/shared/interactive-capabilities/catalog.json", - "catalogDigest": "4b8a786017df37df61ff4c749771e0af19c851b6be51ed46504425c9bdf992bd", + "catalogDigest": "fe4be08cb20c2d67857891380d223a77d420345b94e2733d0000d14485027697", "count": 231, "reasonCounts": { "externalAuth": 4, diff --git a/docs/interactive-capabilities/technical/tauri-command-map.json b/docs/interactive-capabilities/technical/tauri-command-map.json index 27efcc5cf0..6829e9e967 100644 --- a/docs/interactive-capabilities/technical/tauri-command-map.json +++ b/docs/interactive-capabilities/technical/tauri-command-map.json @@ -1,7 +1,7 @@ { "schemaVersion": 2, "generatedFrom": "src/shared/interactive-capabilities/catalog.json", - "catalogDigest": "4b8a786017df37df61ff4c749771e0af19c851b6be51ed46504425c9bdf992bd", + "catalogDigest": "fe4be08cb20c2d67857891380d223a77d420345b94e2733d0000d14485027697", "commandCount": 705, "coverage": { "commandCount": 705, diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/agent_control.rs b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/agent_control.rs index 6e716708fa..e397a00474 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/agent_control.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/agent_control.rs @@ -160,7 +160,7 @@ impl Tool for AgentSpawnTool { } async fn description(&self) -> OpenBitFunResult { - Ok(self.render_agent_spawn_description()) + Ok(self.render_agent_spawn_description(ModelOverridePolicy::presentation().await?.allowed)) } fn short_description(&self) -> String { @@ -171,6 +171,10 @@ impl Tool for AgentSpawnTool { Self::agent_spawn_input_schema() } + async fn input_schema_for_model(&self) -> Value { + ModelOverridePolicy::model_schema(self.input_schema()).await + } + fn output_schema(&self) -> Value { json!({ "type": "object", @@ -223,6 +227,9 @@ impl Tool for AgentSpawnTool { input: &Value, _context: Option<&ToolUseContext>, ) -> ValidationResult { + if let Some(validation) = model_override_validation(input).await { + return validation; + } validate_task_input(Self::task_input(input), self.name()) } @@ -231,6 +238,7 @@ impl Tool for AgentSpawnTool { input: &Value, context: &ToolUseContext, ) -> OpenBitFunResult> { + ModelOverridePolicy::enforce(input).await?; let results = AgentExecutionTool::new() .call_task_impl(&Self::task_input(input)?, context) .await?; @@ -327,6 +335,10 @@ impl Tool for AgentSendInputTool { Self::agent_send_input_schema() } + async fn input_schema_for_model(&self) -> Value { + ModelOverridePolicy::model_schema(self.input_schema()).await + } + fn output_schema(&self) -> Value { json!({ "type": "object", @@ -371,6 +383,9 @@ impl Tool for AgentSendInputTool { input: &Value, _context: Option<&ToolUseContext>, ) -> ValidationResult { + if let Some(validation) = model_override_validation(input).await { + return validation; + } validate_task_input(Self::task_input(input), self.name()) } @@ -379,6 +394,7 @@ impl Tool for AgentSendInputTool { input: &Value, context: &ToolUseContext, ) -> OpenBitFunResult> { + ModelOverridePolicy::enforce(input).await?; let results = AgentExecutionTool::new() .call_task_impl(&Self::task_input(input)?, context) .await?; diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/execution.rs b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/execution.rs index 9f0c581313..dde8e3aa29 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/execution.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/execution.rs @@ -244,6 +244,7 @@ impl AgentExecutionTool { context: &ToolUseContext, is_deep_review_parent: bool, ) -> OpenBitFunResult> { + ModelOverridePolicy::enforce(input).await?; let start_time = std::time::Instant::now(); let invocation = Self::parse_invocation(input, is_deep_review_parent)?; diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/launch_review_agent.rs b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/launch_review_agent.rs index bcc829e9ff..a5a2dcb141 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/launch_review_agent.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/launch_review_agent.rs @@ -206,8 +206,14 @@ impl LaunchReviewAgentTool { }) } - fn render_description() -> String { - r#"Launch one foreground-waited DeepReview worker. + fn render_description(allow_model_override: bool) -> String { + let model_field = if allow_model_override { + "`model_id`, " + } else { + "" + }; + format!( + r#"Launch one foreground-waited DeepReview worker. When the prepared manifest contains active work packets, launch only those packets in declared batch order. Manifest-declared managed Review packets may use bounded same-role file shards; every call blocks the owning Review turn until its result, timeout, or cancellation is recorded. Never convert a packet to a background AgentSpawn. @@ -221,13 +227,13 @@ The capability catalog below contains short descriptions only. For an adaptive R For a managed packet, pass its exact manifest `packet_id` in the top-level `packet_id` field. Runtime rejects missing or unknown managed packet ids. -Do not put `subagent_type`, `packet_id`, `description`, `model_id`, `timeout_seconds`, `retry`, `auto_retry`, `retry_coverage`, or `focused_assignment` inside the prompt string. +Do not put `subagent_type`, `packet_id`, `description`, {model_field}`timeout_seconds`, `retry`, `auto_retry`, `retry_coverage`, or `focused_assignment` inside the prompt string. Retry rules: - Set `retry=true` only when re-dispatching the same reviewer after `partial_timeout` or a transient capacity skip in the current turn. - Retry calls must include `retry_coverage` with `source_packet_id`, `source_status`, `covered_files`, and a smaller `retry_scope_files` list. - Do not set `auto_retry=true` unless this is a backend-owned bounded automatic retry admitted by Review Team settings."# - .to_string() + ) } fn render_tool_use_message(input: &Value, options: &ToolRenderOptions) -> String { @@ -408,14 +414,17 @@ impl Tool for LaunchReviewAgentTool { } async fn description(&self) -> OpenBitFunResult { - Ok(Self::render_description()) + Ok(Self::render_description( + ModelOverridePolicy::presentation().await?.allowed, + )) } async fn description_with_context( &self, context: Option<&ToolUseContext>, ) -> OpenBitFunResult { - let mut description = Self::render_description(); + let mut description = + Self::render_description(ModelOverridePolicy::presentation().await?.allowed); if let Some(context) = context.filter(|context| { !context.is_remote() && context @@ -447,6 +456,10 @@ impl Tool for LaunchReviewAgentTool { Self::launch_input_schema() } + async fn input_schema_for_model(&self) -> Value { + ModelOverridePolicy::model_schema(self.input_schema()).await + } + fn output_schema(&self) -> Value { json!({ "type": "object", @@ -521,6 +534,9 @@ impl Tool for LaunchReviewAgentTool { input: &Value, context: Option<&ToolUseContext>, ) -> ValidationResult { + if let Some(validation) = model_override_validation(input).await { + return validation; + } match Self::parse_invocation(input) { Ok(invocation) => { if let Some(context) = context { @@ -593,6 +609,7 @@ impl Tool for LaunchReviewAgentTool { input: &Value, context: &ToolUseContext, ) -> OpenBitFunResult> { + ModelOverridePolicy::enforce(input).await?; self.call_launch_review_agent_impl(input, context).await } } diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/legacy_task.rs b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/legacy_task.rs index 190a1bf9cf..d956e85d08 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/legacy_task.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/legacy_task.rs @@ -14,9 +14,9 @@ impl TaskTool { Self } - fn render_legacy_description() -> String { + fn render_legacy_description(allow_model_override: bool) -> String { AgentExecutionTool::new() - .render_description() + .render_description(allow_model_override) .replace("AgentSpawn", "Task") .replace("AgentSendInput", "Task") .replace("AgentControl", "Task") @@ -38,7 +38,9 @@ impl Tool for TaskTool { } async fn description(&self) -> OpenBitFunResult { - Ok(Self::render_legacy_description()) + Ok(Self::render_legacy_description( + ModelOverridePolicy::presentation().await?.allowed, + )) } async fn is_available_in_context(&self, _context: Option<&ToolUseContext>) -> bool { @@ -53,13 +55,19 @@ impl Tool for TaskTool { &self, _context: Option<&ToolUseContext>, ) -> OpenBitFunResult { - Ok(Self::render_legacy_description()) + Ok(Self::render_legacy_description( + ModelOverridePolicy::presentation().await?.allowed, + )) } fn input_schema(&self) -> Value { AgentExecutionTool::regular_input_schema() } + async fn input_schema_for_model(&self) -> Value { + ModelOverridePolicy::model_schema(self.input_schema()).await + } + fn output_schema(&self) -> Value { json!({ "type": "object", @@ -78,7 +86,7 @@ impl Tool for TaskTool { &self, _context: Option<&ToolUseContext>, ) -> Value { - AgentExecutionTool::regular_input_schema() + self.input_schema_for_model().await } fn is_readonly(&self) -> bool { @@ -102,6 +110,9 @@ impl Tool for TaskTool { input: &Value, context: Option<&ToolUseContext>, ) -> ValidationResult { + if let Some(validation) = model_override_validation(input).await { + return validation; + } AgentExecutionTool::validate_invocation_input( input, false, @@ -147,6 +158,7 @@ impl Tool for TaskTool { input: &Value, context: &ToolUseContext, ) -> OpenBitFunResult> { + ModelOverridePolicy::enforce(input).await?; AgentExecutionTool::new() .call_task_impl(input, context) .await diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/mod.rs b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/mod.rs index 07d3c1a6ad..452e28d20d 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/mod.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/mod.rs @@ -47,6 +47,10 @@ mod execution; mod input; mod launch_review_agent; mod legacy_task; +mod model_policy; +pub(crate) use model_policy::with_collaboration_model_policy; + +use model_policy::{model_override_validation, ModelOverridePolicy}; mod schema; mod validation; @@ -155,7 +159,7 @@ impl Tool for AgentExecutionTool { } async fn description(&self) -> OpenBitFunResult { - Ok(self.render_description()) + Ok(self.render_description(ModelOverridePolicy::presentation().await?.allowed)) } async fn is_available_in_context(&self, _context: Option<&ToolUseContext>) -> bool { @@ -175,18 +179,22 @@ impl Tool for AgentExecutionTool { &self, _context: Option<&ToolUseContext>, ) -> OpenBitFunResult { - Ok(self.render_description()) + Ok(self.render_description(ModelOverridePolicy::presentation().await?.allowed)) } fn input_schema(&self) -> Value { Self::regular_input_schema() } + async fn input_schema_for_model(&self) -> Value { + ModelOverridePolicy::model_schema(self.input_schema()).await + } + async fn input_schema_for_model_with_context( &self, _context: Option<&ToolUseContext>, ) -> Value { - Self::regular_input_schema() + self.input_schema_for_model().await } fn is_readonly(&self) -> bool { @@ -251,6 +259,9 @@ impl Tool for AgentExecutionTool { input: &Value, context: Option<&ToolUseContext>, ) -> ValidationResult { + if let Some(validation) = model_override_validation(input).await { + return validation; + } Self::validate_invocation_input( input, false, @@ -296,6 +307,7 @@ impl Tool for AgentExecutionTool { input: &Value, context: &ToolUseContext, ) -> OpenBitFunResult> { + ModelOverridePolicy::enforce(input).await?; self.call_task_impl(input, context).await } } diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/model_policy.rs b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/model_policy.rs new file mode 100644 index 0000000000..c6b2492890 --- /dev/null +++ b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/model_policy.rs @@ -0,0 +1,105 @@ +use super::*; + +const DISABLED_MESSAGE: &str = "Subagent model overrides are disabled by the user. Remove model_id and retry to use the configured subagent model."; + +/// Execution-host policy. Workspace and controller-provided context cannot override it. +#[derive(Clone, Copy)] +pub(super) struct ModelOverridePolicy { + pub(super) allowed: bool, +} + +impl ModelOverridePolicy { + pub(super) async fn presentation() -> OpenBitFunResult { + match MODEL_PRESENTATION_POLICY.try_with(|policy| *policy) { + Ok(policy) => Ok(policy), + Err(_) => Self::load().await, + } + } + + pub(super) async fn load() -> OpenBitFunResult { + #[cfg(test)] + { + if let Ok(allowed) = TEST_MODEL_OVERRIDE.try_with(|allowed| *allowed) { + return Ok(Self { allowed }); + } + if !GlobalConfigManager::is_initialized() { + return Ok(Self { allowed: true }); + } + } + let service = GlobalConfigManager::get_service().await?; + let allowed = service + .get_config(Some("ai.allow_subagent_model_override")) + .await?; + Ok(Self { allowed }) + } + + pub(super) fn schema(self, mut schema: Value) -> Value { + if !self.allowed { + if let Some(properties) = schema.get_mut("properties").and_then(Value::as_object_mut) { + properties.remove("model_id"); + } + } + schema + } + + pub(super) async fn model_schema(schema: Value) -> Value { + let policy = Self::presentation().await.unwrap_or_else(|error| { + warn!("Failed to read subagent model override policy: {}", error); + Self { allowed: false } + }); + policy.schema(schema) + } + + pub(super) fn check(self, input: &Value) -> OpenBitFunResult<()> { + if !self.allowed && input.get("model_id").is_some() { + return Err(OpenBitFunError::validation(DISABLED_MESSAGE.to_string())); + } + Ok(()) + } + + /// Check original arguments before translation can drop null/empty fields. + pub(super) async fn enforce(input: &Value) -> OpenBitFunResult<()> { + if input.get("model_id").is_some() { + Self::load().await?.check(input)?; + } + Ok(()) + } +} + +tokio::task_local! { + static MODEL_PRESENTATION_POLICY: ModelOverridePolicy; +} + +/// Freeze only tool presentation during one catalog request. Execution always +/// re-reads the host policy so an already-issued tool call cannot bypass an opt-out. +pub(crate) async fn with_collaboration_model_policy( + future: F, +) -> F::Output { + if MODEL_PRESENTATION_POLICY.try_with(|_| ()).is_ok() { + return future.await; + } + let policy = ModelOverridePolicy::load().await.unwrap_or_else(|error| { + warn!( + "Failed to read collaboration presentation policy: {}", + error + ); + ModelOverridePolicy { allowed: false } + }); + crate::agentic::tools::registry::get_global_tool_registry() + .write() + .await + .refresh_collaboration_model_policy(policy.allowed); + MODEL_PRESENTATION_POLICY.scope(policy, future).await +} + +pub(super) async fn model_override_validation(input: &Value) -> Option { + ModelOverridePolicy::enforce(input) + .await + .err() + .map(|error| AgentExecutionTool::invalid_input(error.to_string())) +} + +#[cfg(test)] +tokio::task_local! { + pub(super) static TEST_MODEL_OVERRIDE: bool; +} diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/schema.rs b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/schema.rs index 1a35c3cfbe..6b2f532303 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/schema.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/schema.rs @@ -74,8 +74,35 @@ impl AgentExecutionTool { }) } - pub(super) fn render_description(&self) -> String { - r#"Run or manage a subagent that handles complex, multi-step tasks autonomously. + pub(super) fn render_description(&self, allow_model_override: bool) -> String { + let send_model_hint = if allow_model_override { + r#" Optionally provide `model_id` to switch the subagent model for this and later turns."# + } else { + r#""# + }; + let prompt_model_field = if allow_model_override { + r#", or `model_id`"# + } else { + r#""# + }; + let model_guidance = if allow_model_override { + r#"`model_id` usage: +- Set it only when the user requests a particular model. +- Omit it to use the subagent's configured model, which may differ from your model. +- Special values: `inherit` explicitly uses the same model as yours; `primary` and `fast` use the user's configured model slots. +- For a configured model, call ListModels first and use its returned `model_id`. + +"# + } else { + r#""# + }; + let continue_example = if allow_model_override { + r#"- Continue an existing subagent with a specific model: `{ "action": "send_input", "agent_id": "parser-review", "model_id": "fast", "prompt": "Continue from your prior parser review and focus on the error recovery paths." }`"# + } else { + r#"- Continue an existing subagent: `{ "action": "send_input", "agent_id": "parser-review", "prompt": "Continue from your prior parser review and focus on the error recovery paths." }`"# + }; + format!( + r#"Run or manage a subagent that handles complex, multi-step tasks autonomously. When to use: - Delegate when a specialized subagent or separate context is likely to improve coverage, independence, or parallelism. @@ -83,7 +110,7 @@ When to use: Supported actions: - `spawn`: create and run a new subagent. Choose a meaningful unique `agent_id`. -- `send_input`: continue an existing subagent. Provide its `agent_id` and a `prompt`. Optionally provide `model_id` to switch the subagent model for this and later turns. +- `send_input`: continue an existing subagent. Provide its `agent_id` and a `prompt`.{send_model_hint} - `cancel`: cancel a background subagent. Provide `agent_id`. Two modes for action='spawn': @@ -97,7 +124,7 @@ The two modes are mutually exclusive: do not provide `subagent_type` when `fork_ - In this mode, the subagent inherits the full conversation history up to this point — all prior user messages, assistant responses, and tool results. You do not need to repeat information already covered in the conversation. `prompt` writing guidelines: -- Do not put `action`, `subagent_type`, `agent_id`, or `model_id` inside the prompt string. +- Do not put `action`, `subagent_type`, `agent_id`{prompt_model_field} inside the prompt string. - Keep it under 180 lines / 16KB. For large delegations, split the work into multiple AgentSpawn calls with clear ownership. - Pass file paths, symbols, constraints, and exact questions instead of pasting large file contents. - Clearly tell the agent whether you expect code changes or research only (searches, file reads, web fetches, etc.), because it does not know the user's intent unless you state it. @@ -106,13 +133,7 @@ The two modes are mutually exclusive: do not provide `subagent_type` when `fork_ - false: Wait for the agent to finish and return its result to you. - true: Run the agent in the background without blocking you. The response includes a `bg_task_id`; use AgentWait when you need the results. -`model_id` usage: -- Set it only when the user requests a particular model. -- Omit it to use the subagent's configured model, which may differ from your model. -- Special values: `inherit` explicitly uses the same model as yours; `primary` and `fast` use the user's configured model slots. -- For a configured model, call ListModels first and use its returned `model_id`. - -Usage notes: +{model_guidance}Usage notes: - Provide a clear prompt for `spawn` and `send_input` so the agent can work autonomously and return the information you need. - The subagent inherits your workspace. If the subagent should inspect or operate on a path outside the current workspace, say that target path and scope clearly in the prompt. - Launch independent agents concurrently when that improves coverage or latency or when the user explicitly requests it. To do this, send parallel AgentSpawn calls in a single assistant message. @@ -122,13 +143,13 @@ Usage notes: Examples (assume "example-reviewer" is present in the agent listing): -- Start a new specialized subagent: `{ "action": "spawn", "agent_id": "parser-review", "subagent_type": "example-reviewer", "prompt": "Inspect the parser flow in src/parser.rs and report risks, key functions, and any missing tests." }` -- Start by forking the current context: `{ "action": "spawn", "agent_id": "migration-impact", "fork_context": true, "prompt": "Using the current context, check whether the migration affects config loading. Stay read-only and report the answer with file references." }` -- Continue an existing subagent with a specific model: `{ "action": "send_input", "agent_id": "parser-review", "model_id": "fast", "prompt": "Continue from your prior parser review and focus on the error recovery paths." }` -- Cancel a background subagent: `{ "action": "cancel", "agent_id": "parser-review" }` +- Start a new specialized subagent: `{{ "action": "spawn", "agent_id": "parser-review", "subagent_type": "example-reviewer", "prompt": "Inspect the parser flow in src/parser.rs and report risks, key functions, and any missing tests." }}` +- Start by forking the current context: `{{ "action": "spawn", "agent_id": "migration-impact", "fork_context": true, "prompt": "Using the current context, check whether the migration affects config loading. Stay read-only and report the answer with file references." }}` +{continue_example} +- Cancel a background subagent: `{{ "action": "cancel", "agent_id": "parser-review" }}` "# - .to_string() + ) } } @@ -159,12 +180,20 @@ impl AgentSpawnTool { }) } - pub(super) fn render_agent_spawn_description(&self) -> String { - r#"Launch a new agent to work independently in the background. + pub(super) fn render_agent_spawn_description(&self, allow_model_override: bool) -> String { + let model_guidance = if allow_model_override { + r#"Set `model_id` only when the user explicitly requests a particular model. Omit it to use the agent's configured model. `inherit` selects the current model; `primary` and `fast` select the corresponding configured model slots. Call ListModels before using a configured model ID. + +"# + } else { + r#""# + }; + format!( + r#"Launch a new agent to work independently in the background. Choose an `agent_type` permitted by the current system prompt. Pass the exact `type` value from the catalog. Each type has its own role and tool set. -Choose a meaningful `agent_id` for this agent. It must be unique among agents launched by you and match `[a-z][a-z0-9_-]{0,31}`. +Choose a meaningful `agent_id` for this agent. It must be unique among agents launched by you and match `[a-z][a-z0-9_-]{{0,31}}`. Write a self-contained `prompt` that gives the agent everything it needs to complete the work: - State the objective, scope, relevant paths or symbols, constraints, and expected result. @@ -176,12 +205,10 @@ The agent shares your workspace. If the task targets a different workspace, expl The agent starts with a fresh conversation, and does not inherit your conversation history. -Set `model_id` only when a particular model is required. Omit it to use the agent's configured model. `inherit` selects the current model; `primary` and `fast` select the corresponding configured model slots. Call ListModels before using a configured model ID. - -Independent agents can be launched together when that improves coverage or latency. Give agents that may write files non-overlapping scopes so their edits and side effects do not conflict. +{model_guidance}Independent agents can be launched together when that improves coverage or latency. Give agents that may write files non-overlapping scopes so their edits and side effects do not conflict. The result includes a `bg_task_id`. Use `bg_task_id` with AgentWait to collect the result. For agents that support follow-up turns, use the requested `agent_id` with AgentSendInput; use AgentControl with `action="interrupt"` to stop active work or `action="delete"` to remove an agent subtree."# - .to_string() + ) } } diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/tests.rs b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/tests.rs index 0d043be57d..d330b3c98c 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/tests.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/tests.rs @@ -2309,3 +2309,221 @@ fn deep_review_retry_scope_prompt_prepend_bounds_review_files() { assert!(prompt.contains("- src/crates/assembly/core/src/token.rs")); assert!(prompt.ends_with("Continue the security review.")); } + +fn collaboration_model_policy_tools() -> Vec> { + vec![ + Box::new(AgentSpawnTool::new()), + Box::new(AgentSendInputTool::new()), + Box::new(TaskTool::new()), + Box::new(LaunchReviewAgentTool::new()), + Box::new(AgentExecutionTool::new()), + ] +} + +#[tokio::test] +async fn subagent_model_override_policy_refreshes_all_model_facing_contracts() { + use super::model_policy::TEST_MODEL_OVERRIDE; + let context = test_tool_context("GeneralPurpose"); + let tools = collaboration_model_policy_tools(); + for allowed in [true, false, true] { + TEST_MODEL_OVERRIDE + .scope(allowed, async { + for tool in &tools { + let schema = tool.input_schema_for_model().await; + assert_eq!( + schema["properties"].get("model_id").is_some(), + allowed, + "{}", + tool.name() + ); + assert_eq!(schema["additionalProperties"], false); + assert_eq!( + tool.input_schema_for_model_with_context(Some(&context)) + .await, + schema + ); + let description = tool.description().await.unwrap(); + let contextual = tool.description_with_context(Some(&context)).await.unwrap(); + if !allowed { + assert!(!description.contains("model_id"), "{}", tool.name()); + assert!(!description.contains("ListModels"), "{}", tool.name()); + assert!(!contextual.contains("model_id"), "{}", tool.name()); + } + // Desktop/CLI catalog projection uses the same runtime definitions. + let expected_schema = schema; + assert_eq!(tool.input_schema_for_model().await, expected_schema); + } + }) + .await; + } +} + +#[tokio::test] +async fn subagent_model_override_policy_rejects_raw_arguments_before_side_effects() { + use super::model_policy::TEST_MODEL_OVERRIDE; + let mut context = test_tool_context("GeneralPurpose"); + // Controller/context data cannot relax execution-host policy. + context + .custom_data + .insert("allow_subagent_model_override".into(), json!(true)); + TEST_MODEL_OVERRIDE.scope(false, async { + for tool in collaboration_model_policy_tools() { + for model in [json!("inherit"), json!("primary"), json!("fast"), json!("custom"), json!(""), serde_json::Value::Null] { + let input = json!({"model_id": model}); + let validation = tool.validate_input(&input, Some(&context)).await; + assert!(!validation.result, "{}", tool.name()); + assert!(validation.message.unwrap().contains("Remove model_id")); + let error = tool.call_impl(&input, &context).await.unwrap_err(); + assert!(error.to_string().contains("Remove model_id"), "{}: {}", tool.name(), error); + } + } + let spawn = json!({"agent_id":"worker", "agent_type":"GeneralPurpose", "prompt":"Inspect the parser"}); + assert!(AgentSpawnTool::new().validate_input(&spawn, Some(&context)).await.result); + let followup = json!({"agent_id":"worker", "prompt":"Continue"}); + assert!(AgentSendInputTool::new().validate_input(&followup, Some(&context)).await.result); + let parsed = AgentSpawnTool::task_input(&spawn).unwrap(); + assert!(parsed.get("model_id").is_none()); + assert!(AgentSendInputTool::task_input(&followup).unwrap().get("model_id").is_none()); + }).await; +} + +#[tokio::test] +async fn subagent_model_override_presentation_snapshot_does_not_freeze_execution_policy() { + use super::model_policy::{ModelOverridePolicy, TEST_MODEL_OVERRIDE}; + TEST_MODEL_OVERRIDE + .scope( + true, + super::with_collaboration_model_policy(async { + TEST_MODEL_OVERRIDE + .scope(false, async { + assert!( + AgentSpawnTool::new().input_schema_for_model().await["properties"] + .get("model_id") + .is_some() + ); + assert!(ModelOverridePolicy::enforce(&json!({"model_id":"fast"})) + .await + .is_err()); + }) + .await; + }), + ) + .await; +} + +#[test] +fn subagent_model_override_policy_invalidates_loaded_specs_only_when_changed() { + let mut registry = crate::agentic::tools::registry::create_tool_registry(); + let names = registry.get_tool_names(); + let initial = registry.current_snapshot_generation(); + registry.refresh_collaboration_model_policy(true); + assert_eq!(registry.current_snapshot_generation(), initial); + registry.refresh_collaboration_model_policy(false); + assert!(registry.current_snapshot_generation() > initial); + let disabled = registry.current_snapshot_generation(); + registry.refresh_collaboration_model_policy(false); + assert_eq!(registry.current_snapshot_generation(), disabled); + registry.refresh_collaboration_model_policy(true); + assert!(registry.current_snapshot_generation() > disabled); + assert_eq!(registry.get_tool_names(), names); +} + +#[tokio::test] +async fn subagent_model_override_uses_host_policy_for_remote_and_headless_contexts() { + use super::model_policy::TEST_MODEL_OVERRIDE; + let mut context = test_tool_context("GeneralPurpose"); + context.workspace = Some(WorkspaceBinding::new_remote( + None, + PathBuf::from("/workspace/project"), + "connection-1".to_string(), + "remote".to_string(), + WorkspaceSessionIdentity { + workspace_kind: openbitfun_core_types::WorkspaceKind::Remote, + hostname: "remote.example".to_string(), + logical_workspace_path: "/workspace/project".to_string(), + remote_connection_id: Some("connection-1".to_string()), + }, + )); + context + .custom_data + .insert("peer_device_control".into(), json!(true)); + context + .custom_data + .insert("user_input_available".into(), json!(false)); + TEST_MODEL_OVERRIDE + .scope(false, async { + for tool in collaboration_model_policy_tools() { + let schema = tool + .input_schema_for_model_with_context(Some(&context)) + .await; + assert!(schema["properties"].get("model_id").is_none()); + let error = tool + .call_impl(&json!({"model_id":"primary"}), &context) + .await + .unwrap_err(); + assert!(error.to_string().contains("Remove model_id")); + } + }) + .await; +} + +#[tokio::test] +async fn subagent_model_override_policy_reaches_native_and_host_catalogs() { + use super::model_policy::TEST_MODEL_OVERRIDE; + use crate::agentic::tools::product_runtime::{ + build_tool_info, resolve_product_resolved_tool_manifest, + }; + let context = test_tool_context("GeneralPurpose"); + TEST_MODEL_OVERRIDE + .scope(false, async { + let tool: Arc = Arc::new(AgentSpawnTool::new()); + let info = build_tool_info(&tool).await; + assert!(info.input_schema["properties"].get("model_id").is_none()); + assert!(!info.description.contains("model_id")); + let manifest = resolve_product_resolved_tool_manifest( + &["AgentSpawn".into(), "AgentSendInput".into()], + &Default::default(), + &context, + ) + .await; + for name in ["AgentSpawn", "AgentSendInput"] { + let definition = manifest + .tool_definitions + .iter() + .find(|tool| tool.name == name) + .unwrap(); + assert!(definition.parameters["properties"] + .get("model_id") + .is_none()); + assert!(!definition.description.contains("model_id")); + } + }) + .await; +} + +#[cfg(feature = "ptc-runtime")] +#[tokio::test] +async fn subagent_model_override_policy_reaches_ptc_bindings() { + use super::model_policy::TEST_MODEL_OVERRIDE; + use crate::agentic::tools::product_runtime::resolve_product_resolved_tool_manifest; + let mut context = test_tool_context("GeneralPurpose"); + context.custom_data.insert( + openbitfun_agent_tools::PTC_TOOL_PRESENTATION_CONTEXT_KEY.into(), + json!("ptc"), + ); + for allowed in [false, true] { + TEST_MODEL_OVERRIDE + .scope(allowed, async { + let manifest = resolve_product_resolved_tool_manifest( + &["AgentSpawn".into(), "AgentSendInput".into()], + &Default::default(), + &context, + ) + .await; + let guide = manifest.ptc_tool_calling_guide.unwrap(); + assert!(guide.contains("AgentSpawn")); + assert_eq!(guide.contains("model_id"), allowed); + }) + .await; + } +} diff --git a/src/crates/assembly/core/src/agentic/tools/product_runtime/catalog.rs b/src/crates/assembly/core/src/agentic/tools/product_runtime/catalog.rs index c9a9ee24f7..c5be1992ae 100644 --- a/src/crates/assembly/core/src/agentic/tools/product_runtime/catalog.rs +++ b/src/crates/assembly/core/src/agentic/tools/product_runtime/catalog.rs @@ -2,6 +2,7 @@ use crate::agentic::agents::{get_agent_registry, AgentToolPolicyOverrides}; use crate::agentic::tools::framework::{Tool, ToolExposure, ToolResult}; +use crate::agentic::tools::implementations::agent_collaboration::with_collaboration_model_policy; use crate::agentic::tools::registry::{get_global_tool_registry, ToolRef}; use crate::agentic::tools::tool_context_runtime::ToolUseContext; use crate::util::errors::{OpenBitFunError, OpenBitFunResult}; @@ -57,19 +58,22 @@ pub struct ToolInfoDto { /// same `dynamic_tool_info`. Desktop now delegates here; CLI reuses the same /// path so the two hosts never drift. pub async fn build_tool_info(tool: &Arc) -> ToolInfoDto { - let description = tool - .description() - .await - .unwrap_or_else(|_| "No description available".to_string()); - ToolInfoDto { - name: tool.name().to_string(), - description, - input_schema: tool.input_schema_for_model().await, - output_schema: tool.output_schema(), - is_readonly: tool.is_readonly(), - is_concurrency_safe: tool.is_concurrency_safe(None), - dynamic_info: tool.dynamic_tool_info(), - } + with_collaboration_model_policy(async { + let description = tool + .description() + .await + .unwrap_or_else(|_| "No description available".to_string()); + ToolInfoDto { + name: tool.name().to_string(), + description, + input_schema: tool.input_schema_for_model().await, + output_schema: tool.output_schema(), + is_readonly: tool.is_readonly(), + is_concurrency_safe: tool.is_concurrency_safe(None), + dynamic_info: tool.dynamic_tool_info(), + } + }) + .await } /// Build the catalog DTO for every tool in the global registry, in registry @@ -339,46 +343,49 @@ pub(crate) async fn resolve_product_tool_manifest( exposure_overrides: &AgentToolPolicyOverrides, context: &ToolUseContext, ) -> ContextualToolManifest { - let (mut allowed_tools, exposure_overrides) = - ProductToolCatalogProvider::resolve_manifest_inputs( - allowed_tools, - exposure_overrides, + with_collaboration_model_policy(async { + let (mut allowed_tools, exposure_overrides) = + ProductToolCatalogProvider::resolve_manifest_inputs( + allowed_tools, + exposure_overrides, + context, + ); + let tool_snapshot = contextual_tool_snapshot(context).await; + append_selected_plugin_tool_names(&mut allowed_tools, &tool_snapshot, context).await; + let mut manifest = resolve_contextual_tool_manifest( + &tool_snapshot, + &allowed_tools, + &exposure_overrides, context, - ); - let tool_snapshot = contextual_tool_snapshot(context).await; - append_selected_plugin_tool_names(&mut allowed_tools, &tool_snapshot, context).await; - let mut manifest = resolve_contextual_tool_manifest( - &tool_snapshot, - &allowed_tools, - &exposure_overrides, - context, - GET_TOOL_SPEC_TOOL_NAME, - ) - .await; + GET_TOOL_SPEC_TOOL_NAME, + ) + .await; - #[cfg(feature = "ptc-runtime")] - if context_is_ptc_mode(context) { - // PTC keeps deferred tools out of the initial full schema. Their - // generated SDK is attached to the prompt reminder by the resolved - // manifest facade below. - let language = ptc_language(context); - manifest.tool_definitions = vec![ToolManifestDefinition::new( - PTC_RUN_CODE_TOOL_NAME, - ptc_run_code_description_for_language(language), - ptc_run_code_input_schema_for_language(language), - )]; - if !manifest - .allowed_tool_names - .iter() - .any(|name| name == PTC_RUN_CODE_TOOL_NAME) - { - manifest + #[cfg(feature = "ptc-runtime")] + if context_is_ptc_mode(context) { + // PTC keeps deferred tools out of the initial full schema. Their + // generated SDK is attached to the prompt reminder by the resolved + // manifest facade below. + let language = ptc_language(context); + manifest.tool_definitions = vec![ToolManifestDefinition::new( + PTC_RUN_CODE_TOOL_NAME, + ptc_run_code_description_for_language(language), + ptc_run_code_input_schema_for_language(language), + )]; + if !manifest .allowed_tool_names - .push(PTC_RUN_CODE_TOOL_NAME.to_string()); + .iter() + .any(|name| name == PTC_RUN_CODE_TOOL_NAME) + { + manifest + .allowed_tool_names + .push(PTC_RUN_CODE_TOOL_NAME.to_string()); + } } - } - manifest + manifest + }) + .await } #[cfg(feature = "ptc-runtime")] @@ -555,48 +562,51 @@ pub(crate) async fn resolve_product_resolved_tool_manifest( exposure_overrides: &AgentToolPolicyOverrides, context: &ToolUseContext, ) -> ResolvedToolManifest { - let contextual_manifest = - resolve_product_tool_manifest(allowed_tools, exposure_overrides, context).await; - #[cfg(feature = "ptc-runtime")] - let ptc_tool_calling_guide = if context_is_ptc_mode(context) { - let include_deferred_tool_apis = - ProductToolCatalogProvider::deferred_tool_loading_enabled(context) - && !contextual_manifest.deferred_tool_names.is_empty(); - let mut ptc_tools = contextual_manifest.direct_tools.clone(); - for tool in &contextual_manifest.deferred_tools { - if !ptc_tools - .iter() - .any(|existing| existing.name() == tool.name()) - { - ptc_tools.push(tool.clone()); + with_collaboration_model_policy(async { + let contextual_manifest = + resolve_product_tool_manifest(allowed_tools, exposure_overrides, context).await; + #[cfg(feature = "ptc-runtime")] + let ptc_tool_calling_guide = if context_is_ptc_mode(context) { + let include_deferred_tool_apis = + ProductToolCatalogProvider::deferred_tool_loading_enabled(context) + && !contextual_manifest.deferred_tool_names.is_empty(); + let mut ptc_tools = contextual_manifest.direct_tools.clone(); + for tool in &contextual_manifest.deferred_tools { + if !ptc_tools + .iter() + .any(|existing| existing.name() == tool.name()) + { + ptc_tools.push(tool.clone()); + } } - } - let contracts = build_ptc_contracts( - &ptc_tools, - &contextual_manifest.deferred_tool_names, - context, - ) - .await; - let language = ptc_language(context); - let sdk_source = - render_ptc_sdk_with_options(&contracts, language, include_deferred_tool_apis); - Some(render_ptc_tool_calling_guide_for_language( - &sdk_source, - language, - include_deferred_tool_apis, - )) - } else { - None - }; + let contracts = build_ptc_contracts( + &ptc_tools, + &contextual_manifest.deferred_tool_names, + context, + ) + .await; + let language = ptc_language(context); + let sdk_source = + render_ptc_sdk_with_options(&contracts, language, include_deferred_tool_apis); + Some(render_ptc_tool_calling_guide_for_language( + &sdk_source, + language, + include_deferred_tool_apis, + )) + } else { + None + }; - let mut manifest: ResolvedToolManifest = contextual_manifest.into(); - let provider = ProductToolCatalogProvider; - manifest.catalog_generation = provider.catalog_generation().await; - #[cfg(feature = "ptc-runtime")] - { - manifest.ptc_tool_calling_guide = ptc_tool_calling_guide; - } - manifest + let mut manifest: ResolvedToolManifest = contextual_manifest.into(); + let provider = ProductToolCatalogProvider; + manifest.catalog_generation = provider.catalog_generation().await; + #[cfg(feature = "ptc-runtime")] + { + manifest.ptc_tool_calling_guide = ptc_tool_calling_guide; + } + manifest + }) + .await } pub(crate) async fn resolve_product_readonly_enabled_tools() -> Vec { @@ -611,10 +621,13 @@ pub(crate) async fn resolve_product_get_tool_spec_results( context: &ToolUseContext, get_tool_spec_tool_name: &str, ) -> Result, GetToolSpecExecutionError> { - let provider = ProductToolCatalogProvider; - GetToolSpecRuntime::new(&provider, get_tool_spec_tool_name) - .call_results(input, &context.loaded_deferred_tool_specs, context) - .await + with_collaboration_model_policy(async { + let provider = ProductToolCatalogProvider; + GetToolSpecRuntime::new(&provider, get_tool_spec_tool_name) + .call_results(input, &context.loaded_deferred_tool_specs, context) + .await + }) + .await } #[cfg(test)] diff --git a/src/crates/assembly/core/src/agentic/tools/registry.rs b/src/crates/assembly/core/src/agentic/tools/registry.rs index e529d42081..b8a00f3b89 100644 --- a/src/crates/assembly/core/src/agentic/tools/registry.rs +++ b/src/crates/assembly/core/src/agentic/tools/registry.rs @@ -61,6 +61,7 @@ pub use openbitfun_agent_tools::GET_TOOL_SPEC_TOOL_NAME; /// Tool registry - manages all available tools (using IndexMap to maintain registration order) pub struct ToolRegistry { inner: AgentToolRegistry, + collaboration_model_override: bool, } impl Default for ToolRegistry { @@ -95,7 +96,10 @@ impl ToolRegistry { } pub(in crate::agentic::tools) fn from_inner(inner: AgentToolRegistry) -> Self { - Self { inner } + Self { + inner, + collaboration_model_override: true, + } } /// Dynamically register MCP tools @@ -245,6 +249,13 @@ impl ToolRegistry { self.inner.current_snapshot_generation() } + pub(crate) fn refresh_collaboration_model_policy(&mut self, allowed: bool) { + if self.collaboration_model_override != allowed { + self.collaboration_model_override = allowed; + self.inner.invalidate_tool_specs(); + } + } + /// Get all tool names pub fn get_tool_names(&self) -> Vec { self.inner.get_tool_names() diff --git a/src/crates/contracts/config-contracts/src/types.rs b/src/crates/contracts/config-contracts/src/types.rs index 6d4ebeb2ff..a232ee2a1d 100644 --- a/src/crates/contracts/config-contracts/src/types.rs +++ b/src/crates/contracts/config-contracts/src/types.rs @@ -1338,6 +1338,10 @@ pub struct AIConfig { #[serde(default = "default_review_team_rate_limit_status")] pub review_team_rate_limit_status: serde_json::Value, + /// Allow model-issued collaboration calls to override configured subagent models. + #[serde(default = "default_true")] + pub allow_subagent_model_override: bool, + /// Maximum number of subagents that may execute concurrently. #[serde(default = "default_subagent_max_concurrency")] pub subagent_max_concurrency: usize, @@ -2367,6 +2371,7 @@ impl Default for AIConfig { skill_settings: SkillSettingsConfig::default(), review_teams: default_review_team_configs(), review_team_rate_limit_status: default_review_team_rate_limit_status(), + allow_subagent_model_override: true, subagent_max_concurrency: default_subagent_max_concurrency(), swarm_max_concurrency: default_swarm_max_concurrency(), subagent_batch_execution_policy: default_subagent_batch_execution_policy(), @@ -5067,3 +5072,39 @@ mod media_config_tests { assert!(media.effective_image_service().is_none()); } } + +#[cfg(test)] +mod subagent_model_override_tests { + use super::AIConfig; + use serde_json::json; + + #[test] + fn legacy_ai_payload_defaults_to_allowed_and_round_trips() { + let legacy = json!({"subagent_max_concurrency": 3, "max_rounds": 12}); + let config: AIConfig = serde_json::from_value(legacy).unwrap(); + assert!(config.allow_subagent_model_override); + assert!(AIConfig::default().allow_subagent_model_override); + let restored: AIConfig = + serde_json::from_value(serde_json::to_value(config).unwrap()).unwrap(); + assert!(restored.allow_subagent_model_override); + assert_eq!(restored.subagent_max_concurrency, 3); + assert_eq!(restored.max_rounds, 12); + } + + #[test] + fn explicit_opt_out_survives_serialization() { + let config: AIConfig = serde_json::from_value(json!({ + "allow_subagent_model_override": false, + "agent_model_defaults": {"subagents": {"default": {"kind": "fixed", "model_id": "fast"}}} + })).unwrap(); + assert!(!config.allow_subagent_model_override); + let encoded = serde_json::to_value(&config).unwrap(); + assert_eq!(encoded["allow_subagent_model_override"], false); + let restored: AIConfig = serde_json::from_value(encoded).unwrap(); + assert!(!restored.allow_subagent_model_override); + assert_eq!( + serde_json::to_value(restored.agent_model_defaults).unwrap(), + serde_json::to_value(config.agent_model_defaults).unwrap() + ); + } +} diff --git a/src/crates/contracts/product-domains/src/generated/product-control-catalog.json b/src/crates/contracts/product-domains/src/generated/product-control-catalog.json index 7b6a4ed90f..80c8e3332d 100644 --- a/src/crates/contracts/product-domains/src/generated/product-control-catalog.json +++ b/src/crates/contracts/product-domains/src/generated/product-control-catalog.json @@ -4,8 +4,8 @@ "title": "OpenBitFun Playbook", "origin": "https://playbook.openbitfun.com", "source": "src/shared/interactive-capabilities/catalog.json", - "digest": "4b8a786017df37df61ff4c749771e0af19c851b6be51ed46504425c9bdf992bd", - "ownerDigest": "31d6371f7765bde7bee88e22a6a4f03c2c5370e138cf49975bdc88f3c5eeb052", + "digest": "fe4be08cb20c2d67857891380d223a77d420345b94e2733d0000d14485027697", + "ownerDigest": "1fdb9c49d404c02483c08e1e0fe9effa0aaa4f0f2914578bcaa63e04de16cc16", "searchAcceptance": [ { "id": "native-office-generation", @@ -187,9 +187,9 @@ "features": 24, "settings": 23, "userFacing": 47, - "documentedItems": 368, + "documentedItems": 369, "controlCoverage": { - "direct": 63, + "direct": 64, "delegated": 74, "interactive": 231, "unsupported": 0 @@ -17809,7 +17809,8 @@ "computer-use", "computer-use-permissions", "browser-auto-connect", - "browser-setup" + "browser-setup", + "subagent-model-override" ], "kind": "query", "risk": "read", @@ -18355,6 +18356,50 @@ "pageId": "tools.execution" } }, + { + "id": "setting.tools.execution:option:subagent-model-override", + "capabilityId": "setting.tools.execution", + "itemIds": [ + "subagent-model-override" + ], + "kind": "option", + "risk": "write", + "executionHost": "productHost", + "availability": { + "desktop": { + "available": true + }, + "cli": { + "available": true + }, + "peer": { + "available": true, + "requiredCapabilities": [ + "product_control_v1" + ] + }, + "remoteControl": { + "available": true + }, + "detachedDispatch": { + "available": true + } + }, + "inputSchema": { + "type": "boolean" + }, + "outputSchema": { + "type": "object", + "additionalProperties": true + }, + "valueSource": { + "kind": "static" + }, + "presentationTarget": { + "kind": "settings", + "pageId": "tools.execution" + } + }, { "id": "setting.tools.execution:open:question-timeout", "capabilityId": "setting.tools.execution", @@ -33431,6 +33476,25 @@ "reasonZh": "可用浏览器和 CDP 状态来自当前机器且可能要求重启确认;智能体可打开配置入口,实际网页操作则使用统一的 ControlHub 浏览器契约。", "reasonEn": "Available browsers and CDP state come from the current machine and may require restart confirmation; the Agent can open setup, while page automation uses the shared ControlHub browser contract." } + }, + { + "id": "subagent-model-override", + "titleZh": "允许 Agent 指定子 Agent 模型", + "titleEn": "Allow agents to choose subagent models", + "destination": { + "kind": "settings", + "pageId": "tools.execution", + "viewId": "advanced" + }, + "control": { + "kind": "direct", + "operations": [], + "options": [ + { + "id": "subagent-model-override" + } + ] + } } ], "stepsZh": [ @@ -33634,6 +33698,20 @@ "kind": "config", "path": "ai.generative_ui_library" } + }, + { + "id": "subagent-model-override", + "titleZh": "允许 Agent 指定子 Agent 模型", + "titleEn": "Allow agents to choose subagent models", + "descriptionZh": "控制 Agent 能否在启动或继续执行子 Agent 时指定模型。", + "descriptionEn": "Control whether agents can override subagent models when launching or continuing work.", + "valueSchema": { + "type": "boolean" + }, + "handler": { + "kind": "config", + "path": "ai.allow_subagent_model_override" + } } ], "searchTerms": [ @@ -33710,6 +33788,8 @@ "Choose whether OpenBitFun automatically connects to your CDP browser on startup", "发现并选择外部浏览器、开启默认 CDP 配置或按需重启连接", "Discover and choose an external browser, enable default CDP, or reconnect on demand", + "允许 Agent 指定子 Agent 模型", + "Allow agents to choose subagent models", "开启按需加载工具帮我节省初始上下文", "把子智能体最大并发改为 8,任务并行方式设为安全并行", "单次工具调用超时改成 600 秒", diff --git a/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json b/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json index 4311a732aa..63db5cbc41 100644 --- a/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json +++ b/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json @@ -1,6 +1,6 @@ { "schemaVersion": 1, - "digest": "fnv1a64:8732d7ca210f7cf2", + "digest": "fnv1a64:67a20e107dd93ffd", "retiredCommandPrefixes": [ { "prefix": "lsp_", @@ -12,6 +12,7 @@ "gen_ui_libraries_v1", "model_routing_v1", "model_pool_selection_v1", + "subagent_model_override_policy_v1", "magpie_discovery_v1", "background_result_delivery_v1", "dialog_queue_v1", @@ -67,6 +68,7 @@ "gen_ui_libraries_v1", "model_routing_v1", "model_pool_selection_v1", + "subagent_model_override_policy_v1", "magpie_discovery_v1", "background_result_delivery_v1", "dialog_queue_v1", @@ -120,6 +122,7 @@ "cli": [ "model_routing_v1", "model_pool_selection_v1", + "subagent_model_override_policy_v1", "magpie_discovery_v1", "background_result_delivery_v1", "dialog_queue_v1", diff --git a/src/crates/contracts/product-domains/src/product_control_owner_registry.rs b/src/crates/contracts/product-domains/src/product_control_owner_registry.rs index 3bdb805f7a..c5dc5e855a 100644 --- a/src/crates/contracts/product-domains/src/product_control_owner_registry.rs +++ b/src/crates/contracts/product-domains/src/product_control_owner_registry.rs @@ -946,6 +946,12 @@ pub fn owner_definitions() -> Vec { string_enum(&["native", "ptc", "ptc_python"]), config("ai.tool_presentation_mode"), ), + option( + "setting.tools.execution", + "subagent-model-override", + boolean(), + config("ai.allow_subagent_model_override"), + ), option( "setting.tools.execution", "subagent-batch-policy", diff --git a/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs b/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs index 980052416c..e3840beedc 100644 --- a/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs +++ b/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs @@ -25,6 +25,7 @@ pub enum PeerHostCapability { GenUiLibrariesV1, ModelRoutingV1, ModelPoolSelectionV1, + SubagentModelOverridePolicyV1, MagpieDiscoveryV1, /// Versioned, execution-host-owned background report decisions are persisted and projected. BackgroundResultDeliveryV1, @@ -140,6 +141,7 @@ impl PeerHostCapability { Self::GenUiLibrariesV1, Self::ModelRoutingV1, Self::ModelPoolSelectionV1, + Self::SubagentModelOverridePolicyV1, Self::MagpieDiscoveryV1, Self::BackgroundResultDeliveryV1, Self::DialogQueueV1, @@ -198,6 +200,7 @@ impl PeerHostCapability { Self::GenUiLibrariesV1 => "gen_ui_libraries_v1", Self::ModelRoutingV1 => "model_routing_v1", Self::ModelPoolSelectionV1 => "model_pool_selection_v1", + Self::SubagentModelOverridePolicyV1 => "subagent_model_override_policy_v1", Self::MagpieDiscoveryV1 => "magpie_discovery_v1", Self::BackgroundResultDeliveryV1 => "background_result_delivery_v1", Self::DialogQueueV1 => "dialog_queue_v1", @@ -263,6 +266,7 @@ const DESKTOP_CAPABILITIES: &[PeerHostCapability] = &[ PeerHostCapability::GenUiLibrariesV1, PeerHostCapability::ModelRoutingV1, PeerHostCapability::ModelPoolSelectionV1, + PeerHostCapability::SubagentModelOverridePolicyV1, PeerHostCapability::MagpieDiscoveryV1, PeerHostCapability::BackgroundResultDeliveryV1, PeerHostCapability::DialogQueueV1, @@ -319,6 +323,7 @@ const DESKTOP_CAPABILITIES: &[PeerHostCapability] = &[ const CLI_CAPABILITIES: &[PeerHostCapability] = &[ PeerHostCapability::ModelRoutingV1, PeerHostCapability::ModelPoolSelectionV1, + PeerHostCapability::SubagentModelOverridePolicyV1, PeerHostCapability::MagpieDiscoveryV1, PeerHostCapability::BackgroundResultDeliveryV1, PeerHostCapability::DialogQueueV1, diff --git a/src/crates/execution/tool-contracts/src/framework.rs b/src/crates/execution/tool-contracts/src/framework.rs index a9fa01d294..006314138a 100644 --- a/src/crates/execution/tool-contracts/src/framework.rs +++ b/src/crates/execution/tool-contracts/src/framework.rs @@ -1613,6 +1613,12 @@ impl ToolRegistry { self.snapshot_generation } + /// Invalidate loaded specifications after an owner changes tool presentation + /// without replacing tool instances or their provider registrations. + pub fn invalidate_tool_specs(&mut self) { + self.snapshot_generation = self.snapshot_generation.saturating_add(1); + } + pub async fn materialized_tool_snapshot(&self) -> Result { materialize_tool_snapshot( &self.get_all_tools(), diff --git a/src/shared/interactive-capabilities/catalog.json b/src/shared/interactive-capabilities/catalog.json index a26e752fb7..5155d8ad0b 100644 --- a/src/shared/interactive-capabilities/catalog.json +++ b/src/shared/interactive-capabilities/catalog.json @@ -11214,6 +11214,28 @@ "command:browser_control_list_browsers", "command:browser_control_enable_default_cdp" ] + }, + { + "id": "subagent-model-override", + "titleZh": "允许 Agent 指定子 Agent 模型", + "titleEn": "Allow agents to choose subagent models", + "destination": { + "kind": "settings", + "pageId": "tools.execution", + "viewId": "advanced" + }, + "control": { + "kind": "direct", + "operations": [], + "options": [ + { + "id": "subagent-model-override" + } + ] + }, + "evidence": [ + "source:src/web-ui/src/locales/zh-CN/settings/agentic-tools.json#config.subagentModelOverride.label" + ] } ], "stepsZh": [ @@ -11337,6 +11359,13 @@ "titleEn": "Default GenUI component library", "descriptionZh": "指定新建交互式 GenUI 应用默认采用的组件库与设计规范(默认 openui);已有应用保留原有目标身份。", "descriptionEn": "Select the component library and bound design spec for newly generated GenUI apps (openui by default); existing apps keep their original target." + }, + { + "id": "subagent-model-override", + "titleZh": "允许 Agent 指定子 Agent 模型", + "titleEn": "Allow agents to choose subagent models", + "descriptionZh": "控制 Agent 能否在启动或继续执行子 Agent 时指定模型。", + "descriptionEn": "Control whether agents can override subagent models when launching or continuing work." } ] }, diff --git a/src/web-ui/README.md b/src/web-ui/README.md index 3162e5de14..b43f90b286 100644 --- a/src/web-ui/README.md +++ b/src/web-ui/README.md @@ -602,3 +602,21 @@ partial view of available events. Peer detail bodies remain owned by the canonic record replica. This observer UI adds no runtime or filesystem dependency for Remote Control or Detached Dispatch jobs. Automated fixtures simulate these routing and device-switch contracts; live remote and native visual checks remain manual. + +### Subagent model selection policy + +In **Settings → Execution → Subagents**, **Allow agents to choose subagent models** +controls `ai.allow_subagent_model_override` on the executing host. It defaults to +`true`, including when loading older configurations. When disabled, AgentSpawn, +AgentSendInput, legacy Task and LaunchReviewAgent omit `model_id` from model-facing +schemas and related instructions. Calls that still supply the field fail before +launching or switching a subagent; remove the argument to use configured models. +Configured defaults, model pools, Agent-specific models and backend-owned Review +model preferences remain effective. Existing running agents keep their models. + +The next tool catalog reflects a setting change, including deferred tool specs +and PTC bindings; execution rechecks the current host setting. SSH workspaces, +mobile/IM controllers and detached jobs use the execution host's policy. In Peer +Device Mode, the setting belongs to the peer; hosts must advertise +`subagent_model_override_policy_v1`. Older hosts show an unsupported setting rather +than saving a value they cannot enforce. diff --git a/src/web-ui/src/app/global-search/generated/interactive-capabilities.json b/src/web-ui/src/app/global-search/generated/interactive-capabilities.json index 2d776ca6cb..c7394af2a4 100644 --- a/src/web-ui/src/app/global-search/generated/interactive-capabilities.json +++ b/src/web-ui/src/app/global-search/generated/interactive-capabilities.json @@ -4,8 +4,8 @@ "title": "OpenBitFun Playbook", "origin": "https://playbook.openbitfun.com", "source": "src/shared/interactive-capabilities/catalog.json", - "digest": "4b8a786017df37df61ff4c749771e0af19c851b6be51ed46504425c9bdf992bd", - "ownerDigest": "31d6371f7765bde7bee88e22a6a4f03c2c5370e138cf49975bdc88f3c5eeb052", + "digest": "fe4be08cb20c2d67857891380d223a77d420345b94e2733d0000d14485027697", + "ownerDigest": "1fdb9c49d404c02483c08e1e0fe9effa0aaa4f0f2914578bcaa63e04de16cc16", "searchAcceptance": [ { "id": "native-office-generation", @@ -187,9 +187,9 @@ "features": 24, "settings": 23, "userFacing": 47, - "documentedItems": 368, + "documentedItems": 369, "controlCoverage": { - "direct": 63, + "direct": 64, "delegated": 74, "interactive": 231, "unsupported": 0 @@ -17809,7 +17809,8 @@ "computer-use", "computer-use-permissions", "browser-auto-connect", - "browser-setup" + "browser-setup", + "subagent-model-override" ], "kind": "query", "risk": "read", @@ -18355,6 +18356,50 @@ "pageId": "tools.execution" } }, + { + "id": "setting.tools.execution:option:subagent-model-override", + "capabilityId": "setting.tools.execution", + "itemIds": [ + "subagent-model-override" + ], + "kind": "option", + "risk": "write", + "executionHost": "productHost", + "availability": { + "desktop": { + "available": true + }, + "cli": { + "available": true + }, + "peer": { + "available": true, + "requiredCapabilities": [ + "product_control_v1" + ] + }, + "remoteControl": { + "available": true + }, + "detachedDispatch": { + "available": true + } + }, + "inputSchema": { + "type": "boolean" + }, + "outputSchema": { + "type": "object", + "additionalProperties": true + }, + "valueSource": { + "kind": "static" + }, + "presentationTarget": { + "kind": "settings", + "pageId": "tools.execution" + } + }, { "id": "setting.tools.execution:open:question-timeout", "capabilityId": "setting.tools.execution", @@ -33024,6 +33069,25 @@ "reasonZh": "可用浏览器和 CDP 状态来自当前机器且可能要求重启确认;智能体可打开配置入口,实际网页操作则使用统一的 ControlHub 浏览器契约。", "reasonEn": "Available browsers and CDP state come from the current machine and may require restart confirmation; the Agent can open setup, while page automation uses the shared ControlHub browser contract." } + }, + { + "id": "subagent-model-override", + "titleZh": "允许 Agent 指定子 Agent 模型", + "titleEn": "Allow agents to choose subagent models", + "destination": { + "kind": "settings", + "pageId": "tools.execution", + "viewId": "advanced" + }, + "control": { + "kind": "direct", + "operations": [], + "options": [ + { + "id": "subagent-model-override" + } + ] + } } ], "stepsZh": [ @@ -33184,6 +33248,16 @@ "openui" ] } + }, + { + "id": "subagent-model-override", + "titleZh": "允许 Agent 指定子 Agent 模型", + "titleEn": "Allow agents to choose subagent models", + "descriptionZh": "控制 Agent 能否在启动或继续执行子 Agent 时指定模型。", + "descriptionEn": "Control whether agents can override subagent models when launching or continuing work.", + "valueSchema": { + "type": "boolean" + } } ], "searchTerms": [ @@ -33260,6 +33334,8 @@ "Choose whether OpenBitFun automatically connects to your CDP browser on startup", "发现并选择外部浏览器、开启默认 CDP 配置或按需重启连接", "Discover and choose an external browser, enable default CDP, or reconnect on demand", + "允许 Agent 指定子 Agent 模型", + "Allow agents to choose subagent models", "开启按需加载工具帮我节省初始上下文", "把子智能体最大并发改为 8,任务并行方式设为安全并行", "单次工具调用超时改成 600 秒", diff --git a/src/web-ui/src/app/scenes/settings/pages/ai/ExecutionSettingsPage.tsx b/src/web-ui/src/app/scenes/settings/pages/ai/ExecutionSettingsPage.tsx index a8d0f49d3e..77f953b6b8 100644 --- a/src/web-ui/src/app/scenes/settings/pages/ai/ExecutionSettingsPage.tsx +++ b/src/web-ui/src/app/scenes/settings/pages/ai/ExecutionSettingsPage.tsx @@ -1,3 +1,4 @@ +import SubagentModelOverrideSection from './SubagentModelOverrideSection'; import { filterSelectableTextChatModels } from '@/infrastructure/config/services/modelCategory'; import { getActiveSurfaceScope } from '@/infrastructure/peer-device/deviceSurface'; import { modelSelectionsConfigPath, effectiveModelSelections, readModelSelections } from '@/infrastructure/config/services/modelSelections'; @@ -512,6 +513,7 @@ const ExecutionSettingsPage: React.FC = () => { /> + ({ + read: vi.fn(), save: vi.fn(), peers: vi.fn(), + changed: undefined as undefined | (() => void), +})); +vi.mock('@/infrastructure/api/service-api/ConfigAPI', () => ({ configAPI: { getConfig: ports.read } })); +vi.mock('@/infrastructure/peer-device/PeerConnectionManager', () => ({ peerConnectionManager: { list: ports.peers } })); +vi.mock('@/infrastructure/config/services/ConfigManager', () => ({ configManager: { + setConfig: ports.save, + watch: (_path: string, changed: () => void) => { ports.changed = changed; return () => {}; }, +} })); + +let container: HTMLDivElement, root: Root; +const mount = () => act(async () => root.render()); +const toggle = () => container.querySelector('input[type="checkbox"]')!; +const click = () => act(async () => toggle().click()); +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise(done => { resolve = done; }); + return { promise, resolve }; +} + +beforeEach(() => { + ports.read.mockReset().mockResolvedValue(true); + ports.save.mockReset().mockResolvedValue(undefined); + ports.peers.mockReset().mockReturnValue([{ surfaceId: 'peer-test', capabilities: { subagentModelOverridePolicyV1: true } }]); + activateSurface('local'); + container = document.createElement('div'); + document.body.appendChild(container); + root = createRoot(container); +}); +afterEach(async () => { await act(async () => root.unmount()); container.remove(); activateSurface('local'); }); + +it('persists an explicit false and can re-enable the host setting', async () => { + await mount(); + expect(toggle().checked).toBe(true); + await click(); + expect(ports.save).toHaveBeenLastCalledWith('ai.allow_subagent_model_override', false); + expect(toggle().checked).toBe(false); + await click(); + expect(ports.save).toHaveBeenLastCalledWith('ai.allow_subagent_model_override', true); +}); + +it('locks unsupported peers without reading or writing the controller setting', async () => { + ports.peers.mockReturnValue([{ surfaceId: 'peer-test', capabilities: {} }]); + activateSurface('peer-test'); + await mount(); + expect(toggle().disabled).toBe(true); + expect(ports.read).not.toHaveBeenCalled(); + expect(ports.save).not.toHaveBeenCalled(); +}); + +it('does not enable editing when an older server omits the field', async () => { + ports.read.mockResolvedValue(undefined); + await mount(); + expect(toggle().disabled).toBe(true); + expect(ports.save).not.toHaveBeenCalled(); +}); + +it('preserves the committed setting on write failure', async () => { + ports.save.mockRejectedValueOnce(new Error('Offline')); + await mount(); + await click(); + expect(toggle().checked).toBe(true); + expect(container.querySelector('button')).not.toBeNull(); +}); + +it('keeps failed reads uneditable and supports retry', async () => { + ports.read.mockRejectedValueOnce(new Error('Offline')); + await mount(); + expect(toggle()).toBeNull(); + ports.read.mockResolvedValue(false); + await act(async () => container.querySelector('button')!.click()); + expect(toggle().checked).toBe(false); +}); + +it('discards a previous host read after switching to a peer', async () => { + const stale = deferred(); + ports.read.mockReturnValueOnce(stale.promise); + await mount(); + ports.read.mockResolvedValue(false); + await act(async () => activateSurface('peer-test')); + await act(async () => stale.resolve(true)); + expect(toggle().checked).toBe(false); +}); + +it('discards a previous host save after switching to a peer', async () => { + await mount(); + const pending = deferred(); + ports.save.mockReturnValueOnce(pending.promise); + await click(); + ports.read.mockResolvedValue(true); + await act(async () => activateSurface('peer-test')); + await act(async () => pending.resolve()); + expect(toggle().checked).toBe(true); +}); + +it('refreshes after host configuration changes without overriding a newer save', async () => { + await mount(); + const stale = deferred(); + ports.read.mockReturnValueOnce(stale.promise); + await act(async () => ports.changed!()); + await click(); + await act(async () => stale.resolve(true)); + expect(toggle().checked).toBe(false); +}); diff --git a/src/web-ui/src/app/scenes/settings/pages/ai/SubagentModelOverrideSection.tsx b/src/web-ui/src/app/scenes/settings/pages/ai/SubagentModelOverrideSection.tsx new file mode 100644 index 0000000000..ca477f1cc9 --- /dev/null +++ b/src/web-ui/src/app/scenes/settings/pages/ai/SubagentModelOverrideSection.tsx @@ -0,0 +1,80 @@ +import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react'; +import { Switch } from '@openbitfun/ui'; +import { ConfigLoadingState, ConfigPageRow, ConfigRetryState } from '@/infrastructure/config/components/common'; +import { configManager } from '@/infrastructure/config/services/ConfigManager'; +import { readSubagentModelPolicy, subagentModelOverridePath, writeSubagentModelPolicy } from '@/infrastructure/config/services/subagentModelPolicy'; +import { getActiveSurfaceScope, onSurfaceActivated } from '@/infrastructure/peer-device/deviceSurface'; +import { useI18n } from '@/infrastructure/i18n'; +import { createLogger } from '@/shared/utils/logger'; + +const log = createLogger('SubagentModelOverrideSettings'); + +export default function SubagentModelOverrideSection() { + const { t } = useI18n('settings/agentic-tools'); + const scope = useSyncExternalStore(onSurfaceActivated, getActiveSurfaceScope, getActiveSurfaceScope); + const [loaded, setLoaded] = useState<{ epoch: number; allowed: boolean | undefined } | null>(null); + const [error, setError] = useState<'load' | 'save' | null>(null); + const [saving, setSaving] = useState(false); + const request = useRef(0); + const savingRef = useRef(false); + const load = useCallback(async () => { + const current = ++request.current; + setError(null); + try { + const allowed = await readSubagentModelPolicy(); + if (scope.isCurrent() && current === request.current) setLoaded({ epoch: scope.epoch, allowed }); + } catch (failure) { + if (scope.isCurrent() && current === request.current) { + log.error('Failed to load subagent model override policy', failure); + setError('load'); + } + } + }, [scope]); + + useEffect(() => { + setLoaded(null); + setSaving(false); + savingRef.current = false; + void load(); + const stop = configManager.watch(subagentModelOverridePath, () => { + if (!savingRef.current) void load(); + }); + return () => { request.current++; stop(); }; + }, [load]); + + const ready = loaded?.epoch === scope.epoch; + const save = async (allowed: boolean) => { + if (!scope.isCurrent() || !ready || loaded.allowed === undefined || savingRef.current) return; + request.current++; + savingRef.current = true; + setSaving(true); + setError(null); + try { + await writeSubagentModelPolicy(allowed); + if (scope.isCurrent()) setLoaded({ epoch: scope.epoch, allowed }); + } catch (failure) { + if (scope.isCurrent()) { + log.error('Failed to save subagent model override policy', failure); + setError('save'); + } + } finally { + if (scope.isCurrent()) { savingRef.current = false; setSaving(false); } + } + }; + + return <> + + {ready + ? void save(event.target.checked)} /> + : !error && } + + {error && void load()} />} + ; +} diff --git a/src/web-ui/src/app/scenes/settings/pages/shared/RuntimeSettings.test.tsx b/src/web-ui/src/app/scenes/settings/pages/shared/RuntimeSettings.test.tsx index 0adcbe110e..8b4c541cec 100644 --- a/src/web-ui/src/app/scenes/settings/pages/shared/RuntimeSettings.test.tsx +++ b/src/web-ui/src/app/scenes/settings/pages/shared/RuntimeSettings.test.tsx @@ -44,6 +44,7 @@ vi.mock('../ai/DefaultHarnessSection', () => ({ default: () =>
default-harn vi.mock('../ai/ReviewCapacitySection', () => ({ default: () => null })); vi.mock('../ai/GenUILibrarySection', () => ({ default: () => null })); vi.mock('../ai/ToolJsonRepairSection', () => ({ default: () => null })); +vi.mock('../ai/SubagentModelOverrideSection', () => ({ default: () => null })); vi.mock('@openbitfun/ui', async (original) => ({ ...await original(), Select: ({ value, options, disabled, onValueChange }: { value: string; options: Array<{ value: string; label: string }>; disabled: boolean; onValueChange?: (value: string) => void }) => ( diff --git a/src/web-ui/src/infrastructure/api/generated/productControl.ts b/src/web-ui/src/infrastructure/api/generated/productControl.ts index c821406c6b..8e06e9cd95 100644 --- a/src/web-ui/src/infrastructure/api/generated/productControl.ts +++ b/src/web-ui/src/infrastructure/api/generated/productControl.ts @@ -1,5 +1,5 @@ // Generated by scripts/generate-interactive-capabilities.mjs; do not edit. -export const PRODUCT_CONTROL_GRAPH_DIGEST = "4b8a786017df37df61ff4c749771e0af19c851b6be51ed46504425c9bdf992bd" as const; +export const PRODUCT_CONTROL_GRAPH_DIGEST = "fe4be08cb20c2d67857891380d223a77d420345b94e2733d0000d14485027697" as const; export type ProductControlCapabilityId = "feature.home-search" | "feature.ai-assistant" | "feature.agents" | "feature.personal-assistants" | "feature.projects" | "feature.files-editor" | "feature.terminal" | "feature.cli-tui" | "feature.git" | "feature.code-review" | "feature.browser" | "feature.computer-use" | "feature.skills" | "feature.miniapps" | "feature.tasks-automation" | "feature.insights" | "feature.ecosystem-compatibility" | "feature.remote-workspaces" | "feature.remote-connect" | "feature.detached-dispatch" | "feature.pages" | "feature.voice-input" | "feature.desktop-pet" | "feature.desktop-cards" | "setting.application.general" | "setting.application.appearance" | "setting.application.pet" | "setting.application.input" | "setting.application.shortcuts" | "setting.application.development" | "setting.ai.models" | "setting.ai.permissions" | "setting.ai.memory" | "setting.workspace.session" | "setting.workspace.worktrees" | "setting.tools.execution" | "setting.application.terminal" | "setting.tools.desktop-control" | "setting.tools.browser-control" | "setting.tools.automation" | "setting.tools.web-search" | "setting.tools.mcp" | "setting.tools.acp" | "setting.data.usage" | "setting.data.archived" | "setting.data.diagnostics" | "feature.generative-ui"; @@ -39,7 +39,7 @@ export interface ProductControlOptionIdsByCapability { "setting.ai.memory": "enabled" | "btw-sessions" | "external-context-policy" | "minimum-rollout-idle-hours" | "maximum-rollout-age-days" | "startup-rollout-limit" | "startup-rollout-scan-limit" | "extraction-concurrency" | "raw-memory-limit" | "memory-retention-days"; "setting.workspace.session": "session-title-generation" | "prompt-suggestion" | "workspace-search"; "setting.workspace.worktrees": "worktree-root-path" | "worktree-branch-prefix" | "worktree-copy-local-changes" | "worktree-auto-delete-enabled" | "worktree-auto-delete-limit"; - "setting.tools.execution": "show-permission-mode-control" | "deferred-tool-loading" | "tool-presentation-mode" | "subagent-batch-policy" | "subagent-max-concurrency" | "swarm-max-concurrency" | "tool-timeout-seconds" | "computer-use-enabled" | "browser-auto-connect" | "tool-json-repair" | "genui-library"; + "setting.tools.execution": "show-permission-mode-control" | "deferred-tool-loading" | "tool-presentation-mode" | "subagent-batch-policy" | "subagent-max-concurrency" | "swarm-max-concurrency" | "tool-timeout-seconds" | "computer-use-enabled" | "browser-auto-connect" | "tool-json-repair" | "genui-library" | "subagent-model-override"; "setting.application.terminal": "terminal-default-shell" | "terminal-panel-position"; "setting.tools.desktop-control": never; "setting.tools.browser-control": never; diff --git a/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts b/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts index 66cd38780f..3a9455290d 100644 --- a/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts +++ b/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate-interactive-capabilities.mjs; do not edit. // Source: openbitfun_product_domains::remote_surface (Product Operation Registry). -export const REMOTE_SURFACE_REGISTRY_DIGEST = "fnv1a64:8732d7ca210f7cf2" as const; +export const REMOTE_SURFACE_REGISTRY_DIGEST = "fnv1a64:67a20e107dd93ffd" as const; /** * Registered Tauri commands the Peer Device controller keeps on the controller @@ -167,6 +167,7 @@ export const PEER_HOST_CAPABILITY_IDS = [ "gen_ui_libraries_v1", "model_routing_v1", "model_pool_selection_v1", + "subagent_model_override_policy_v1", "magpie_discovery_v1", "background_result_delivery_v1", "dialog_queue_v1", @@ -229,6 +230,7 @@ export const PEER_HOST_ADVERTISED_CAPABILITIES: Readonly< "gen_ui_libraries_v1", "model_routing_v1", "model_pool_selection_v1", + "subagent_model_override_policy_v1", "magpie_discovery_v1", "background_result_delivery_v1", "dialog_queue_v1", @@ -282,6 +284,7 @@ export const PEER_HOST_ADVERTISED_CAPABILITIES: Readonly< cli: [ "model_routing_v1", "model_pool_selection_v1", + "subagent_model_override_policy_v1", "magpie_discovery_v1", "background_result_delivery_v1", "dialog_queue_v1", diff --git a/src/web-ui/src/infrastructure/config/services/subagentModelPolicy.ts b/src/web-ui/src/infrastructure/config/services/subagentModelPolicy.ts new file mode 100644 index 0000000000..bc27cac8e7 --- /dev/null +++ b/src/web-ui/src/infrastructure/config/services/subagentModelPolicy.ts @@ -0,0 +1,26 @@ +import { configAPI } from '@/infrastructure/api/service-api/ConfigAPI'; +import { getActiveSurfaceScope } from '@/infrastructure/peer-device/deviceSurface'; +import { peerConnectionManager } from '@/infrastructure/peer-device/PeerConnectionManager'; +import { configManager } from './ConfigManager'; + +export const subagentModelOverridePath = 'ai.allow_subagent_model_override'; + +export function supportsSubagentModelPolicy(): boolean { + const scope = getActiveSurfaceScope(); + return scope.surfaceId === 'local' || peerConnectionManager.list() + .find(peer => peer.surfaceId === scope.surfaceId)?.capabilities.subagentModelOverridePolicyV1 === true; +} + +/** Undefined means the connected host predates this policy, not a default of true. */ +export async function readSubagentModelPolicy(): Promise { + if (!supportsSubagentModelPolicy()) return undefined; + const value = await configAPI.getConfig(subagentModelOverridePath); + if (value == null) return undefined; + if (typeof value !== 'boolean') throw new Error('Invalid subagent model override policy'); + return value; +} + +export async function writeSubagentModelPolicy(allowed: boolean): Promise { + if (!supportsSubagentModelPolicy()) throw new Error('Subagent model override policy is unsupported on this host'); + await configManager.setConfig(subagentModelOverridePath, allowed); +} diff --git a/src/web-ui/src/infrastructure/config/types/index.ts b/src/web-ui/src/infrastructure/config/types/index.ts index e52be1c0de..9d95c5b17e 100644 --- a/src/web-ui/src/infrastructure/config/types/index.ts +++ b/src/web-ui/src/infrastructure/config/types/index.ts @@ -516,6 +516,7 @@ export interface AIConfig { tool_presentation_mode?: 'native' | 'ptc' | 'ptc_python'; default_models: DefaultModelsConfig; model_routing?: ModelRoutingConfig; + allow_subagent_model_override: boolean; agent_model_defaults: AgentModelDefaultsConfig; agent_model_selections?: AgentModelSelections; task_models: TaskModelsConfig; diff --git a/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.test.ts b/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.test.ts index 70d94d4fbc..32e7a15a51 100644 --- a/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.test.ts +++ b/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.test.ts @@ -102,6 +102,7 @@ describe('PeerConnectionManager attach', () => { btw_initial_model_selection_v1: true, btw_model_pool_selection_v1: true, magpie_discovery_v1: true, + subagent_model_override_policy_v1: true, }, }, }), @@ -121,6 +122,7 @@ describe('PeerConnectionManager attach', () => { expect(caps.sessionTrajectoryV1).toBe(true); expect(caps.btwInitialModelSelectionV1).toBe(true); expect(caps.btwModelPoolSelectionV1).toBe(true); + expect(caps.subagentModelOverridePolicyV1).toBe(true); expect(caps.magpieDiscoveryV1).toBe(true); }); diff --git a/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts b/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts index 448c257b23..3001ef8e51 100644 --- a/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts +++ b/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts @@ -84,6 +84,7 @@ export interface PeerHostCapabilities { readonly sessionTrajectoryV1?: boolean; readonly modelRoutingV1?: boolean; readonly modelPoolSelectionV1?: boolean; + readonly subagentModelOverridePolicyV1?: boolean; readonly magpieDiscoveryV1?: boolean; readonly computerUseSharingV1?: boolean; /** Typed ProductControl HostInvoke, including shared config read-back. */ @@ -258,6 +259,7 @@ const NO_CAPABILITIES: PeerHostCapabilities = { sessionTrajectoryV1: false, modelRoutingV1: false, modelPoolSelectionV1: false, + subagentModelOverridePolicyV1: false, magpieDiscoveryV1: false, computerUseSharingV1: false, productControlV1: false, @@ -732,6 +734,7 @@ export class PeerConnectionManager { genUiLibrariesV1: caps?.gen_ui_libraries_v1 === true, modelRoutingV1: caps?.model_routing_v1 === true, modelPoolSelectionV1: caps?.model_pool_selection_v1 === true, + subagentModelOverridePolicyV1: caps?.subagent_model_override_policy_v1 === true, magpieDiscoveryV1: caps?.magpie_discovery_v1 === true, computerUseSharingV1: caps?.computer_use_sharing_v1 === true, productControlV1: caps?.product_control_v1 === true, diff --git a/src/web-ui/src/locales/en-US/settings/agentic-tools.json b/src/web-ui/src/locales/en-US/settings/agentic-tools.json index 33d06d81b1..5b7f560553 100644 --- a/src/web-ui/src/locales/en-US/settings/agentic-tools.json +++ b/src/web-ui/src/locales/en-US/settings/agentic-tools.json @@ -42,7 +42,16 @@ "subagentModelSettings": "Go to the Agents page to set models for individual subagents", "subagentModelInherit": "Inherit parent session", "subagentDefaultModel": "Default subagent model", - "subagentDefaultModelDesc": "Used by subagents without an individual model override." + "subagentDefaultModelDesc": "Used by subagents without an individual model override.", + "subagentModelOverride": { + "label": "Allow agents to choose subagent models", + "hint": "When disabled, subagents use their configured models. Agents cannot choose a different model when launching or continuing work.", + "unsupported": "This host does not support controlling subagent model selection. Update the host to change this setting.", + "loadFailed": "Could not load the subagent model setting.", + "saveFailed": "Could not save the subagent model setting.", + "loading": "Loading subagent model setting…", + "retry": "Retry" + } }, "filters": { "all": "All", diff --git a/src/web-ui/src/locales/zh-CN/settings/agentic-tools.json b/src/web-ui/src/locales/zh-CN/settings/agentic-tools.json index 58e046be99..cb11b0084e 100644 --- a/src/web-ui/src/locales/zh-CN/settings/agentic-tools.json +++ b/src/web-ui/src/locales/zh-CN/settings/agentic-tools.json @@ -42,7 +42,16 @@ "subagentModelSettings": "前往智能体页面为子智能体单独设置模型", "subagentModelInherit": "继承父会话", "subagentDefaultModel": "子智能体默认模型", - "subagentDefaultModelDesc": "未单独指定模型的子智能体使用此设置。" + "subagentDefaultModelDesc": "未单独指定模型的子智能体使用此设置。", + "subagentModelOverride": { + "label": "允许 Agent 指定子 Agent 模型", + "hint": "关闭后,子 Agent 使用已配置的模型,Agent 无法在启动或继续执行时指定其他模型。", + "unsupported": "当前宿主不支持控制子 Agent 模型选择,请更新宿主后修改此设置。", + "loadFailed": "无法加载子 Agent 模型设置。", + "saveFailed": "无法保存子 Agent 模型设置。", + "loading": "正在加载子 Agent 模型设置…", + "retry": "重试" + } }, "filters": { "all": "全部", diff --git a/src/web-ui/src/locales/zh-TW/settings/agentic-tools.json b/src/web-ui/src/locales/zh-TW/settings/agentic-tools.json index 4a4be6da39..5e395ae62c 100644 --- a/src/web-ui/src/locales/zh-TW/settings/agentic-tools.json +++ b/src/web-ui/src/locales/zh-TW/settings/agentic-tools.json @@ -42,7 +42,16 @@ "subagentModelSettings": "前往智慧體頁面為子智慧體個別設定模型", "subagentModelInherit": "繼承父會話", "subagentDefaultModel": "子智能體預設模型", - "subagentDefaultModelDesc": "未個別指定模型的子智慧體使用此設定。" + "subagentDefaultModelDesc": "未個別指定模型的子智慧體使用此設定。", + "subagentModelOverride": { + "label": "允許 Agent 指定子 Agent 模型", + "hint": "關閉後,子 Agent 使用已設定的模型,Agent 無法在啟動或繼續執行時指定其他模型。", + "unsupported": "目前主機不支援控制子 Agent 模型選擇,請更新主機後修改此設定。", + "loadFailed": "無法載入子 Agent 模型設定。", + "saveFailed": "無法儲存子 Agent 模型設定。", + "loading": "正在載入子 Agent 模型設定…", + "retry": "重試" + } }, "filters": { "all": "全部", From f44dbd63e600c37371c6849a3eb4497626ded25b Mon Sep 17 00:00:00 2001 From: wsp Date: Tue, 17 Nov 2026 19:24:03 +0800 Subject: [PATCH 3/5] feat(agent): add configurable fork delegation - Add AgentFork for background delegation with inherited context. - Preserve the parent tool definitions for fork prompt-cache reuse and enforce delegation policy when a launch tool is called. - Expose the fork default model in execution settings and track fork runs across chat, CLI, and remote surfaces. --- .../capabilities.json | 5 +- .../capabilities/feature.agents.md | 2 +- .../technical/product-control-open-audit.json | 2 +- .../technical/tauri-command-map.json | 2 +- .../flow-chat-presentation/src/registry.ts | 1 + src/apps/cli/src/peer_host/fanout.rs | 41 ++++--- src/apps/cli/src/ui/chat/tools.rs | 2 +- src/apps/cli/src/ui/theme.rs | 2 +- src/apps/cli/src/ui/tool_cards.rs | 32 +++++- .../policy/ChatMessageStructurePolicy.ets | 4 +- .../services/SubagentStreamCoordinator.ets | 2 +- .../subagent-process-visibility.test.cjs | 38 ++++--- .../core/builtin_skills/create-agent/SKILL.md | 2 +- .../create-agent/references/tool-catalog.md | 1 + .../agentic/agents/definitions/modes/claw.rs | 1 + .../agents/definitions/modes/cowork.rs | 1 + .../agents/definitions/modes/deep_research.rs | 2 + .../assembly/core/src/agentic/agents/mod.rs | 2 + .../core/src/agentic/agents/registry/query.rs | 2 +- .../src/agentic/coordination/coordinator.rs | 12 +- .../src/agentic/tools/agent-tool-exposure.md | 1 + .../agent_collaboration/agent_control.rs | 107 ++++++++++++++++++ .../agent_collaboration/agent_list_tool.rs | 13 ++- .../agent_collaboration/mod.rs | 1 + .../agent_collaboration/schema.rs | 30 +++++ .../agent_collaboration/tests.rs | 92 ++++++++++++++- .../src/agentic/tools/implementations/mod.rs | 4 +- .../agentic/tools/pipeline/tool_pipeline.rs | 2 +- .../core/src/agentic/tools/product_runtime.rs | 1 + .../tools/product_runtime/materialization.rs | 2 + .../core/src/agentic/tools/registry.rs | 1 + .../generated/product-control-catalog.json | 5 +- .../agent-runtime/src/custom_agent.rs | 1 + .../custom_agent_mode_contracts.rs | 1 + .../execution/tool-contracts/src/framework.rs | 9 +- .../execution/tool-execution/src/pipeline.rs | 2 +- .../tests/tool_pipeline_planning.rs | 22 ++++ .../execution/tool-provider-groups/src/lib.rs | 12 +- .../src/remote_connect.rs | 2 + .../tests/remote_connect_contracts.rs | 56 ++++----- .../src/components/ChatTranscript.tsx | 12 +- .../mobile-chat-regressions-fixture.tsx | 4 +- .../mobile-chat-regressions-browser.test.mjs | 20 ++++ .../interactive-capabilities/catalog.json | 1 + src/web-ui/README.md | 9 +- .../generated/interactive-capabilities.json | 5 +- .../agents/components/CreateAgentPage.tsx | 1 + .../scenes/agents/components/toolGroups.ts | 2 +- .../pages/ai/ExecutionSettingsPage.tsx | 73 +++++++----- .../pages/ai/SubagentModelOverrideSection.tsx | 12 +- .../pages/shared/RuntimeSettings.test.tsx | 38 ++++++- .../app/scenes/settings/settingsRegistry.ts | 1 + .../src/flow_chat/components/FlowToolCard.tsx | 2 +- .../src/flow_chat/timeline/agentCardLayout.ts | 2 +- .../tool-cards/AgentControlToolCard.test.tsx | 6 +- .../tool-cards/AgentControlToolCard.tsx | 4 +- .../tool-cards/builtinAgentSessions.ts | 4 +- .../src/flow_chat/tool-cards/index.test.ts | 2 + src/web-ui/src/flow_chat/tool-cards/index.ts | 1 + .../flow_chat/tool-cards/toolCardMetadata.ts | 11 ++ .../tool-cards/toolInteractionModel.test.ts | 8 +- .../tool-cards/toolInteractionModel.ts | 6 +- .../utils/deepReviewCapacityGuard.ts | 2 +- .../flow_chat/utils/deepReviewContinuation.ts | 2 +- .../flow_chat/utils/deepReviewExperience.ts | 2 +- .../api/generated/productControl.ts | 2 +- .../locales/en-US/scenes/capabilities.json | 3 +- .../locales/en-US/settings/agentic-tools.json | 2 + .../locales/zh-CN/scenes/capabilities.json | 3 +- .../locales/zh-CN/settings/agentic-tools.json | 2 + .../locales/zh-TW/scenes/capabilities.json | 3 +- .../locales/zh-TW/settings/agentic-tools.json | 2 + 72 files changed, 602 insertions(+), 165 deletions(-) diff --git a/docs/interactive-capabilities/capabilities.json b/docs/interactive-capabilities/capabilities.json index a11868d258..688daf9b19 100644 --- a/docs/interactive-capabilities/capabilities.json +++ b/docs/interactive-capabilities/capabilities.json @@ -4,7 +4,7 @@ "title": "OpenBitFun Playbook", "origin": "https://playbook.openbitfun.com", "source": "src/shared/interactive-capabilities/catalog.json", - "digest": "fe4be08cb20c2d67857891380d223a77d420345b94e2733d0000d14485027697", + "digest": "408cc52581d52de1e3686853eec8a09b2c02129869cb82b2931e21694e10557b", "ownerDigest": "1fdb9c49d404c02483c08e1e0fe9effa0aaa4f0f2914578bcaa63e04de16cc16", "searchAcceptance": [ { @@ -1917,6 +1917,7 @@ }, "delegateTools": [ "AgentSpawn", + "AgentFork", "AgentWait", "AgentSendInput", "AgentControl", @@ -23575,6 +23576,7 @@ "kind": "delegate", "tools": [ "AgentSpawn", + "AgentFork", "AgentWait", "AgentSendInput", "AgentControl", @@ -23686,6 +23688,7 @@ "Spawn parallel subagents to audit error handling across auth, billing, and gateway, then synthesize the findings", "Help me draft a read-only subagent specialized in reviewing SQL migration safety", "AgentSpawn", + "AgentFork", "AgentWait", "AgentSendInput", "AgentControl", diff --git a/docs/interactive-capabilities/capabilities/feature.agents.md b/docs/interactive-capabilities/capabilities/feature.agents.md index a04cd7eb27..b31d2ae796 100644 --- a/docs/interactive-capabilities/capabilities/feature.agents.md +++ b/docs/interactive-capabilities/capabilities/feature.agents.md @@ -50,7 +50,7 @@ Browse and customize specialized agents, tailor each role’s allowed tools and - Toggle tool groups, individual tools, and Skills per agent — with one-click reset to defaults - 说明:既可以给内置模式增减工具与技能,也可以为自定义角色做最小权限裁剪;改乱了点一下「恢复默认」就能回到出厂推荐组合。 - Why & how: Tailor built-in or custom agents with minimal-privilege tool and Skill pickers, and reset any built-in profile back to defaults in one click. -- **由专用智能体工具控制 / Delegated Agent tool** · `AgentSpawn` / `AgentWait` / `AgentSendInput` / `AgentControl` / `AgentList` · 由主智能体自动派生并行子智能体协同调研、编码与审查,并统一汇总结果 +- **由专用智能体工具控制 / Delegated Agent tool** · `AgentSpawn` / `AgentFork` / `AgentWait` / `AgentSendInput` / `AgentControl` / `AgentList` · 由主智能体自动派生并行子智能体协同调研、编码与审查,并统一汇总结果 - Let the primary agent spawn parallel subagents for research, coding, and review and synthesize their output - 说明:主智能体会把大任务拆成互不踩踏的子切片交给多个子智能体同时推进;你在对话流里还能看到可爱的子代理化身卡片并随时点开查看它的独立推理轨迹。 - Why & how: The primary agent breaks complex requests into non-overlapping slices, monitors running subagents, steers or cancels them if needed, and delivers a unified answer. diff --git a/docs/interactive-capabilities/technical/product-control-open-audit.json b/docs/interactive-capabilities/technical/product-control-open-audit.json index 62f6abb135..c577614185 100644 --- a/docs/interactive-capabilities/technical/product-control-open-audit.json +++ b/docs/interactive-capabilities/technical/product-control-open-audit.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "generatedFrom": "src/shared/interactive-capabilities/catalog.json", - "catalogDigest": "fe4be08cb20c2d67857891380d223a77d420345b94e2733d0000d14485027697", + "catalogDigest": "408cc52581d52de1e3686853eec8a09b2c02129869cb82b2931e21694e10557b", "count": 231, "reasonCounts": { "externalAuth": 4, diff --git a/docs/interactive-capabilities/technical/tauri-command-map.json b/docs/interactive-capabilities/technical/tauri-command-map.json index 6829e9e967..85fbc91964 100644 --- a/docs/interactive-capabilities/technical/tauri-command-map.json +++ b/docs/interactive-capabilities/technical/tauri-command-map.json @@ -1,7 +1,7 @@ { "schemaVersion": 2, "generatedFrom": "src/shared/interactive-capabilities/catalog.json", - "catalogDigest": "fe4be08cb20c2d67857891380d223a77d420345b94e2733d0000d14485027697", + "catalogDigest": "408cc52581d52de1e3686853eec8a09b2c02129869cb82b2931e21694e10557b", "commandCount": 705, "coverage": { "commandCount": 705, diff --git a/packages/flow-chat-presentation/src/registry.ts b/packages/flow-chat-presentation/src/registry.ts index 72305d370f..12955f8d21 100644 --- a/packages/flow-chat-presentation/src/registry.ts +++ b/packages/flow-chat-presentation/src/registry.ts @@ -15,6 +15,7 @@ export const toolPresentationRegistry = { ListModels: { owner: 'standard', component: 'ListModelsToolCard' }, ControlHub: { owner: 'standard', component: 'ControlHubToolCard' }, AgentSpawn: { owner: 'standard', component: 'AgentControlToolCard' }, + AgentFork: { owner: 'standard', component: 'AgentControlToolCard' }, AgentSendInput: { owner: 'standard', component: 'SessionMessageToolCard' }, AgentWait: { owner: 'standard', component: 'AgentWaitToolCard' }, TodoWrite: { owner: 'standard', component: 'TodoToolCard' }, diff --git a/src/apps/cli/src/peer_host/fanout.rs b/src/apps/cli/src/peer_host/fanout.rs index 56ddc5cfae..6996332a08 100644 --- a/src/apps/cli/src/peer_host/fanout.rs +++ b/src/apps/cli/src/peer_host/fanout.rs @@ -391,11 +391,12 @@ async fn handle_agentic_event( { let (tool_name, params) = effective_tool_invocation(&identity.tool_name, params); debug_assert_eq!(identity.effective_name(), tool_name); - if matches!(tool_name, "Task" | "AgentSpawn") - && params - .get("run_in_background") - .and_then(serde_json::Value::as_bool) - == Some(true) + if matches!(tool_name, "AgentSpawn" | "AgentFork") + || (tool_name == "Task" + && params + .get("run_in_background") + .and_then(serde_json::Value::as_bool) + == Some(true)) { state.turns.record_background_task_call( &PeerTurnKey::new(session_id, turn_id), @@ -426,17 +427,27 @@ async fn handle_agentic_event( let terminal_task_call = match tool_event { ToolEventData::Completed { identity, result, .. - } if matches!(identity.effective_name(), "Task" | "AgentSpawn") => Some(( - identity.tool_id.as_str(), - result - .get("background_task_id") - .and_then(serde_json::Value::as_str), - result - .get("cancelled_background_tasks") - .and_then(serde_json::Value::as_u64), - )), + } if matches!( + identity.effective_name(), + "Task" | "AgentSpawn" | "AgentFork" + ) => + { + Some(( + identity.tool_id.as_str(), + result + .get("bg_task_id") + .or_else(|| result.get("background_task_id")) + .and_then(serde_json::Value::as_str), + result + .get("cancelled_background_tasks") + .and_then(serde_json::Value::as_u64), + )) + } ToolEventData::Failed { identity, .. } | ToolEventData::Cancelled { identity, .. } - if matches!(identity.effective_name(), "Task" | "AgentSpawn") => + if matches!( + identity.effective_name(), + "Task" | "AgentSpawn" | "AgentFork" + ) => { Some((identity.tool_id.as_str(), None, None)) } diff --git a/src/apps/cli/src/ui/chat/tools.rs b/src/apps/cli/src/ui/chat/tools.rs index 5d9611f42d..38ce3a32a7 100644 --- a/src/apps/cli/src/ui/chat/tools.rs +++ b/src/apps/cli/src/ui/chat/tools.rs @@ -92,7 +92,7 @@ impl ChatView { } "Edit" | "Write" | "Delete" | "search_replace" | "write_file" | "write_file_tool" => tool_state.result.is_some(), - "Task" | "AgentSpawn" => { + "Task" | "AgentSpawn" | "AgentFork" => { tool_state.result.is_some() || matches!( tool_state.status, diff --git a/src/apps/cli/src/ui/theme.rs b/src/apps/cli/src/ui/theme.rs index aba3e8c421..4db98a20aa 100644 --- a/src/apps/cli/src/ui/theme.rs +++ b/src/apps/cli/src/ui/theme.rs @@ -677,7 +677,7 @@ pub(super) fn tool_icon(tool_name: &str) -> &'static str { "LS" | "list_dir" | "ls" => "\u{2192}", // → "WebFetch" => "%", "WebSearch" => "\u{25c8}", // ◈ - "Task" | "AgentSpawn" => "#", + "Task" | "AgentSpawn" | "AgentFork" => "#", "HmosCompilation" => "\u{2692}", "TodoWrite" => "\u{2699}", // ⚙ "Skill" => "\u{2192}", // → diff --git a/src/apps/cli/src/ui/tool_cards.rs b/src/apps/cli/src/ui/tool_cards.rs index a614468219..af9e27e395 100644 --- a/src/apps/cli/src/ui/tool_cards.rs +++ b/src/apps/cli/src/ui/tool_cards.rs @@ -126,7 +126,7 @@ fn tool_display_mode(tool_name: &str, tool_state: &ToolDisplayState) -> ToolDisp } // Agent launches always render as Block — even during early detection / params streaming, // we want to show the subagent card with real-time progress rather than inline "Delegating...". - "Task" | "AgentSpawn" => ToolDisplayMode::Block, + "Task" | "AgentSpawn" | "AgentFork" => ToolDisplayMode::Block, // Always block tools "TodoWrite" | "AskUserQuestion" | "CreatePlan" => ToolDisplayMode::Block, @@ -426,7 +426,7 @@ fn inline_pending_text(canonical: &str, tool_state: &ToolDisplayState) -> String "LS" => "Listing directory...".to_string(), "WebSearch" => "Searching web...".to_string(), "WebFetch" => "Fetching from the web...".to_string(), - "Task" | "AgentSpawn" => "Launching agent...".to_string(), + "Task" | "AgentSpawn" | "AgentFork" => "Launching agent...".to_string(), "TodoWrite" => "Updating todos...".to_string(), "HmosCompilation" => "Compiling HarmonyOS project...".to_string(), "Skill" => "Loading skill...".to_string(), @@ -640,7 +640,7 @@ fn render_block_dispatch( "OpenBitFunControl" if login_qr_result(tool_state).is_some() => { render_login_qr_block(tool_state, theme, focused, spinner_frame, available_width) } - "Task" | "AgentSpawn" => { + "Task" | "AgentSpawn" | "AgentFork" => { render_task_block(tool_state, theme, focused, spinner_frame, available_width) } "TodoWrite" => { @@ -1514,7 +1514,11 @@ fn render_task_block( ToolDisplayStatus::Running | ToolDisplayStatus::Streaming ); - let title = format!("{} Agent", capitalize_first(&subagent_type)); + let title = if tool_state.tool_name == "AgentFork" { + tool_state.tool_name.clone() + } else { + format!("{} Agent", capitalize_first(&subagent_type)) + }; // Build description line with tool call count (if available) let desc_text = if let Some(ref progress) = tool_state.subagent_progress { @@ -2200,6 +2204,26 @@ mod tests { use super::*; use ratatui::{backend::TestBackend, style::Color, widgets::List, Terminal}; + #[test] + fn agent_fork_renders_a_launch_without_an_agent_type() { + let state = ToolDisplayState { + tool_id: "fork-call".into(), + tool_name: "AgentFork".into(), + parameters: serde_json::json!({"agent_id":"review", "prompt":"Check the inherited findings"}), + status: ToolDisplayStatus::Running, + result: None, + progress_message: None, + duration_ms: None, + metadata: None, + subagent_progress: None, + }; + let rendered = render_tool_card_inner(&state, &Theme::dark(), false, false, "", 80); + let text = rendered.plain_lines.join("\n"); + assert!(text.contains("AgentFork")); + assert!(text.contains("Check the inherited findings")); + assert!(!text.contains("Unknown")); + } + fn login_qr_state() -> ToolDisplayState { let qr = openbitfun_core::service::remote_connect::QrGenerator::present_content( "https://example.test/wechat-login?code=terminal-fixture", diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ChatMessageStructurePolicy.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ChatMessageStructurePolicy.ets index 4bae245e58..247fb94475 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ChatMessageStructurePolicy.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/pages/policy/ChatMessageStructurePolicy.ets @@ -471,14 +471,14 @@ export class ChatMessageStructurePolicy { * Normalized names of the tool calls that launch a child agent. * * `Task` is the delegation tool older desktops used; the current delegation - * tool is `AgentSpawn`. Both own a branch, and mobile web accepts both names + * tools are `AgentSpawn` and `AgentFork`. All own a branch, and mobile web accepts these names * for the same reason. A plain tool row must never be mistaken for one of * these, so the list stays explicit instead of matching a prefix or a * contains-rule. */ private static isOwnerTool(tool: ConversationUiToolStatus): boolean { const name = ToolStatusPresentationPolicy.normalizedName(tool); - return name === 'task' || name === 'agentspawn'; + return name === 'task' || name === 'agentspawn' || name === 'agentfork'; } /** diff --git a/src/apps/mobile/harmonyos/entry/src/main/ets/services/SubagentStreamCoordinator.ets b/src/apps/mobile/harmonyos/entry/src/main/ets/services/SubagentStreamCoordinator.ets index e4fa56520b..4296dbb81d 100644 --- a/src/apps/mobile/harmonyos/entry/src/main/ets/services/SubagentStreamCoordinator.ets +++ b/src/apps/mobile/harmonyos/entry/src/main/ets/services/SubagentStreamCoordinator.ets @@ -411,7 +411,7 @@ export class SubagentStreamCoordinator { private static isOwnerToolName(rawName: string): boolean { const name = rawName.trim().replace(/[\s-]/g, '_').toLowerCase(); - return name === 'task' || name === 'agentspawn'; + return name === 'task' || name === 'agentspawn' || name === 'agentfork'; } private static ownerData(event: HostSessionEvent): SubagentOwnerItemData | undefined { diff --git a/src/apps/mobile/harmonyos/tools/tests/subagent-process-visibility.test.cjs b/src/apps/mobile/harmonyos/tools/tests/subagent-process-visibility.test.cjs index e3cbdf66db..73c3d0655a 100644 --- a/src/apps/mobile/harmonyos/tools/tests/subagent-process-visibility.test.cjs +++ b/src/apps/mobile/harmonyos/tools/tests/subagent-process-visibility.test.cjs @@ -450,7 +450,7 @@ test('an unmarked launch item keeps the parent rows that follow it out of its br }); test('every owner name the host can send opens the branch', () => { - for (const name of ['Task', 'task', 'TASK', ' Task ', 'AgentSpawn', 'agentspawn', 'AgentSpawn']) { + for (const name of ['Task', 'task', 'TASK', ' Task ', 'AgentSpawn', 'agentspawn', 'AgentFork', 'agentfork']) { const owner = { type: 'tool', tool: { id: 'call', name, status: 'running' } }; const child = { type: 'text', is_subagent: true, content: 'child output' }; const scoped = Policy.scopeSubagentItems([owner, child]); @@ -459,23 +459,25 @@ test('every owner name the host can send opens the branch', () => { }); test('a card read from a decorated parent message carries the child branch', () => { - const harness = coordinatorHarness(); - const { coordinator, opened } = harness; - coordinator.beginSession(SESSION); - coordinator.observeParentEvent(ownerRecord(1)); - assert.ok(opened.has(CHILD_SESSION), 'the child session is followed once its launch is read'); - - const callbacks = opened.get(CHILD_SESSION); - childRecords().forEach(event => callbacks.onEvent(event)); - callbacks.onCaughtUp(); - - const decorated = coordinator.decorate(parentMessages([ownerRecord(1)])); - const card = Policy.subagentBranchAt(ui.toConversationUiMessage(decorated[1]).items || [], 0, SWARM_CALL_ID); - assert.ok(card, 'the branch is found by the launch tool call'); - assert.deepEqual((card.subItems || []).map(child => child.type), ['thinking', 'tool', 'text']); - assert.ok(harness.notifications() > 0, 'the parent is republished when the branch changes'); - coordinator.endSession(); - assert.ok(harness.closed.includes(CHILD_SESSION), 'and the child stream is closed with the session'); + for (const toolName of ['AgentSpawn', 'AgentFork']) { + const harness = coordinatorHarness(); + const { coordinator, opened } = harness; + coordinator.beginSession(SESSION); + coordinator.observeParentEvent(ownerRecord(1, CHILD_SESSION, toolName)); + assert.ok(opened.has(CHILD_SESSION), 'the child session is followed once its launch is read'); + + const callbacks = opened.get(CHILD_SESSION); + childRecords().forEach(event => callbacks.onEvent(event)); + callbacks.onCaughtUp(); + + const decorated = coordinator.decorate(parentMessages([ownerRecord(1, CHILD_SESSION, toolName)])); + const card = Policy.subagentBranchAt(ui.toConversationUiMessage(decorated[1]).items || [], 0, SWARM_CALL_ID); + assert.ok(card, 'the branch is found by the launch tool call'); + assert.deepEqual((card.subItems || []).map(child => child.type), ['thinking', 'tool', 'text']); + assert.ok(harness.notifications() > 0, 'the parent is republished when the branch changes'); + coordinator.endSession(); + assert.ok(harness.closed.includes(CHILD_SESSION), 'and the child stream is closed with the session'); + } }); test('the same child record published twice adds one step', () => { diff --git a/src/crates/assembly/core/builtin_skills/create-agent/SKILL.md b/src/crates/assembly/core/builtin_skills/create-agent/SKILL.md index 1a35ce6aa7..b50fcff08a 100644 --- a/src/crates/assembly/core/builtin_skills/create-agent/SKILL.md +++ b/src/crates/assembly/core/builtin_skills/create-agent/SKILL.md @@ -58,7 +58,7 @@ Write the role prompt in the Markdown body, not in a YAML `prompt` field. Use in Prefer an explicit tool list tailored to the role. If `tools` is omitted, these defaults apply: -- Mode: `Read`, `Glob`, `Grep`, `Write`, `Edit`, `Delete`, `ExecCommand`, `WriteStdin`, `ExecControl`, `AgentSpawn`, `AgentSendInput`, `AgentControl`, `ListModels`, `AgentWait`, `Skill`, `WebSearch`, `WebFetch`, `get_goal`, `create_goal`, `update_goal`. +- Mode: `Read`, `Glob`, `Grep`, `Write`, `Edit`, `Delete`, `ExecCommand`, `WriteStdin`, `ExecControl`, `AgentSpawn`, `AgentFork`, `AgentSendInput`, `AgentControl`, `ListModels`, `AgentWait`, `Skill`, `WebSearch`, `WebFetch`, `get_goal`, `create_goal`, `update_goal`. - Subagent: `LS`, `Read`, `Glob`, `Grep`. An explicit `tools: []` gives the role no tools. Setting `readonly: false` alone does not add write tools. diff --git a/src/crates/assembly/core/builtin_skills/create-agent/references/tool-catalog.md b/src/crates/assembly/core/builtin_skills/create-agent/references/tool-catalog.md index a3798a6a45..c6fe019eea 100644 --- a/src/crates/assembly/core/builtin_skills/create-agent/references/tool-catalog.md +++ b/src/crates/assembly/core/builtin_skills/create-agent/references/tool-catalog.md @@ -33,6 +33,7 @@ Use these tables to select tools for the user's tasks, then put their exact name | Tool name | Purpose | | --- | --- | | `AgentSpawn` | Launch an agent to work independently in the background. | +| `AgentFork` | Launch a background agent with a copy of the current conversation context. | | `AgentSendInput` | Send an instruction to an existing agent. | | `AgentWait` | Wait for selected background agent results. | | `AgentList` | List direct child agents and their status. | diff --git a/src/crates/assembly/core/src/agentic/agents/definitions/modes/claw.rs b/src/crates/assembly/core/src/agentic/agents/definitions/modes/claw.rs index b6cdb02f34..937a622823 100644 --- a/src/crates/assembly/core/src/agentic/agents/definitions/modes/claw.rs +++ b/src/crates/assembly/core/src/agentic/agents/definitions/modes/claw.rs @@ -18,6 +18,7 @@ impl ClawMode { default_tools: vec![ "AskUserQuestion".to_string(), "AgentSpawn".to_string(), + "AgentFork".to_string(), "AgentSendInput".to_string(), "AgentControl".to_string(), "AgentList".to_string(), diff --git a/src/crates/assembly/core/src/agentic/agents/definitions/modes/cowork.rs b/src/crates/assembly/core/src/agentic/agents/definitions/modes/cowork.rs index 38dea04daa..4c7859a9ae 100644 --- a/src/crates/assembly/core/src/agentic/agents/definitions/modes/cowork.rs +++ b/src/crates/assembly/core/src/agentic/agents/definitions/modes/cowork.rs @@ -25,6 +25,7 @@ impl CoworkMode { "create_goal".to_string(), "update_goal".to_string(), "AgentSpawn".to_string(), + "AgentFork".to_string(), "AgentSendInput".to_string(), "AgentControl".to_string(), "AgentList".to_string(), diff --git a/src/crates/assembly/core/src/agentic/agents/definitions/modes/deep_research.rs b/src/crates/assembly/core/src/agentic/agents/definitions/modes/deep_research.rs index fbbdc7f555..374243290c 100644 --- a/src/crates/assembly/core/src/agentic/agents/definitions/modes/deep_research.rs +++ b/src/crates/assembly/core/src/agentic/agents/definitions/modes/deep_research.rs @@ -16,6 +16,7 @@ impl DeepResearchMode { Self { default_tools: vec![ "AgentSpawn".to_string(), + "AgentFork".to_string(), "AgentSendInput".to_string(), "AgentControl".to_string(), "AgentList".to_string(), @@ -99,6 +100,7 @@ mod tests { let tools = agent.default_tools(); for tool in [ "AgentSpawn", + "AgentFork", "AgentSendInput", "AgentControl", "AgentList", diff --git a/src/crates/assembly/core/src/agentic/agents/mod.rs b/src/crates/assembly/core/src/agentic/agents/mod.rs index 792d527d45..5380b55ef7 100644 --- a/src/crates/assembly/core/src/agentic/agents/mod.rs +++ b/src/crates/assembly/core/src/agentic/agents/mod.rs @@ -87,6 +87,7 @@ static EMPTY_PERMISSION_CONSTRAINTS: std::sync::LazyLock Vec { vec![ "AgentSpawn".to_string(), + "AgentFork".to_string(), "AgentSendInput".to_string(), "AgentControl".to_string(), "AgentList".to_string(), @@ -288,6 +289,7 @@ mod tests { for collaboration_tool in [ "AgentSpawn", + "AgentFork", "AgentSendInput", "AgentControl", "AgentList", diff --git a/src/crates/assembly/core/src/agentic/agents/registry/query.rs b/src/crates/assembly/core/src/agentic/agents/registry/query.rs index 2815bdece9..ba490664e4 100644 --- a/src/crates/assembly/core/src/agentic/agents/registry/query.rs +++ b/src/crates/assembly/core/src/agentic/agents/registry/query.rs @@ -83,7 +83,7 @@ impl AgentRegistry { self.get_agent_tools(agent_type, workspace_id) .await .iter() - .any(|tool| matches!(tool.as_str(), "AgentSpawn" | "Task")) + .any(|tool| matches!(tool.as_str(), "AgentSpawn" | "AgentFork" | "Task")) } /// Return every effective local agent definition that can participate in diff --git a/src/crates/assembly/core/src/agentic/coordination/coordinator.rs b/src/crates/assembly/core/src/agentic/coordination/coordinator.rs index 63d7561e23..c7b8690235 100644 --- a/src/crates/assembly/core/src/agentic/coordination/coordinator.rs +++ b/src/crates/assembly/core/src/agentic/coordination/coordinator.rs @@ -874,7 +874,7 @@ fn external_delegation_agent_id(logical_id: &str, invocation_id: &uuid::Uuid) -> } fn fork_subagent_system_reminder() -> String { - "You are now running as a forked subagent. Messages before this reminder were inherited from the parent agent as context. Messages after this reminder are the request for you. Do not call the Task tool to launch another subagent. Use the tools available to complete the task directly.".to_string() + "You are now running as a forked subagent. Messages before this reminder were inherited from the parent agent as context. Messages after this reminder are the request for you. Do not launch another subagent. Use the tools available to complete the task directly.".to_string() } fn session_created_by_parent(session: &Session, parent_session_id: &str) -> bool { @@ -13016,8 +13016,10 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet context: request.context, permission_runtime_ceiling: Some(request.permission_runtime_ceiling), delegation_policy: request.delegation_policy, + // Keep the inherited tool definitions cacheable. The launch tools + // enforce the child's delegation policy when invoked. runtime_tool_restrictions: runtime_tool_restrictions_for_session_lifetime( - runtime_tool_restrictions_for_delegation_policy(request.delegation_policy), + ToolRuntimeRestrictions::default(), parent_transient, ), prompt_cache_source_session_id: Some(snapshot.parent_session_id), @@ -25201,6 +25203,12 @@ pub(crate) mod tests { .expect("fork request should inherit the parent model"); assert_eq!(prepared.session_config.model_id.as_deref(), Some("primary")); + for tool_name in ["Task", "AgentSpawn", "AgentFork"] { + assert!(prepared + .runtime_tool_restrictions + .is_tool_allowed(tool_name)); + } + assert!(!prepared.delegation_policy.allow_subagent_spawn); } #[tokio::test] diff --git a/src/crates/assembly/core/src/agentic/tools/agent-tool-exposure.md b/src/crates/assembly/core/src/agentic/tools/agent-tool-exposure.md index 48d474807a..4315003158 100644 --- a/src/crates/assembly/core/src/agentic/tools/agent-tool-exposure.md +++ b/src/crates/assembly/core/src/agentic/tools/agent-tool-exposure.md @@ -45,6 +45,7 @@ Notes: | `ListModels` | Deferred | None | - | | `Task` | Direct | None | - | | `AgentSpawn` | Direct | None | - | +| `AgentFork` | Direct | None | - | | `AgentSendInput` | Direct | None | - | | `AgentControl` | Direct | None | - | | `AgentList` | Direct | None | - | diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/agent_control.rs b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/agent_control.rs index e397a00474..6a7f66b4e6 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/agent_control.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/agent_control.rs @@ -1,6 +1,7 @@ use super::*; const AGENT_SPAWN_FIELDS: &[&str] = &["agent_id", "prompt", "agent_type", "model_id"]; +const AGENT_FORK_FIELDS: &[&str] = &["agent_id", "prompt", "model_id"]; const AGENT_SEND_INPUT_FIELDS: &[&str] = &["agent_id", "prompt", "model_id"]; fn input_object<'a>( @@ -246,6 +247,112 @@ impl Tool for AgentSpawnTool { } } +impl Default for AgentForkTool { + fn default() -> Self { + Self::new() + } +} + +impl AgentForkTool { + pub fn new() -> Self { + Self + } + + pub(super) fn task_input(input: &Value) -> OpenBitFunResult { + let object = input_object(input, "AgentFork", AGENT_FORK_FIELDS)?; + let agent_id = required_string(object, "agent_id", "AgentFork")?; + let raw_agent_id = object["agent_id"] + .as_str() + .expect("required_string already verified agent_id is a string"); + crate::agentic::coordination::validate_agent_id(raw_agent_id)?; + let prompt = required_string(object, "prompt", "AgentFork")?; + let model_id = optional_string(object, "model_id")?; + let mut task_input = json!({ + "action": "spawn", + "agent_id": agent_id, + "prompt": prompt, + "fork_context": true, + "run_in_background": true + }); + insert_optional_model_id(&mut task_input, model_id); + Ok(task_input) + } +} + +#[async_trait] +impl Tool for AgentForkTool { + fn name(&self) -> &str { + "AgentFork" + } + + fn manages_own_execution_timeout(&self) -> bool { + true + } + + async fn description(&self) -> OpenBitFunResult { + Ok(self.render_agent_fork_description(ModelOverridePolicy::presentation().await?.allowed)) + } + + fn short_description(&self) -> String { + "Launch an agent with a copy of the current conversation context.".to_string() + } + + fn input_schema(&self) -> Value { + Self::agent_fork_input_schema() + } + + async fn input_schema_for_model(&self) -> Value { + ModelOverridePolicy::model_schema(self.input_schema()).await + } + + fn output_schema(&self) -> Value { + AgentSpawnTool::new().output_schema() + } + + fn is_readonly(&self) -> bool { + false + } + + fn is_concurrency_safe(&self, _input: Option<&Value>) -> bool { + false + } + + fn permission_intents( + &self, + input: &Value, + context: &ToolUseContext, + ) -> OpenBitFunResult> { + AgentExecutionTool::new().permission_intents(&Self::task_input(input)?, context) + } + + fn render_tool_use_message(&self, input: &Value, options: &ToolRenderOptions) -> String { + AgentSpawnTool::new().render_tool_use_message(input, options) + } + + async fn validate_input( + &self, + input: &Value, + _context: Option<&ToolUseContext>, + ) -> ValidationResult { + if let Some(validation) = model_override_validation(input).await { + return validation; + } + validate_task_input(Self::task_input(input), self.name()) + } + + async fn call_impl( + &self, + input: &Value, + context: &ToolUseContext, + ) -> OpenBitFunResult> { + ModelOverridePolicy::enforce(input).await?; + let results = AgentExecutionTool::new() + .call_task_impl(&Self::task_input(input)?, context) + .await?; + Ok(AgentSpawnTool::render_results(results)) + } +} + impl Default for AgentSendInputTool { fn default() -> Self { Self::new() diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/agent_list_tool.rs b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/agent_list_tool.rs index 2bb2d77b5d..a6ef7084b8 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/agent_list_tool.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/agent_list_tool.rs @@ -52,8 +52,9 @@ impl AgentListTool { for agent_id in &reserved_ids { assistant_text.push_str(&format!("\n- {agent_id}")); } - assistant_text - .push_str("\n\nAll reserved IDs listed above are unavailable for AgentSpawn."); + assistant_text.push_str( + "\n\nAll reserved IDs listed above are unavailable for AgentSpawn and AgentFork.", + ); data["reserved_agent_ids"] = json!(reserved_ids); } Ok(vec![ToolResult::Result { @@ -106,7 +107,7 @@ impl Tool for AgentListTool { "properties": { "include_reserved": { "type": "boolean", - "description": "Defaults to false. Set to true to also return reserved historical IDs (which cannot be reused for AgentSpawn)." + "description": "Defaults to false. Set to true to also return reserved historical IDs (which cannot be reused for AgentSpawn or AgentFork)." } }, "additionalProperties": false @@ -361,9 +362,9 @@ mod tests { assert_eq!(data["reserved_agent_ids"], serde_json::json!([deleted_id])); assert!(text.contains("Reserved IDs without active agents (1):")); assert!(text.contains(&deleted_id)); - assert!( - text.contains("All reserved IDs listed above are unavailable for AgentSpawn.") - ); + assert!(text.contains( + "All reserved IDs listed above are unavailable for AgentSpawn and AgentFork." + )); } else { assert!(data.get("reserved_agent_ids").is_none()); assert!(!text.contains(&deleted_id)); diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/mod.rs b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/mod.rs index 452e28d20d..157b3b0a7e 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/mod.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/mod.rs @@ -62,6 +62,7 @@ pub use legacy_task::TaskTool; pub(crate) struct AgentExecutionTool; pub struct AgentSpawnTool; +pub struct AgentForkTool; pub struct AgentSendInputTool; const LARGE_TASK_PROMPT_SOFT_LINE_LIMIT: usize = 180; diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/schema.rs b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/schema.rs index 6b2f532303..4488661756 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/schema.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/schema.rs @@ -212,6 +212,36 @@ The result includes a `bg_task_id`. Use `bg_task_id` with AgentWait to collect t } } +impl AgentForkTool { + pub(super) fn agent_fork_input_schema() -> Value { + let mut schema = AgentSpawnTool::agent_spawn_input_schema(); + schema["properties"] + .as_object_mut() + .unwrap() + .remove("agent_type"); + schema["required"] = json!(["agent_id", "prompt"]); + schema["properties"]["prompt"]["description"] = json!("The fork's objective, scope, constraints, and expected result. May refer to the inherited conversation context."); + schema + } + + pub(super) fn render_agent_fork_description(&self, allow_model_override: bool) -> String { + let model_guidance = if allow_model_override { + "\n\nSet `model_id` only when the user explicitly requests a particular model. Omit it to use the configured subagent model. `inherit` selects the current model; `primary` and `fast` select the corresponding configured model slots. Call ListModels before using a configured model ID." + } else { + "" + }; + format!( + r#"Launch a new agent in the background with a copy of the current conversation context. Use this when the delegated work benefits from the discussion and findings already in this conversation. + +Choose a meaningful unique `agent_id` matching `[a-z][a-z0-9_-]{{0,31}}`. State the fork's objective, scope, constraints, and expected result in `prompt`. It can refer to the inherited conversation instead of repeating it. The fork runs independently after launch; later messages are not automatically shared. + +The agent shares your workspace. Give agents that may write files non-overlapping scopes so their edits and side effects do not conflict.{model_guidance} + +The result includes a `bg_task_id`. Use AgentWait with this ID to collect the result, AgentSendInput with `agent_id` to send follow-up instructions, and AgentControl to interrupt or delete the agent."# + ) + } +} + impl AgentSendInputTool { pub(super) fn agent_send_input_schema() -> Value { json!({ diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/tests.rs b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/tests.rs index d330b3c98c..854f9a320c 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/tests.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/tests.rs @@ -1,6 +1,7 @@ use super::{ execution::{requested_subagent_type_is_allowed, resolved_subagent_is_available}, - AgentExecutionTool, AgentSendInputTool, AgentSpawnTool, LaunchReviewAgentTool, TaskTool, + AgentExecutionTool, AgentForkTool, AgentSendInputTool, AgentSpawnTool, LaunchReviewAgentTool, + TaskTool, }; use crate::agentic::agents::CustomSubagentConfig; use crate::agentic::agents::{ @@ -211,6 +212,69 @@ fn split_agent_send_input_runs_in_the_background() { assert_eq!(task_input["run_in_background"], true); } +#[tokio::test] +async fn agent_fork_preserves_legacy_fork_contract_and_permissions() { + let tool = AgentForkTool::new(); + let input = json!({"agent_id":"parser-fork", "prompt":"Review the findings above", "model_id":"inherit"}); + let translated = AgentForkTool::task_input(&input).unwrap(); + let legacy = json!({"action":"spawn", "agent_id":"parser-fork", "prompt":"Review the findings above", "model_id":"inherit", "fork_context":true, "run_in_background":true}); + assert_eq!(translated, legacy); + assert_eq!( + AgentExecutionTool::context_mode_from_input(&translated).unwrap(), + openbitfun_runtime_ports::SubagentContextMode::Fork + ); + assert!(tool.validate_input(&input, None).await.result); + let context = test_tool_context("GeneralPurpose"); + assert_eq!( + serde_json::to_value(tool.permission_intents(&input, &context).unwrap()).unwrap(), + serde_json::to_value( + TaskTool::new() + .permission_intents(&legacy, &context) + .unwrap() + ) + .unwrap() + ); + assert!(!tool.is_readonly()); + assert!(!tool.is_concurrency_safe(Some(&input))); + assert!(tool.manages_own_execution_timeout()); +} + +#[tokio::test] +async fn agent_fork_rejects_invalid_ids_and_spawn_only_parameters() { + let tool = AgentForkTool::new(); + for agent_id in ["", "ParserFork", "parser fork", " parser-fork", "1fork"] { + assert!( + !tool + .validate_input(&json!({"agent_id":agent_id, "prompt":"Review"}), None) + .await + .result + ); + } + for input in [ + json!({"prompt":"Review"}), + json!({"agent_id":"review"}), + json!({"agent_id":"review", "prompt":" "}), + ] { + assert!(!tool.validate_input(&input, None).await.result); + } + for field in [ + "agent_type", + "subagent_type", + "fork_context", + "action", + "run_in_background", + ] { + let mut input = json!({"agent_id":"review", "prompt":"Review"}); + input[field] = json!("unsupported"); + assert!(!tool.validate_input(&input, None).await.result, "{field}"); + } + let schema = tool.input_schema(); + assert_eq!(schema["required"], json!(["agent_id", "prompt"])); + assert!(schema["properties"].get("agent_type").is_none()); + assert!(schema["properties"].get("fork_context").is_none()); + assert_eq!(schema["properties"].as_object().unwrap().len(), 3); +} + #[test] fn agent_send_input_tool_message_renders_the_target_agent_id() { let input = json!({ @@ -991,6 +1055,16 @@ async fn call_impl_rejects_nested_subagent_delegation() { assert!(error .to_string() .contains("Recursive subagent delegation is blocked. Use direct tools instead.")); + let fork_error = AgentForkTool::new() + .call_impl( + &json!({"agent_id":"review-fork", "prompt":"Review the inherited findings"}), + &context, + ) + .await + .expect_err("forking must not bypass nested delegation restrictions"); + assert!(fork_error + .to_string() + .contains("Recursive subagent delegation is blocked")); } #[test] @@ -2313,6 +2387,7 @@ fn deep_review_retry_scope_prompt_prepend_bounds_review_files() { fn collaboration_model_policy_tools() -> Vec> { vec![ Box::new(AgentSpawnTool::new()), + Box::new(AgentForkTool::new()), Box::new(AgentSendInputTool::new()), Box::new(TaskTool::new()), Box::new(LaunchReviewAgentTool::new()), @@ -2481,12 +2556,16 @@ async fn subagent_model_override_policy_reaches_native_and_host_catalogs() { assert!(info.input_schema["properties"].get("model_id").is_none()); assert!(!info.description.contains("model_id")); let manifest = resolve_product_resolved_tool_manifest( - &["AgentSpawn".into(), "AgentSendInput".into()], + &[ + "AgentSpawn".into(), + "AgentFork".into(), + "AgentSendInput".into(), + ], &Default::default(), &context, ) .await; - for name in ["AgentSpawn", "AgentSendInput"] { + for name in ["AgentSpawn", "AgentFork", "AgentSendInput"] { let definition = manifest .tool_definitions .iter() @@ -2515,13 +2594,18 @@ async fn subagent_model_override_policy_reaches_ptc_bindings() { TEST_MODEL_OVERRIDE .scope(allowed, async { let manifest = resolve_product_resolved_tool_manifest( - &["AgentSpawn".into(), "AgentSendInput".into()], + &[ + "AgentSpawn".into(), + "AgentFork".into(), + "AgentSendInput".into(), + ], &Default::default(), &context, ) .await; let guide = manifest.ptc_tool_calling_guide.unwrap(); assert!(guide.contains("AgentSpawn")); + assert!(guide.contains("AgentFork")); assert_eq!(guide.contains("model_id"), allowed); }) .await; diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/mod.rs b/src/crates/assembly/core/src/agentic/tools/implementations/mod.rs index dd16dc7587..d3016758c6 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/mod.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/mod.rs @@ -89,8 +89,8 @@ pub mod worktree_tool; pub use crate::agentic::tools::product_runtime::GetToolSpecTool; pub(crate) use agent_collaboration::AgentExecutionTool; pub use agent_collaboration::{ - AgentControlTool, AgentListTool, AgentSendInputTool, AgentSpawnTool, AgentWaitTool, - LaunchReviewAgentTool, TaskTool, + AgentControlTool, AgentForkTool, AgentListTool, AgentSendInputTool, AgentSpawnTool, + AgentWaitTool, LaunchReviewAgentTool, TaskTool, }; #[cfg(feature = "tools-image-analysis")] pub use analyze_image_tool::AnalyzeImageTool; diff --git a/src/crates/assembly/core/src/agentic/tools/pipeline/tool_pipeline.rs b/src/crates/assembly/core/src/agentic/tools/pipeline/tool_pipeline.rs index 0ef8cc41fa..dc41aa4c24 100644 --- a/src/crates/assembly/core/src/agentic/tools/pipeline/tool_pipeline.rs +++ b/src/crates/assembly/core/src/agentic/tools/pipeline/tool_pipeline.rs @@ -767,7 +767,7 @@ fn permission_decision_input( } } -const SUBAGENT_LAUNCH_TOOL_NAMES: &[&str] = &["Task", "AgentSpawn"]; +const SUBAGENT_LAUNCH_TOOL_NAMES: &[&str] = &["Task", "AgentSpawn", "AgentFork"]; /// Native hook session facts derived from one tool task. fn native_hook_session_facts<'a>( diff --git a/src/crates/assembly/core/src/agentic/tools/product_runtime.rs b/src/crates/assembly/core/src/agentic/tools/product_runtime.rs index 3553c36fa9..3218030533 100644 --- a/src/crates/assembly/core/src/agentic/tools/product_runtime.rs +++ b/src/crates/assembly/core/src/agentic/tools/product_runtime.rs @@ -299,6 +299,7 @@ mod baseline_tests { "Read", "Task", "AgentSpawn", + "AgentFork", "ListWorkspaces", "SessionControl", "Cron", diff --git a/src/crates/assembly/core/src/agentic/tools/product_runtime/materialization.rs b/src/crates/assembly/core/src/agentic/tools/product_runtime/materialization.rs index 8124559032..0ddebf890b 100644 --- a/src/crates/assembly/core/src/agentic/tools/product_runtime/materialization.rs +++ b/src/crates/assembly/core/src/agentic/tools/product_runtime/materialization.rs @@ -35,6 +35,7 @@ const PRODUCT_TOOL_REGISTRATION_ORDER: &[&str] = &[ "ListModels", "Task", "AgentSpawn", + "AgentFork", "AgentSendInput", "AgentControl", "AgentList", @@ -127,6 +128,7 @@ impl StaticToolProviderFactory for ProductConcreteToolFactory { "OpenBitFunControl" => Some(Arc::new(OpenBitFunControlTool::new())), "Task" => Some(Arc::new(TaskTool::new())), "AgentSpawn" => Some(Arc::new(AgentSpawnTool::new())), + "AgentFork" => Some(Arc::new(AgentForkTool::new())), "AgentSendInput" => Some(Arc::new(AgentSendInputTool::new())), "AgentControl" => Some(Arc::new(AgentControlTool::new())), "AgentList" => Some(Arc::new(AgentListTool::new())), diff --git a/src/crates/assembly/core/src/agentic/tools/registry.rs b/src/crates/assembly/core/src/agentic/tools/registry.rs index b8a00f3b89..86519d6401 100644 --- a/src/crates/assembly/core/src/agentic/tools/registry.rs +++ b/src/crates/assembly/core/src/agentic/tools/registry.rs @@ -584,6 +584,7 @@ mod tests { "ListModels", "Task", "AgentSpawn", + "AgentFork", "AgentSendInput", "AgentControl", "AgentList", diff --git a/src/crates/contracts/product-domains/src/generated/product-control-catalog.json b/src/crates/contracts/product-domains/src/generated/product-control-catalog.json index 80c8e3332d..30197834b2 100644 --- a/src/crates/contracts/product-domains/src/generated/product-control-catalog.json +++ b/src/crates/contracts/product-domains/src/generated/product-control-catalog.json @@ -4,7 +4,7 @@ "title": "OpenBitFun Playbook", "origin": "https://playbook.openbitfun.com", "source": "src/shared/interactive-capabilities/catalog.json", - "digest": "fe4be08cb20c2d67857891380d223a77d420345b94e2733d0000d14485027697", + "digest": "408cc52581d52de1e3686853eec8a09b2c02129869cb82b2931e21694e10557b", "ownerDigest": "1fdb9c49d404c02483c08e1e0fe9effa0aaa4f0f2914578bcaa63e04de16cc16", "searchAcceptance": [ { @@ -1917,6 +1917,7 @@ }, "delegateTools": [ "AgentSpawn", + "AgentFork", "AgentWait", "AgentSendInput", "AgentControl", @@ -23174,6 +23175,7 @@ "kind": "delegate", "tools": [ "AgentSpawn", + "AgentFork", "AgentWait", "AgentSendInput", "AgentControl", @@ -23269,6 +23271,7 @@ "Spawn parallel subagents to audit error handling across auth, billing, and gateway, then synthesize the findings", "Help me draft a read-only subagent specialized in reviewing SQL migration safety", "AgentSpawn", + "AgentFork", "AgentWait", "AgentSendInput", "AgentControl", diff --git a/src/crates/execution/agent-runtime/src/custom_agent.rs b/src/crates/execution/agent-runtime/src/custom_agent.rs index 99ab417f9f..80078c8ab0 100644 --- a/src/crates/execution/agent-runtime/src/custom_agent.rs +++ b/src/crates/execution/agent-runtime/src/custom_agent.rs @@ -19,6 +19,7 @@ pub const DEFAULT_CUSTOM_MODE_TOOLS: &[&str] = &[ "WriteStdin", "ExecControl", "AgentSpawn", + "AgentFork", "AgentSendInput", "AgentControl", "AgentList", diff --git a/src/crates/execution/agent-runtime/tests/agent_definition_contracts/custom_agent_mode_contracts.rs b/src/crates/execution/agent-runtime/tests/agent_definition_contracts/custom_agent_mode_contracts.rs index 99793ad517..ec39cb4c9d 100644 --- a/src/crates/execution/agent-runtime/tests/agent_definition_contracts/custom_agent_mode_contracts.rs +++ b/src/crates/execution/agent-runtime/tests/agent_definition_contracts/custom_agent_mode_contracts.rs @@ -76,6 +76,7 @@ fn custom_mode_defaults_generate_id_and_default_policy() { } for tool_name in [ "AgentSpawn", + "AgentFork", "AgentSendInput", "AgentControl", "AgentList", diff --git a/src/crates/execution/tool-contracts/src/framework.rs b/src/crates/execution/tool-contracts/src/framework.rs index 006314138a..f125749b60 100644 --- a/src/crates/execution/tool-contracts/src/framework.rs +++ b/src/crates/execution/tool-contracts/src/framework.rs @@ -639,7 +639,7 @@ fn escape_get_tool_spec_xml_text(value: &str) -> String { pub fn tool_manifest_sort_rank(tool_name: &str) -> usize { match tool_name { - "AgentSpawn" => 1, + "AgentSpawn" | "AgentFork" => 1, "AgentSendInput" => 1, "AgentControl" => 1, "AgentWait" => 1, @@ -2460,7 +2460,7 @@ pub fn tool_restrictions_for_delegation_policy( ) -> ToolRuntimeRestrictions { let mut restrictions = ToolRuntimeRestrictions::default(); if !delegation_policy.allow_subagent_spawn { - for tool_name in ["AgentSpawn"] { + for tool_name in ["AgentSpawn", "AgentFork"] { restrictions.denied_tool_names.insert(tool_name.to_string()); restrictions.denied_tool_messages.insert( tool_name.to_string(), @@ -2750,6 +2750,11 @@ mod tests { tool_restrictions_for_delegation_policy(DelegationPolicy::top_level().spawn_child()); assert!(!restrictions.is_tool_allowed("AgentSpawn")); + assert!(!restrictions.is_tool_allowed("AgentFork")); + assert!( + tool_restrictions_for_delegation_policy(DelegationPolicy::top_level()) + .is_tool_allowed("AgentFork") + ); assert!(restrictions.is_tool_allowed("Read")); assert_eq!( restrictions diff --git a/src/crates/execution/tool-execution/src/pipeline.rs b/src/crates/execution/tool-execution/src/pipeline.rs index 298f4cd10c..2f19e71cad 100644 --- a/src/crates/execution/tool-execution/src/pipeline.rs +++ b/src/crates/execution/tool-execution/src/pipeline.rs @@ -198,7 +198,7 @@ pub fn tool_call_concurrency_safe_for_batch( same_batch_subagent_call_count: usize, subagent_batch_execution_policy: SubagentBatchExecutionPolicy, ) -> bool { - if tool_name != "AgentSpawn" { + if !matches!(tool_name, "AgentSpawn" | "AgentFork") { return tool_is_concurrency_safe; } diff --git a/src/crates/execution/tool-execution/tests/tool_pipeline_planning.rs b/src/crates/execution/tool-execution/tests/tool_pipeline_planning.rs index 0710e0609f..e811a70c4e 100644 --- a/src/crates/execution/tool-execution/tests/tool_pipeline_planning.rs +++ b/src/crates/execution/tool-execution/tests/tool_pipeline_planning.rs @@ -111,6 +111,28 @@ fn retry_policy_preserves_attempt_limit_and_error_class_contract() { assert_eq!(retry_delay_ms(2), 200); } +#[test] +fn agent_fork_respects_subagent_batch_policy() { + assert!(!tool_call_concurrency_safe_for_batch( + "AgentFork", + false, + 2, + SubagentBatchExecutionPolicy::SafeOnly + )); + assert!(!tool_call_concurrency_safe_for_batch( + "AgentFork", + false, + 2, + SubagentBatchExecutionPolicy::Serial + )); + assert!(tool_call_concurrency_safe_for_batch( + "AgentFork", + false, + 2, + SubagentBatchExecutionPolicy::ForceParallel + )); +} + #[test] fn cancellation_policy_preserves_cancellable_and_terminal_state_contract() { assert!(should_cancel_tool_state(ToolTaskStateKind::Queued)); diff --git a/src/crates/execution/tool-provider-groups/src/lib.rs b/src/crates/execution/tool-provider-groups/src/lib.rs index 962d71dc9d..cb45985b49 100644 --- a/src/crates/execution/tool-provider-groups/src/lib.rs +++ b/src/crates/execution/tool-provider-groups/src/lib.rs @@ -115,14 +115,12 @@ pub fn tool_feature_group(tool_name: &str) -> Option { "generate_image" => Some(ToolPackFeatureGroup::ImageGeneration), "GenOfficeFile" => Some(ToolPackFeatureGroup::OfficeDocuments), "GenerativeUI" | "InitMiniApp" | "FinalizeMiniApp" | "PublishMiniApp" - | "MiniAppBrowser" | "Playbook" => { - Some(ToolPackFeatureGroup::MiniApp) - } + | "MiniAppBrowser" | "Playbook" => Some(ToolPackFeatureGroup::MiniApp), "PageManage" | "PageDeploy" | "PagePublish" => Some(ToolPackFeatureGroup::Pages), "FrontendWorkbench" => Some(ToolPackFeatureGroup::Creation), - "Task" | "AgentSpawn" | "AgentSendInput" | "AgentControl" | "AgentList" | "AgentWait" - | "LaunchReviewAgent" | "Skill" | "AskUserQuestion" | "TodoWrite" | "get_goal" - | "create_goal" | "update_goal" | "submit_code_review" | "GetToolSpec" + "Task" | "AgentSpawn" | "AgentFork" | "AgentSendInput" | "AgentControl" | "AgentList" + | "AgentWait" | "LaunchReviewAgent" | "Skill" | "AskUserQuestion" | "TodoWrite" + | "get_goal" | "create_goal" | "update_goal" | "submit_code_review" | "GetToolSpec" | "CallDeferredTool" | "ListWorkspaces" | "SessionControl" | "SessionMessage" | "SessionHistory" | "Cron" | "PortForward" | "DesktopCard" | "OpenBitFunControl" => { Some(ToolPackFeatureGroup::AgentControl) @@ -209,6 +207,7 @@ const PRODUCT_TOOL_PROVIDER_GROUP_PLAN: &[ToolProviderGroupPlan] = &[ tool_names: &[ "Task", "AgentSpawn", + "AgentFork", "AgentSendInput", "AgentControl", "AgentList", @@ -572,6 +571,7 @@ mod tests { "ListModels", "Task", "AgentSpawn", + "AgentFork", "AgentSendInput", "AgentControl", "AgentList", diff --git a/src/crates/services/services-integrations/src/remote_connect.rs b/src/crates/services/services-integrations/src/remote_connect.rs index a90e9ad0f8..fbd895ac12 100644 --- a/src/crates/services/services-integrations/src/remote_connect.rs +++ b/src/crates/services/services-integrations/src/remote_connect.rs @@ -2647,6 +2647,7 @@ pub fn build_remote_chat_messages(turns: Vec) -> Vec { /** * Collect subagent internal items into the agent launch item's subItems field. - * When an AgentSpawn (or legacy Task) tool appears, subsequent subagent items + * When an AgentSpawn, AgentFork (or legacy Task) tool appears, subsequent subagent items * are attached for nested rendering. */ function filterSubagentItems(items: ChatMessageItem[]): ChatMessageItem[] { @@ -723,7 +723,7 @@ function filterSubagentItems(items: ChatMessageItem[]): ChatMessageItem[] { let currentTaskItem: ChatMessageItem | null = null; for (const item of items) { - if (item.type === 'tool' && ['Task', 'AgentSpawn'].includes(item.tool?.name ?? '')) { + if (item.type === 'tool' && ['Task', 'AgentSpawn', 'AgentFork'].includes(item.tool?.name ?? '')) { const taskCopy: ChatMessageItem = { ...item, subItems: [] }; result.push(taskCopy); currentTaskItem = taskCopy; @@ -862,12 +862,12 @@ function renderStandardGroups( const flushAll = () => { flushRead(); flushRegular(); }; for (const entry of g.entries) { - if (entry.tool && !['Task', 'AgentSpawn'].includes(entry.tool.name) && isToolAwaitingApproval(entry.tool)) { + if (entry.tool && !['Task', 'AgentSpawn', 'AgentFork'].includes(entry.tool.name) && isToolAwaitingApproval(entry.tool)) { flushAll(); rendered.push( , ); - } else if (entry.tool && ['Task', 'AgentSpawn'].includes(entry.tool.name)) { + } else if (entry.tool && ['Task', 'AgentSpawn', 'AgentFork'].includes(entry.tool.name)) { flushAll(); rendered.push( , @@ -1205,13 +1205,13 @@ const ChatTranscript: React.FC = ({ ); } - const taskTools = activeTurn.tools.filter((tool) => ['Task', 'AgentSpawn'].includes(tool.name)); + const taskTools = activeTurn.tools.filter((tool) => ['Task', 'AgentSpawn', 'AgentFork'].includes(tool.name)); const hasRunningSubagent = taskTools.some((tool) => tool.status === 'running'); const askTools = activeTurn.tools.filter( (tool) => tool.name === 'AskUserQuestion' && tool.status === 'running' && tool.tool_input, ); const askToolIds = new Set(askTools.map((tool) => tool.id)); - const regularTools = activeTurn.tools.filter((tool) => !['Task', 'AgentSpawn'].includes(tool.name) && !askToolIds.has(tool.id)); + const regularTools = activeTurn.tools.filter((tool) => !['Task', 'AgentSpawn', 'AgentFork'].includes(tool.name) && !askToolIds.has(tool.id)); const subItemsForTask: ChatMessageItem[] = hasRunningSubagent ? [ ...(activeTurn.thinking ? [{ type: 'thinking' as const, content: activeTurn.thinking }] : []), diff --git a/src/mobile-web/tests/helpers/mobile-chat-regressions-fixture.tsx b/src/mobile-web/tests/helpers/mobile-chat-regressions-fixture.tsx index 0e396ce8fb..29c29ceb5d 100644 --- a/src/mobile-web/tests/helpers/mobile-chat-regressions-fixture.tsx +++ b/src/mobile-web/tests/helpers/mobile-chat-regressions-fixture.tsx @@ -9,7 +9,7 @@ import '@openbitfun/ui/mobile.css'; import '../../src/styles/index.scss'; let root: ReturnType; -export function showTranscript(approval = false, variant: 'legacy' | 'ordered' | 'subagent' = 'legacy', taskStatus: RemoteToolStatus['status'] = 'completed') { +export function showTranscript(approval = false, variant: 'legacy' | 'ordered' | 'subagent' = 'legacy', taskStatus: RemoteToolStatus['status'] = 'completed', launchTool = 'Task') { if (!root) { document.body.innerHTML = '
'; root = createRoot(document.querySelector('#transcript-fixture')!); @@ -24,7 +24,7 @@ export function showTranscript(approval = false, variant: 'legacy' | 'ordered' | tools.forEach((tool, index) => { tool.name = 'Read'; if (index === 3) tool.status = 'cancelled'; }); items = tools.map(tool => ({ type: 'tool', tool })); } else if (variant === 'subagent') { - const task: RemoteToolStatus = { id: 'task', name: 'Task', status: taskStatus }; + const task: RemoteToolStatus = { id: 'task', name: launchTool, status: taskStatus }; displayedTools = [task, ...tools]; items = [{ type: 'tool', tool: task }, ...tools.map(tool => ({ type: 'tool', tool, is_subagent: true }))]; } diff --git a/src/mobile-web/tests/mobile-chat-regressions-browser.test.mjs b/src/mobile-web/tests/mobile-chat-regressions-browser.test.mjs index e57b8e69d5..d47808871e 100644 --- a/src/mobile-web/tests/mobile-chat-regressions-browser.test.mjs +++ b/src/mobile-web/tests/mobile-chat-regressions-browser.test.mjs @@ -69,3 +69,23 @@ test('message times and quiet tool failures work at compact and wide sizes', { t assert.equal(await page.$('.chat-tool-list--collapsed'), null, 'approval stays reachable'); } finally { await browser.close(); await source.close(); } }); + +test('agent launch tools retain their child branch cards', { timeout: 60000 }, async () => { + const source = await startSourceServer(); + const browser = await launchBrowser(); + try { + const page = await browser.newPage(); + await page.goto(source.origin); + for (const width of [390, 1280]) { + await page.setViewport({ width, height: 844 }); + for (const launchTool of ['AgentSpawn', 'AgentFork']) { + await page.evaluate(async name => (await import('/tests/helpers/mobile-chat-regressions-fixture.tsx')).showTranscript(false, 'subagent', 'completed', name), launchTool); + await page.waitForSelector('.chat-task-card'); + assert.equal(await page.$$eval('.chat-task-card', nodes => nodes.length), 1, launchTool); + } + } + } finally { + await browser.close(); + await source.close(); + } +}); diff --git a/src/shared/interactive-capabilities/catalog.json b/src/shared/interactive-capabilities/catalog.json index 5155d8ad0b..da4bf3ecb1 100644 --- a/src/shared/interactive-capabilities/catalog.json +++ b/src/shared/interactive-capabilities/catalog.json @@ -1592,6 +1592,7 @@ "kind": "delegate", "tools": [ "AgentSpawn", + "AgentFork", "AgentWait", "AgentSendInput", "AgentControl", diff --git a/src/web-ui/README.md b/src/web-ui/README.md index b43f90b286..50b38453b9 100644 --- a/src/web-ui/README.md +++ b/src/web-ui/README.md @@ -607,7 +607,7 @@ and device-switch contracts; live remote and native visual checks remain manual. In **Settings → Execution → Subagents**, **Allow agents to choose subagent models** controls `ai.allow_subagent_model_override` on the executing host. It defaults to -`true`, including when loading older configurations. When disabled, AgentSpawn, +`true`, including when loading older configurations. When disabled, AgentSpawn, AgentFork, AgentSendInput, legacy Task and LaunchReviewAgent omit `model_id` from model-facing schemas and related instructions. Calls that still supply the field fail before launching or switching a subagent; remove the argument to use configured models. @@ -620,3 +620,10 @@ mobile/IM controllers and detached jobs use the execution host's policy. In Peer Device Mode, the setting belongs to the peer; hosts must advertise `subagent_model_override_policy_v1`. Older hosts show an unsupported setting rather than saving a value they cannot enforce. + +`AgentFork` launches a background agent with a copy of the current conversation +context and the current agent type. It takes `agent_id`, `prompt`, and optionally +`model_id`; it does not accept `agent_type`. Use `AgentSpawn` for a fresh specialist +conversation. Both return `bg_task_id` and support the existing AgentWait, +AgentSendInput, and AgentControl workflow. Forks retain the existing workspace, +permission, and nested-delegation constraints. diff --git a/src/web-ui/src/app/global-search/generated/interactive-capabilities.json b/src/web-ui/src/app/global-search/generated/interactive-capabilities.json index c7394af2a4..14366fee78 100644 --- a/src/web-ui/src/app/global-search/generated/interactive-capabilities.json +++ b/src/web-ui/src/app/global-search/generated/interactive-capabilities.json @@ -4,7 +4,7 @@ "title": "OpenBitFun Playbook", "origin": "https://playbook.openbitfun.com", "source": "src/shared/interactive-capabilities/catalog.json", - "digest": "fe4be08cb20c2d67857891380d223a77d420345b94e2733d0000d14485027697", + "digest": "408cc52581d52de1e3686853eec8a09b2c02129869cb82b2931e21694e10557b", "ownerDigest": "1fdb9c49d404c02483c08e1e0fe9effa0aaa4f0f2914578bcaa63e04de16cc16", "searchAcceptance": [ { @@ -1917,6 +1917,7 @@ }, "delegateTools": [ "AgentSpawn", + "AgentFork", "AgentWait", "AgentSendInput", "AgentControl", @@ -23170,6 +23171,7 @@ "kind": "delegate", "tools": [ "AgentSpawn", + "AgentFork", "AgentWait", "AgentSendInput", "AgentControl", @@ -23265,6 +23267,7 @@ "Spawn parallel subagents to audit error handling across auth, billing, and gateway, then synthesize the findings", "Help me draft a read-only subagent specialized in reviewing SQL migration safety", "AgentSpawn", + "AgentFork", "AgentWait", "AgentSendInput", "AgentControl", diff --git a/src/web-ui/src/app/scenes/agents/components/CreateAgentPage.tsx b/src/web-ui/src/app/scenes/agents/components/CreateAgentPage.tsx index 93a3485cc2..d35d98ea64 100644 --- a/src/web-ui/src/app/scenes/agents/components/CreateAgentPage.tsx +++ b/src/web-ui/src/app/scenes/agents/components/CreateAgentPage.tsx @@ -52,6 +52,7 @@ const DEFAULT_CUSTOM_MODE_TOOLS = [ 'WriteStdin', 'ExecControl', 'AgentSpawn', + 'AgentFork', 'AgentSendInput', 'AgentControl', 'AgentWait', diff --git a/src/web-ui/src/app/scenes/agents/components/toolGroups.ts b/src/web-ui/src/app/scenes/agents/components/toolGroups.ts index 11b8dfefd8..ae79404268 100644 --- a/src/web-ui/src/app/scenes/agents/components/toolGroups.ts +++ b/src/web-ui/src/app/scenes/agents/components/toolGroups.ts @@ -48,7 +48,7 @@ const BUILTIN_TOOL_GROUPS: BuiltinToolGroupDefinition[] = [ { id: 'builtin:delegation', labelKey: 'agentsOverview.toolGroups.delegation', - toolNames: ['AgentSpawn', 'AgentSendInput', 'AgentControl', 'AgentList', 'ListModels', 'AgentWait', 'Skill'], + toolNames: ['AgentSpawn', 'AgentFork', 'AgentSendInput', 'AgentControl', 'AgentList', 'ListModels', 'AgentWait', 'Skill'], }, { id: 'builtin:web', diff --git a/src/web-ui/src/app/scenes/settings/pages/ai/ExecutionSettingsPage.tsx b/src/web-ui/src/app/scenes/settings/pages/ai/ExecutionSettingsPage.tsx index 77f953b6b8..095372d18a 100644 --- a/src/web-ui/src/app/scenes/settings/pages/ai/ExecutionSettingsPage.tsx +++ b/src/web-ui/src/app/scenes/settings/pages/ai/ExecutionSettingsPage.tsx @@ -43,6 +43,7 @@ type DescribedSelectOption = SelectOption & { description?: string }; const log = createLogger('ExecutionSettingsPage'); type SubagentBatchExecutionPolicy = 'safe_only' | 'force_parallel' | 'serial'; +type SubagentModelSetting = 'default' | 'fork'; type ToolPresentationMode = 'native' | 'ptc' | 'ptc_python'; const DEFAULT_SUBAGENT_BATCH_EXECUTION_POLICY: SubagentBatchExecutionPolicy = 'force_parallel'; @@ -77,7 +78,9 @@ const ExecutionSettingsPage: React.FC = () => { catch { /* The strict read below surfaces malformed or missing settings. */ } } const hasSeededPageData = seed.loaded && Boolean(seededSelections); - const [subagentDefaultModel, setSubagentDefaultModel] = useState(() => seededSelections?.subagents.default ?? { kind: 'inherit' }); + const [subagentModels, setSubagentModels] = useState>(() => + seededSelections?.subagents ?? { default: { kind: 'inherit' }, fork: { kind: 'inherit' } } + ); const [modelPools, setModelPools] = useState(() => { const document = seed.get('ai.model_pools', null); return document ? readableModelPools(document) : []; @@ -190,8 +193,6 @@ const ExecutionSettingsPage: React.FC = () => { } }; - const subagentModelValue = JSON.stringify(subagentDefaultModel); - const subagentModelOptions: ComboboxOption[] = [ { value: JSON.stringify({ kind: 'inherit' }), label: tTools('config.subagentModelInherit') }, { value: JSON.stringify({ kind: 'model', model_ref: 'fast' }), label: tModels('sessionTitle.model.fast') }, @@ -200,23 +201,23 @@ const ExecutionSettingsPage: React.FC = () => { ...(supportsModelPools() ? modelPools.map(pool => ({ value: JSON.stringify({ kind: 'pool', pool_id: pool.id }), label: pool.name, description: tModels('pools.title') })) : []), ]; - const handleSubagentDefaultModelChange = async (value: string | number) => { + const handleSubagentModelChange = async (setting: SubagentModelSetting, value: string | number) => { const scope = getActiveSurfaceScope(); const selection = JSON.parse(String(value)) as AgentModelTargetSelection; setToolExecConfigLoading(true); try { if (modelSelectionsConfigPath() === 'ai.agent_model_selections') { - await configManager.setConfig('ai.agent_model_selections.subagents.default', selection); + await configManager.setConfig(`ai.agent_model_selections.subagents.${setting}`, selection); } else { if (selection.kind === 'pool') throw new Error('This host does not support model_pool_selection_v1'); - await configManager.setConfig('ai.agent_model_defaults.subagents.default', selection.kind === 'inherit' ? selection : { kind: 'fixed', model_id: selection.model_ref }); + await configManager.setConfig(`ai.agent_model_defaults.subagents.${setting}`, selection.kind === 'inherit' ? selection : { kind: 'fixed', model_id: selection.model_ref }); } if (!scope.isCurrent()) return; - setSubagentDefaultModel(selection); + setSubagentModels(previous => ({ ...previous, [setting]: selection })); notificationService.success(tTools('messages.saveSuccess'), { duration: 2000 }); } catch (error) { if (!scope.isCurrent()) return; - log.error('Failed to save default subagent model', error); + log.error('Failed to save subagent model selection', { setting, error }); notificationService.error( `${tTools('messages.saveFailed')}: ${error instanceof Error ? error.message : String(error)}` ); @@ -306,11 +307,12 @@ const ExecutionSettingsPage: React.FC = () => { }; const loadPageData = useCallback(async () => { + const scope = getActiveSurfaceScope(); const isInitialLoad = !hasLoadedPageDataRef.current; if (isInitialLoad) { setIsLoading(true); setLoadError(false); } try { const [ - loadedSubagentDefaultModel, + loadedModelSelections, loadedModels, deferredToolLoadingEnabled, loadedSubagentMaxConcurrency, @@ -332,7 +334,8 @@ const ExecutionSettingsPage: React.FC = () => { configManager.getOptionalConfig('ai.tool_presentation_mode'), supportsModelPools() ? configManager.getOptionalConfig('ai.model_pools') : Promise.resolve(undefined), ]); - setSubagentDefaultModel(loadedSubagentDefaultModel.subagents.default); + if (!scope.isCurrent()) return; + setSubagentModels(loadedModelSelections.subagents); setModelPools(poolDocument ? readableModelPools(poolDocument) : []); setConfiguredModels(loadedModels ?? []); setEnableDeferredToolLoading(deferredToolLoadingEnabled ?? true); @@ -355,10 +358,11 @@ const ExecutionSettingsPage: React.FC = () => { hasLoadedPageDataRef.current = true; } catch (error) { + if (!scope.isCurrent()) return; log.error('Failed to load settings page data', { error }); if (isInitialLoad) setLoadError(true); } finally { - if (isInitialLoad) setIsLoading(false); + if (isInitialLoad && scope.isCurrent()) setIsLoading(false); } }, []); useEffect(() => { @@ -378,13 +382,28 @@ const ExecutionSettingsPage: React.FC = () => { return () => { active = false; }; }, [loadPageData, hasSeededPageData]); - if (!subagentModelOptions.some(option => option.value === subagentModelValue)) { - subagentModelOptions.push({ - value: subagentModelValue, - label: tModels('sessionTitle.models.unavailable', { id: subagentDefaultModel.kind === 'pool' ? subagentDefaultModel.pool_id : subagentDefaultModel.kind === 'model' ? subagentDefaultModel.model_ref : tTools('config.subagentModelInherit') }), - disabled: true, - }); - } + const renderSubagentModelControl = (setting: SubagentModelSetting, label: string) => { + const selection = subagentModels[setting]; + const value = JSON.stringify(selection); + const options = [...subagentModelOptions]; + if (!options.some(option => option.value === value)) { + const id = selection.kind === 'pool' ? selection.pool_id : selection.kind === 'model' + ? selection.model_ref : tTools('config.subagentModelInherit'); + options.push({ value, label: tModels('sessionTitle.models.unavailable', { id }), disabled: true }); + } + return ( +
+ void handleSubagentModelChange(setting, nextValue)} + /> +
+ ); + }; return ( {loadError ? ( @@ -503,15 +522,15 @@ const ExecutionSettingsPage: React.FC = () => { description={tTools('config.subagentDefaultModelDesc')} align="center" > -
- void handleSubagentDefaultModelChange(value)} - /> -
+ {renderSubagentModelControl('default', tTools('config.subagentDefaultModel'))} + + + {renderSubagentModelControl('fork', tTools('config.forkSubagentDefaultModel'))} { + request.current++; + }, []); const load = useCallback(async () => { const current = ++request.current; setError(null); @@ -39,13 +42,16 @@ export default function SubagentModelOverrideSection() { const stop = configManager.watch(subagentModelOverridePath, () => { if (!savingRef.current) void load(); }); - return () => { request.current++; stop(); }; - }, [load]); + return () => { + invalidateRequests(); + stop(); + }; + }, [invalidateRequests, load]); const ready = loaded?.epoch === scope.epoch; const save = async (allowed: boolean) => { if (!scope.isCurrent() || !ready || loaded.allowed === undefined || savingRef.current) return; - request.current++; + invalidateRequests(); savingRef.current = true; setSaving(true); setError(null); diff --git a/src/web-ui/src/app/scenes/settings/pages/shared/RuntimeSettings.test.tsx b/src/web-ui/src/app/scenes/settings/pages/shared/RuntimeSettings.test.tsx index 8b4c541cec..8c3fb30498 100644 --- a/src/web-ui/src/app/scenes/settings/pages/shared/RuntimeSettings.test.tsx +++ b/src/web-ui/src/app/scenes/settings/pages/shared/RuntimeSettings.test.tsx @@ -6,6 +6,7 @@ import DeviceControlSettingsPage from '../tools/DeviceControlSettingsPage'; import ExecutionSettingsPage from '../ai/ExecutionSettingsPage'; import WorkspaceSearchSection from '../development/WorkspaceSearchSection'; import { BROWSER_LINK_TARGET_STORAGE_KEY, browserLinkPreferenceStore } from '@/infrastructure/config/services/browserLinkPreference'; +import { activateSurface } from '@/infrastructure/peer-device/deviceSurface'; const mocks = vi.hoisted(() => { Object.defineProperty(window, '__TAURI__', { configurable: true, value: {} }); @@ -26,7 +27,19 @@ vi.mock('@/infrastructure/i18n', () => ({ vi.mock('@/infrastructure/api/service-api/ApiClient', () => ({ api: { invoke: mocks.invoke } })); vi.mock('@/infrastructure/api/service-api/SystemAPI', () => ({ systemAPI: { getSystemInfo: async () => ({ platform: 'macos' }) } })); vi.mock('../../../../../infrastructure/config/services/ConfigManager', () => ({ configManager: { hasCachedConfig: () => false, getCachedConfig: () => undefined, - getConfig: mocks.getConfig, getOptionalConfig: async (path: string) => path === 'ai.agent_model_selections' ? { mode: { kind: 'model', model_ref: 'primary' }, subagents: { default: { kind: 'model', model_ref: 'fast' }, builtin: {}, fork: { kind: 'inherit' } } } : true, setConfig: mocks.setConfig, + getConfig: mocks.getConfig, + getOptionalConfig: async (path: string) => { + if (path === 'ai.agent_model_selections') return { + mode: { kind: 'model', model_ref: 'primary' }, + subagents: { default: { kind: 'model', model_ref: 'fast' }, builtin: {}, fork: { kind: 'inherit' } }, + }; + if (path === 'ai.agent_model_defaults') return { + mode: 'primary', + subagents: { default: { kind: 'fixed', model_id: 'fast' }, builtin: {}, fork: { kind: 'fixed', model_id: 'primary' } }, + }; + return true; + }, + setConfig: mocks.setConfig, } })); vi.mock('../../../../../infrastructure/config/hooks/useComputerUseEnabled', () => ({ useComputerUseEnabled: () => ({ computerUseEnabled: false, setComputerUseEnabled: mocks.setEnabled }) })); vi.mock('../../../../../infrastructure/config/services/AIExperienceConfigService', () => ({ aiExperienceConfigService: { getCachedSettings: () => null, getSettingsAsync: async () => ({ enable_workspace_search: true }) } })); @@ -129,9 +142,32 @@ describe('Tool execution concurrency settings', () => { expect(mocks.error).toHaveBeenCalledWith('messages.saveFailed: Host rejected the concurrency setting'); }); }); +describe('Fork subagent model settings', () => { + it.each([ + ['local', 'config.subagentModelInherit', 'sessionTitle.model.primary', 'ai.agent_model_selections.subagents.fork', { kind: 'model', model_ref: 'primary' }], + ['legacy-peer', 'sessionTitle.model.primary', 'sessionTitle.model.fast', 'ai.agent_model_defaults.subagents.fork', { kind: 'fixed', model_id: 'fast' }], + ])('loads and saves the fork model independently on %s', async (surface, initialLabel, nextLabel, path, selection) => { + activateSurface(surface); + await act(async () => root.render()); + const forkModel = button('config.forkSubagentDefaultModel'); + const defaultModel = button('config.subagentDefaultModel'); + expect(forkModel.textContent).toContain(initialLabel); + expect(defaultModel.textContent).toContain('sessionTitle.model.fast'); + + await act(async () => forkModel.click()); + const nextOption = Array.from(document.querySelectorAll('[role="option"]')) + .find(option => option.textContent === nextLabel)!; + await act(async () => nextOption.click()); + + expect(mocks.setConfig.mock.calls).toEqual([[path, selection]]); + expect(forkModel.textContent).toContain(nextLabel); + expect(defaultModel.textContent).toContain('sessionTitle.model.fast'); + }); +}); afterEach(async () => { await act(async () => root.unmount()); container.remove(); + activateSurface('local'); browserLinkPreferenceStore.setState({ target: 'builtin' }); localStorage.removeItem(BROWSER_LINK_TARGET_STORAGE_KEY); }); diff --git a/src/web-ui/src/app/scenes/settings/settingsRegistry.ts b/src/web-ui/src/app/scenes/settings/settingsRegistry.ts index fe209987e1..6139712e11 100644 --- a/src/web-ui/src/app/scenes/settings/settingsRegistry.ts +++ b/src/web-ui/src/app/scenes/settings/settingsRegistry.ts @@ -284,6 +284,7 @@ export const SETTINGS_PAGE_MANIFESTS: readonly SettingsPageManifest[] = [ phrase('settings/runtime', 'toolExecution.sectionTitle'), phrase('settings/runtime', 'deferredToolLoading.sectionTitle'), phrase('settings/runtime', 'toolPresentation.mode'), + phrase('settings/agentic-tools', 'config.forkSubagentDefaultModel'), phrase('settings/review-capacity', 'capacity.title'), phrase('settings/models', 'toolArgumentJsonRepair.title'), phrase('settings/runtime', 'genui.title'), diff --git a/src/web-ui/src/flow_chat/components/FlowToolCard.tsx b/src/web-ui/src/flow_chat/components/FlowToolCard.tsx index d45f641661..7ae2972b03 100644 --- a/src/web-ui/src/flow_chat/components/FlowToolCard.tsx +++ b/src/web-ui/src/flow_chat/components/FlowToolCard.tsx @@ -73,7 +73,7 @@ const FlowToolCardCard: React.FC = React.memo(({ const CardComponent = toolItem.importedSource && !importedToolCardName(toolItem) ? DefaultToolCard : getToolCardComponent(effectiveToolItem.toolName); const interruptionNote = getToolInterruptionNote(effectiveToolItem, t); - const cardHandlesInterruptionNote = ['Task', 'AgentSpawn', 'LaunchReviewAgent'].includes(effectiveToolItem.toolName); + const cardHandlesInterruptionNote = ['Task', 'AgentSpawn', 'AgentFork', 'LaunchReviewAgent'].includes(effectiveToolItem.toolName); const toolCardTestId = effectiveToolItem.toolName === 'ExecCommand' ? 'chat-shell-tool-card' diff --git a/src/web-ui/src/flow_chat/timeline/agentCardLayout.ts b/src/web-ui/src/flow_chat/timeline/agentCardLayout.ts index 02b31cc1c5..36d0ff9ed8 100644 --- a/src/web-ui/src/flow_chat/timeline/agentCardLayout.ts +++ b/src/web-ui/src/flow_chat/timeline/agentCardLayout.ts @@ -10,7 +10,7 @@ export const AGENT_CARD_BATCH_SIZE = 6; export function isAgentLaunchCard(item: FlowItem): boolean { if (item.type !== 'tool') return false; const tool = projectEffectiveToolItem(item as FlowToolItem); - if (tool.toolName === 'AgentSpawn') return true; + if (['AgentSpawn', 'AgentFork'].includes(tool.toolName)) return true; if (!['Task', 'LaunchReviewAgent'].includes(tool.toolName)) return false; const action = (toolString(readInteractionInput(tool).action) || toolString(readToolRecord(tool.toolResult?.result).action)).toLowerCase(); diff --git a/src/web-ui/src/flow_chat/tool-cards/AgentControlToolCard.test.tsx b/src/web-ui/src/flow_chat/tool-cards/AgentControlToolCard.test.tsx index bbde8f635f..aee60862e6 100644 --- a/src/web-ui/src/flow_chat/tool-cards/AgentControlToolCard.test.tsx +++ b/src/web-ui/src/flow_chat/tool-cards/AgentControlToolCard.test.tsx @@ -115,7 +115,7 @@ const config: ToolCardConfig = { }; function agentToolItem( - toolName: 'AgentSpawn' | 'AgentSendInput', + toolName: 'AgentSpawn' | 'AgentFork' | 'AgentSendInput', overrides: Partial = {}, ): FlowToolItem { return { @@ -202,7 +202,7 @@ describeWithJsdom('AgentControlToolCard', () => { it('shows an incubating egg only for a new spawn, then stops on failure', () => { mocks.includeChildSession = false; - const render = (toolName: 'AgentSpawn' | 'AgentSendInput', status: FlowToolItem['status']) => act(() => root.render( + const render = (toolName: 'AgentSpawn' | 'AgentFork' | 'AgentSendInput', status: FlowToolItem['status']) => act(() => root.render( , )); @@ -217,7 +217,7 @@ describeWithJsdom('AgentControlToolCard', () => { expect(container.querySelector('.lucide-bot')).toBeNull(); }); - it.each(['AgentSpawn'] as const)( + it.each(['AgentSpawn', 'AgentFork'] as const)( 'opens %s directly in the side pane and never expands the prompt inline', async (toolName) => { await act(async () => root.render( diff --git a/src/web-ui/src/flow_chat/tool-cards/AgentControlToolCard.tsx b/src/web-ui/src/flow_chat/tool-cards/AgentControlToolCard.tsx index c717802105..a91713b89f 100644 --- a/src/web-ui/src/flow_chat/tool-cards/AgentControlToolCard.tsx +++ b/src/web-ui/src/flow_chat/tool-cards/AgentControlToolCard.tsx @@ -171,7 +171,7 @@ const AgentSpawnCard: React.FC = ({ ? status : statusForLifecycle(lifecycle, status); const canOpenSession = Boolean(linkedSubagentSessionId && sessionId); - const isSpawn = toolItem.toolName === 'AgentSpawn'; + const isSpawn = ['AgentSpawn', 'AgentFork'].includes(toolItem.toolName); const handleOpenSession = useCallback((event: React.MouseEvent) => { event.stopPropagation(); @@ -263,5 +263,5 @@ const AgentSpawnCard: React.FC = ({ ); }; -export const AgentControlToolCard: React.FC = props => props.toolItem.toolName === 'AgentSpawn' +export const AgentControlToolCard: React.FC = props => ['AgentSpawn', 'AgentFork'].includes(props.toolItem.toolName) ? : ; diff --git a/src/web-ui/src/flow_chat/tool-cards/builtinAgentSessions.ts b/src/web-ui/src/flow_chat/tool-cards/builtinAgentSessions.ts index b4475f983b..ed4d18d915 100644 --- a/src/web-ui/src/flow_chat/tool-cards/builtinAgentSessions.ts +++ b/src/web-ui/src/flow_chat/tool-cards/builtinAgentSessions.ts @@ -13,7 +13,7 @@ export function resolveBuiltinAgentSessions(toolItem: FlowToolItem, sessions: Fl if (candidate.id === toolItem.id) return links; if (candidate.type !== 'tool') continue; const effective = projectEffectiveToolItem(candidate); - if (!['Task', 'AgentSpawn', 'AgentSendInput'].includes(effective.toolName)) continue; + if (!['Task', 'AgentSpawn', 'AgentFork', 'AgentSendInput'].includes(effective.toolName)) continue; const input = runtimeToolRecord(effective.toolCall?.input); const data = runtimeToolRecord(effective.toolResult?.result); const agent = builtinText(data.agent_id, input.agent_id); @@ -21,7 +21,7 @@ export function resolveBuiltinAgentSessions(toolItem: FlowToolItem, sessions: Fl const session = builtinText(effective.subagentSessionId, data.session_id) ?? findProjectedSession({ sessions }, { parentSessionId, parentToolIds: new Set([candidate.id, candidate.toolCall.id]) })?.sessionId; if (session) links[agent] = session; - else if (effective.toolName === 'AgentSpawn') delete links[agent]; + else if (['AgentSpawn', 'AgentFork'].includes(effective.toolName)) delete links[agent]; } // The item is outside hydrated history, so a temporal link cannot be established. return {}; diff --git a/src/web-ui/src/flow_chat/tool-cards/index.test.ts b/src/web-ui/src/flow_chat/tool-cards/index.test.ts index 28d133c1f7..913787d288 100644 --- a/src/web-ui/src/flow_chat/tool-cards/index.test.ts +++ b/src/web-ui/src/flow_chat/tool-cards/index.test.ts @@ -47,6 +47,7 @@ describe('tool card registry', () => { it('renders AgentSpawn and AgentSendInput with the shared agent control card', () => { expect(getToolCardComponent('AgentSpawn')).toBe(AgentControlToolCard); + expect(getToolCardComponent('AgentFork')).toBe(AgentControlToolCard); expect(getToolCardComponent('AgentSendInput')).toBe(AgentControlToolCard); expect(getToolCardComponent('AgentInterrupt')).toBe(AgentInteractionToolCard); }); @@ -82,6 +83,7 @@ describe('tool card registry', () => { 'ListModels', 'ControlHub', 'AgentSpawn', + 'AgentFork', 'AgentSendInput', 'AgentInterrupt', 'AgentWait', diff --git a/src/web-ui/src/flow_chat/tool-cards/index.ts b/src/web-ui/src/flow_chat/tool-cards/index.ts index 818896ef89..7523e7aa2c 100644 --- a/src/web-ui/src/flow_chat/tool-cards/index.ts +++ b/src/web-ui/src/flow_chat/tool-cards/index.ts @@ -109,6 +109,7 @@ export const STANDARD_TOOL_CARD_ADAPTERS = { // Agent activity 'AgentSpawn': AgentControlToolCard, + 'AgentFork': AgentControlToolCard, 'AgentSendInput': AgentControlToolCard, 'AgentInterrupt': AgentInteractionToolCard, 'AgentWait': AgentWaitToolCard, diff --git a/src/web-ui/src/flow_chat/tool-cards/toolCardMetadata.ts b/src/web-ui/src/flow_chat/tool-cards/toolCardMetadata.ts index fe30455b2b..f0ce278a6a 100644 --- a/src/web-ui/src/flow_chat/tool-cards/toolCardMetadata.ts +++ b/src/web-ui/src/flow_chat/tool-cards/toolCardMetadata.ts @@ -52,6 +52,7 @@ const PROMINENT_TOOL_CARD_NAMES = new Set([ 'Task', 'LaunchReviewAgent', 'AgentSpawn', + 'AgentFork', 'submit_code_review', 'ContextCompression', 'ReviewSessionSummary', @@ -233,6 +234,16 @@ const TOOL_CARD_DEFINITIONS: Record = { displayMode: 'detailed', primaryColor: APPEARANCE_DOMAIN_TOKENS.toolIdentity.assistantAction }, + 'AgentFork': { + toolName: 'AgentFork', + displayName: 'Launch Agent', + icon: '', + requiresConfirmation: false, + resultDisplayType: 'detailed', + description: 'Launch a background agent', + displayMode: 'detailed', + primaryColor: APPEARANCE_DOMAIN_TOKENS.toolIdentity.assistantAction + }, 'AgentSendInput': { toolName: 'AgentSendInput', displayName: 'Send Agent Input', diff --git a/src/web-ui/src/flow_chat/tool-cards/toolInteractionModel.test.ts b/src/web-ui/src/flow_chat/tool-cards/toolInteractionModel.test.ts index 921f7fa304..2d0e12d6ab 100644 --- a/src/web-ui/src/flow_chat/tool-cards/toolInteractionModel.test.ts +++ b/src/web-ui/src/flow_chat/tool-cards/toolInteractionModel.test.ts @@ -22,8 +22,8 @@ describe('tool interaction history projection', () => { }))).toEqual({ agent_id: 'maintainer', prompt: 'Keep working' }); }); - it('resolves only an explicit matching agent link in the current parent history', () => { - const launch = item({ id: 'launch', toolName: 'AgentSpawn', subagentSessionId: 'remote-child' }); + it.each(['AgentSpawn', 'AgentFork'])('resolves an explicit %s link in the current parent history', (toolName) => { + const launch = item({ id: 'launch', toolName, subagentSessionId: 'remote-child' }); const unrelated = item({ id: 'other', toolName: 'AgentSpawn', subagentSessionId: 'different-child', toolCall: { id: 'other', input: { agent_id: 'triage' } } }); expect(resolveInteractionAgentSessionId(item(), parent([launch, unrelated]))).toBe('remote-child'); @@ -45,9 +45,9 @@ describe('tool interaction history projection', () => { expect(resolveInteractionAgentSessionId(send, parent([first, send, later]))).toBe('first-child'); }); - it('does not attach an unlinked relaunch or its messages to a previous child', () => { + it.each(['AgentSpawn', 'AgentFork'])('does not attach an unlinked %s or its messages to a previous child', (toolName) => { const first = item({ id: 'first-launch', toolName: 'AgentSpawn', subagentSessionId: 'first-child' }); - const relaunch = item({ id: 'new-launch', toolName: 'AgentSpawn' }); + const relaunch = item({ id: 'new-launch', toolName }); const send = item(); const history = parent([first, relaunch, send]); expect(resolveInteractionAgentSessionId(relaunch, history)).toBe(''); diff --git a/src/web-ui/src/flow_chat/tool-cards/toolInteractionModel.ts b/src/web-ui/src/flow_chat/tool-cards/toolInteractionModel.ts index c69114a502..46292f649b 100644 --- a/src/web-ui/src/flow_chat/tool-cards/toolInteractionModel.ts +++ b/src/web-ui/src/flow_chat/tool-cards/toolInteractionModel.ts @@ -58,7 +58,7 @@ export function resolveInteractionAgentSessionId( }); if (projected) return projected.sessionId; // A new launch cannot borrow a former session merely by reusing its alias. - if (projectEffectiveToolItem(item).toolName === 'AgentSpawn') return ''; + if (['AgentSpawn', 'AgentFork'].includes(projectEffectiveToolItem(item).toolName)) return ''; const agentId = toolString(input.agent_id ?? input.agentId) || toolString(result.agent_id ?? result.agentId); if (!agentId || !parent) return ''; @@ -70,7 +70,7 @@ export function resolveInteractionAgentSessionId( if (candidate.id === item.id) return linkedSessionId; if (candidate.type !== 'tool') continue; const effective = projectEffectiveToolItem(candidate); - if (!['Task', 'AgentSpawn', 'AgentSendInput'].includes(effective.toolName)) continue; + if (!['Task', 'AgentSpawn', 'AgentFork', 'AgentSendInput'].includes(effective.toolName)) continue; const data = readToolRecord(effective.toolResult?.result); const params = readInteractionInput(effective); if ((toolString(data.agent_id ?? data.agentId) || toolString(params.agent_id ?? params.agentId)) !== agentId) continue; @@ -79,7 +79,7 @@ export function resolveInteractionAgentSessionId( parentSessionId: context.parentSessionId, parentToolIds: new Set([candidate.id, candidate.toolCall?.id].filter((id): id is string => Boolean(id))), })?.sessionId); - if (linked || effective.toolName === 'AgentSpawn') linkedSessionId = linked || ''; + if (linked || ['AgentSpawn', 'AgentFork'].includes(effective.toolName)) linkedSessionId = linked || ''; } } } diff --git a/src/web-ui/src/flow_chat/utils/deepReviewCapacityGuard.ts b/src/web-ui/src/flow_chat/utils/deepReviewCapacityGuard.ts index a940404775..94a6b4daec 100644 --- a/src/web-ui/src/flow_chat/utils/deepReviewCapacityGuard.ts +++ b/src/web-ui/src/flow_chat/utils/deepReviewCapacityGuard.ts @@ -24,7 +24,7 @@ function isActiveSubagentTask(item: unknown): item is FlowToolItem { const toolItem = item as FlowToolItem; if ( toolItem.type !== 'tool' || - !['Task', 'AgentSpawn', 'LaunchReviewAgent'].includes(getEffectiveToolName(toolItem)) || + !['Task', 'AgentSpawn', 'AgentFork', 'LaunchReviewAgent'].includes(getEffectiveToolName(toolItem)) || !ACTIVE_TOOL_STATUSES.has(toolItem.status) ) { return false; diff --git a/src/web-ui/src/flow_chat/utils/deepReviewContinuation.ts b/src/web-ui/src/flow_chat/utils/deepReviewContinuation.ts index 8cd7a89996..edc20c09c1 100644 --- a/src/web-ui/src/flow_chat/utils/deepReviewContinuation.ts +++ b/src/web-ui/src/flow_chat/utils/deepReviewContinuation.ts @@ -312,7 +312,7 @@ export function collectReviewerProgress(session: Session): DeepReviewReviewerPro for (const turn of session.dialogTurns) { for (const round of turn.modelRounds) { for (const item of round.items) { - if (item.type !== 'tool' || !['Task', 'AgentSpawn', 'LaunchReviewAgent'].includes(getEffectiveToolName(item))) { + if (item.type !== 'tool' || !['Task', 'AgentSpawn', 'AgentFork', 'LaunchReviewAgent'].includes(getEffectiveToolName(item))) { continue; } const progress = getReviewerProgressFromTask(item); diff --git a/src/web-ui/src/flow_chat/utils/deepReviewExperience.ts b/src/web-ui/src/flow_chat/utils/deepReviewExperience.ts index 5460e84df3..a4769d150c 100644 --- a/src/web-ui/src/flow_chat/utils/deepReviewExperience.ts +++ b/src/web-ui/src/flow_chat/utils/deepReviewExperience.ts @@ -204,7 +204,7 @@ export function extractPartialReviewData( for (const turn of session.dialogTurns) { for (const round of turn.modelRounds) { for (const item of round.items) { - if (item.type !== 'tool' || !['Task', 'AgentSpawn', 'LaunchReviewAgent'].includes(getEffectiveToolName(item))) { + if (item.type !== 'tool' || !['Task', 'AgentSpawn', 'AgentFork', 'LaunchReviewAgent'].includes(getEffectiveToolName(item))) { continue; } const reviewer = String( diff --git a/src/web-ui/src/infrastructure/api/generated/productControl.ts b/src/web-ui/src/infrastructure/api/generated/productControl.ts index 8e06e9cd95..42c2f21b37 100644 --- a/src/web-ui/src/infrastructure/api/generated/productControl.ts +++ b/src/web-ui/src/infrastructure/api/generated/productControl.ts @@ -1,5 +1,5 @@ // Generated by scripts/generate-interactive-capabilities.mjs; do not edit. -export const PRODUCT_CONTROL_GRAPH_DIGEST = "fe4be08cb20c2d67857891380d223a77d420345b94e2733d0000d14485027697" as const; +export const PRODUCT_CONTROL_GRAPH_DIGEST = "408cc52581d52de1e3686853eec8a09b2c02129869cb82b2931e21694e10557b" as const; export type ProductControlCapabilityId = "feature.home-search" | "feature.ai-assistant" | "feature.agents" | "feature.personal-assistants" | "feature.projects" | "feature.files-editor" | "feature.terminal" | "feature.cli-tui" | "feature.git" | "feature.code-review" | "feature.browser" | "feature.computer-use" | "feature.skills" | "feature.miniapps" | "feature.tasks-automation" | "feature.insights" | "feature.ecosystem-compatibility" | "feature.remote-workspaces" | "feature.remote-connect" | "feature.detached-dispatch" | "feature.pages" | "feature.voice-input" | "feature.desktop-pet" | "feature.desktop-cards" | "setting.application.general" | "setting.application.appearance" | "setting.application.pet" | "setting.application.input" | "setting.application.shortcuts" | "setting.application.development" | "setting.ai.models" | "setting.ai.permissions" | "setting.ai.memory" | "setting.workspace.session" | "setting.workspace.worktrees" | "setting.tools.execution" | "setting.application.terminal" | "setting.tools.desktop-control" | "setting.tools.browser-control" | "setting.tools.automation" | "setting.tools.web-search" | "setting.tools.mcp" | "setting.tools.acp" | "setting.data.usage" | "setting.data.archived" | "setting.data.diagnostics" | "feature.generative-ui"; diff --git a/src/web-ui/src/locales/en-US/scenes/capabilities.json b/src/web-ui/src/locales/en-US/scenes/capabilities.json index 0de5941feb..5fd49ec551 100644 --- a/src/web-ui/src/locales/en-US/scenes/capabilities.json +++ b/src/web-ui/src/locales/en-US/scenes/capabilities.json @@ -597,7 +597,8 @@ "computer-use": "Enable or disable the Allow desktop control switch after OS authorization", "computer-use-permissions": "Inspect and request Accessibility and Screen Recording OS permissions", "browser-auto-connect": "Choose whether OpenBitFun automatically connects to your CDP browser on startup", - "browser-setup": "Discover and choose an external browser, enable default CDP, or reconnect on demand" + "browser-setup": "Discover and choose an external browser, enable default CDP, or reconnect on demand", + "subagent-model-override": "Choose whether agents can override subagent models when launching or continuing work" } }, "desktop-control": { diff --git a/src/web-ui/src/locales/en-US/settings/agentic-tools.json b/src/web-ui/src/locales/en-US/settings/agentic-tools.json index 5b7f560553..3849fbd072 100644 --- a/src/web-ui/src/locales/en-US/settings/agentic-tools.json +++ b/src/web-ui/src/locales/en-US/settings/agentic-tools.json @@ -43,6 +43,8 @@ "subagentModelInherit": "Inherit parent session", "subagentDefaultModel": "Default subagent model", "subagentDefaultModelDesc": "Used by subagents without an individual model override.", + "forkSubagentDefaultModel": "Default fork subagent model", + "forkSubagentDefaultModelDesc": "Used when launching a subagent with inherited conversation context and no model override.", "subagentModelOverride": { "label": "Allow agents to choose subagent models", "hint": "When disabled, subagents use their configured models. Agents cannot choose a different model when launching or continuing work.", diff --git a/src/web-ui/src/locales/zh-CN/scenes/capabilities.json b/src/web-ui/src/locales/zh-CN/scenes/capabilities.json index 6b0d26bba4..9062362e51 100644 --- a/src/web-ui/src/locales/zh-CN/scenes/capabilities.json +++ b/src/web-ui/src/locales/zh-CN/scenes/capabilities.json @@ -597,7 +597,8 @@ "computer-use": "开启或关闭已获系统授权的“允许桌面控制”开关", "computer-use-permissions": "查看并请求辅助功能与屏幕录制系统权限", "browser-auto-connect": "控制 OpenBitFun 启动时是否自动连接外部 CDP 浏览器", - "browser-setup": "发现并选择外部浏览器、开启默认 CDP 配置或按需重启连接" + "browser-setup": "发现并选择外部浏览器、开启默认 CDP 配置或按需重启连接", + "subagent-model-override": "控制 Agent 能否在启动或继续执行子 Agent 时指定模型" } }, "desktop-control": { diff --git a/src/web-ui/src/locales/zh-CN/settings/agentic-tools.json b/src/web-ui/src/locales/zh-CN/settings/agentic-tools.json index cb11b0084e..4bfdfcd3f6 100644 --- a/src/web-ui/src/locales/zh-CN/settings/agentic-tools.json +++ b/src/web-ui/src/locales/zh-CN/settings/agentic-tools.json @@ -43,6 +43,8 @@ "subagentModelInherit": "继承父会话", "subagentDefaultModel": "子智能体默认模型", "subagentDefaultModelDesc": "未单独指定模型的子智能体使用此设置。", + "forkSubagentDefaultModel": "Fork 子智能体默认模型", + "forkSubagentDefaultModelDesc": "启动继承父会话上下文的子智能体时,若未指定模型,则使用此设置。", "subagentModelOverride": { "label": "允许 Agent 指定子 Agent 模型", "hint": "关闭后,子 Agent 使用已配置的模型,Agent 无法在启动或继续执行时指定其他模型。", diff --git a/src/web-ui/src/locales/zh-TW/scenes/capabilities.json b/src/web-ui/src/locales/zh-TW/scenes/capabilities.json index f1159c633e..53f93efd16 100644 --- a/src/web-ui/src/locales/zh-TW/scenes/capabilities.json +++ b/src/web-ui/src/locales/zh-TW/scenes/capabilities.json @@ -597,7 +597,8 @@ "computer-use": "開啟或關閉已獲系統授權的「允許桌面控制」開關", "computer-use-permissions": "檢視並請求輔助功能與螢幕錄製系統權限", "browser-auto-connect": "控制 OpenBitFun 啟動時是否自動連線外部 CDP 瀏覽器", - "browser-setup": "探索並選擇外部瀏覽器、開啟預設 CDP 設定或依需求重新啟動連線" + "browser-setup": "探索並選擇外部瀏覽器、開啟預設 CDP 設定或依需求重新啟動連線", + "subagent-model-override": "控制 Agent 能否在啟動或繼續執行子 Agent 時指定模型" } }, "desktop-control": { diff --git a/src/web-ui/src/locales/zh-TW/settings/agentic-tools.json b/src/web-ui/src/locales/zh-TW/settings/agentic-tools.json index 5e395ae62c..47b42e1a8d 100644 --- a/src/web-ui/src/locales/zh-TW/settings/agentic-tools.json +++ b/src/web-ui/src/locales/zh-TW/settings/agentic-tools.json @@ -43,6 +43,8 @@ "subagentModelInherit": "繼承父會話", "subagentDefaultModel": "子智能體預設模型", "subagentDefaultModelDesc": "未個別指定模型的子智慧體使用此設定。", + "forkSubagentDefaultModel": "Fork 子智慧體預設模型", + "forkSubagentDefaultModelDesc": "啟動繼承父會話上下文的子智慧體時,若未指定模型,則使用此設定。", "subagentModelOverride": { "label": "允許 Agent 指定子 Agent 模型", "hint": "關閉後,子 Agent 使用已設定的模型,Agent 無法在啟動或繼續執行時指定其他模型。", From d45664490ddcf202af5582fabe01036273398017 Mon Sep 17 00:00:00 2001 From: wsp Date: Tue, 17 Nov 2026 23:56:38 +0800 Subject: [PATCH 4/5] fix(agent): Prevent catalog future stack overflows Box collaboration policy inputs before constructing async state so nested catalog scopes cannot multiply large futures on the stack. Keep manual compaction preparation behind a heap allocation boundary. Preserve lazy policy loading and nested presentation snapshots. Add regression coverage for future size, scope inheritance, and cleanup, and document focused verification with the default thread stack. Validation: 16 focused PTC-enabled Rust tests pass after probe removal; the Rust CI configuration contract passes. Ubuntu CI passed with the same production fixes before removing temporary diagnostics. --- src/crates/assembly/core/AGENTS.md | 22 ++++ .../src/agentic/coordination/coordinator.rs | 8 +- .../agent_collaboration/model_policy.rs | 116 +++++++++++++++--- 3 files changed, 128 insertions(+), 18 deletions(-) diff --git a/src/crates/assembly/core/AGENTS.md b/src/crates/assembly/core/AGENTS.md index c7e89d506f..165b177eaa 100644 --- a/src/crates/assembly/core/AGENTS.md +++ b/src/crates/assembly/core/AGENTS.md @@ -264,6 +264,18 @@ cargo test --locked -p openbitfun-core --no-default-features --features agent-ru These fixtures cover prompt name mappings and simulated workspace policies; they do not establish live SSH, relay, Peer, or Detached Dispatch behavior. +For collaboration presentation policy scope, input-independent future size, and +native/PTC catalog propagation: + +```bash +cargo test --locked -p openbitfun-core --no-default-features --features agent-runtime,git --lib -- collaboration_policy_ subagent_model_override_policy_ +cargo test --locked -p openbitfun-core --no-default-features --features ptc-runtime --lib -- collaboration_policy_ subagent_model_override_policy_ +``` + +The policy wrapper boxes its input before constructing its async state machine; +keep this boundary shared by all catalog callers. These fixtures do not exercise +live remote transports. + For ordinary subagent shared concurrency, permit release, and cancelled/timed-out waits: ```bash @@ -386,6 +398,16 @@ Run this filter alone with `RUST_MIN_STACK` unset so prior skill discovery canno warm the cold-start path. The shared coordinator keeps startup state behind one allocation boundary for every admission surface. +For manual compaction cancellation and terminal persistence: + +```bash +cargo test --locked -p openbitfun-core --no-default-features --features agent-runtime,git --lib manual_compaction_ +``` + +Keep `RUST_MIN_STACK` unset when checking stack-overflow regressions. Linux CI's +`product-full` suite also covers the larger assembled tool-catalog futures. +These local fixtures do not exercise live remote scenarios. + For direct user follow-ups to reusable subagent sessions, legacy route defaults, source binding, and FreshOnly admission: diff --git a/src/crates/assembly/core/src/agentic/coordination/coordinator.rs b/src/crates/assembly/core/src/agentic/coordination/coordinator.rs index c7b8690235..6a1158b115 100644 --- a/src/crates/assembly/core/src/agentic/coordination/coordinator.rs +++ b/src/crates/assembly/core/src/agentic/coordination/coordinator.rs @@ -6406,7 +6406,11 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet ) -> OpenBitFunResult<()> { let compression_id = format!("compression_{}", uuid::Uuid::new_v4()); let mut context_window = session.config.max_context_tokens; - let result = async { + // Preparation and compaction embed the full model/tool-catalog future. + // Keep that state on the heap instead of duplicating it through this + // task and its callers: even a pre-cancelled turn must enter the poll + // stack frame before it can observe cancellation. + let result = Box::pin(async { let (manual_execution_context, resolved_context_window) = prepare_compression_cancellable(&cancellation_token, async { let manual_workspace_services = @@ -6468,7 +6472,7 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet commit_gate, ) .await - } + }) .await; match result { Ok(outcome) => { diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/model_policy.rs b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/model_policy.rs index c6b2492890..13b69ecceb 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/model_policy.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/agent_collaboration/model_policy.rs @@ -72,24 +72,30 @@ tokio::task_local! { /// Freeze only tool presentation during one catalog request. Execution always /// re-reads the host policy so an already-issued tool call cannot bypass an opt-out. -pub(crate) async fn with_collaboration_model_policy( +pub(crate) fn with_collaboration_model_policy( future: F, -) -> F::Output { - if MODEL_PRESENTATION_POLICY.try_with(|_| ()).is_ok() { - return future.await; +) -> impl std::future::Future { + // Box before constructing the async state machine. An async fn would still + // retain its inline F argument, and nested catalog scopes multiply both its + // size and TaskLocalFuture's debug poll temporaries (especially with PTC). + let future = Box::pin(future); + async move { + if MODEL_PRESENTATION_POLICY.try_with(|_| ()).is_ok() { + return future.await; + } + let policy = ModelOverridePolicy::load().await.unwrap_or_else(|error| { + warn!( + "Failed to read collaboration presentation policy: {}", + error + ); + ModelOverridePolicy { allowed: false } + }); + crate::agentic::tools::registry::get_global_tool_registry() + .write() + .await + .refresh_collaboration_model_policy(policy.allowed); + MODEL_PRESENTATION_POLICY.scope(policy, future).await } - let policy = ModelOverridePolicy::load().await.unwrap_or_else(|error| { - warn!( - "Failed to read collaboration presentation policy: {}", - error - ); - ModelOverridePolicy { allowed: false } - }); - crate::agentic::tools::registry::get_global_tool_registry() - .write() - .await - .refresh_collaboration_model_policy(policy.allowed); - MODEL_PRESENTATION_POLICY.scope(policy, future).await } pub(super) async fn model_override_validation(input: &Value) -> Option { @@ -103,3 +109,81 @@ pub(super) async fn model_override_validation(input: &Value) -> Option() { + let buffer = [0u8; N]; + std::future::pending::<()>().await; + std::hint::black_box(buffer); + } + + fn future_size(_: impl FnOnce() -> F) -> usize { + std::mem::size_of::() + } + + // Infer sizes without allocating the large fixture on the test stack. + assert!(future_size(input::<65536>) > future_size(input::<1>)); + assert_eq!( + future_size(|| with_collaboration_model_policy(input::<1>())), + future_size(|| with_collaboration_model_policy(input::<65536>())), + "The policy wrapper must not embed the catalog future's state" + ); + assert_eq!( + future_size(|| with_collaboration_model_policy(input::<65536>())), + future_size(|| { + with_collaboration_model_policy(with_collaboration_model_policy(input::<65536>())) + }), + "Nested catalog scopes must not multiply the wrapper's state" + ); + } + + #[tokio::test] + async fn collaboration_policy_remains_lazy_inherited_and_scoped() { + let wrapped = with_collaboration_model_policy(async { + assert!(!ModelOverridePolicy::presentation().await.unwrap().allowed); + tokio::task::yield_now().await; + assert!(!ModelOverridePolicy::presentation().await.unwrap().allowed); + TEST_MODEL_OVERRIDE + .scope( + true, + with_collaboration_model_policy(async { + // Nested presentation inherits the snapshot, while execution + // policy still reads the current host setting independently. + assert!(!ModelOverridePolicy::presentation().await.unwrap().allowed); + assert!(ModelOverridePolicy::load().await.unwrap().allowed); + }), + ) + .await; + }); + assert!(MODEL_PRESENTATION_POLICY.try_with(|_| ()).is_err()); + // Select the policy only when polled, after construction outside this scope. + TEST_MODEL_OVERRIDE.scope(false, wrapped).await; + assert!(MODEL_PRESENTATION_POLICY.try_with(|_| ()).is_err()); + } + + #[tokio::test] + async fn collaboration_policy_pending_and_dropped_future_does_not_leak_scope() { + TEST_MODEL_OVERRIDE + .scope(false, async { + let mut wrapped = Box::pin(with_collaboration_model_policy(async { + assert!(!ModelOverridePolicy::presentation().await.unwrap().allowed); + std::future::pending::<()>().await; + })); + std::future::poll_fn(|cx| { + assert!(wrapped.as_mut().poll(cx).is_pending()); + std::task::Poll::Ready(()) + }) + .await; + assert!(MODEL_PRESENTATION_POLICY.try_with(|_| ()).is_err()); + drop(wrapped); + assert!(MODEL_PRESENTATION_POLICY.try_with(|_| ()).is_err()); + }) + .await; + } +} From 3a115d6b4daaef3715309c4fdf45da7f03007436 Mon Sep 17 00:00:00 2001 From: wsp Date: Wed, 18 Nov 2026 00:21:32 +0800 Subject: [PATCH 5/5] ci: Add cross-platform Rust stack diagnostics Capture core test output and exact Cargo artifacts on Linux, macOS, and Windows. Diagnose stack overflows with bounded isolated reruns, platform debugger traces, and a larger-stack comparison while keeping the original test result as the CI gate. Reuse existing binaries without extra builds or Rust test runs on successful CI paths. Preserve evidence when a test cannot be identified or a debugger is unavailable, and clean up timed-out process trees. Add platform contract tests and document artifact use and limitations. Validation: 26 diagnostic tests, focused CI assertions, and YAML checks pass. A native Windows fixture verifies real stack-overflow detection, large-stack recovery, and process-tree cleanup. Native debugger traces remain to be validated on their respective hosts. The full GitHub configuration suite still has unrelated local shell-environment failures. --- .github/workflows/ci.yml | 20 +- scripts/check-github-config.test.mjs | 27 +- scripts/ci/AGENTS.md | 86 +++++++ scripts/ci/rust-stack-diagnostics.mjs | 270 ++++++++++++++++++++ scripts/ci/rust-stack-diagnostics.test.mjs | 276 +++++++++++++++++++++ 5 files changed, 671 insertions(+), 8 deletions(-) create mode 100644 scripts/ci/AGENTS.md create mode 100644 scripts/ci/rust-stack-diagnostics.mjs create mode 100644 scripts/ci/rust-stack-diagnostics.test.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7fe78c0863..182a27754f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -231,6 +231,9 @@ jobs: node-version-file: package.json package-manager-cache: false + - name: Verify Rust stack diagnostic contracts + run: node --test scripts/ci/rust-stack-diagnostics.test.mjs + # Tauri code generation only requires its configured resource roots to # exist during check/test; distributable assets remain frontend-build's owner. - name: Create Tauri resource directories @@ -330,15 +333,28 @@ jobs: run: cargo check --manifest-path OpenBitFun-Installer/src-tauri/Cargo.toml - name: Run core library tests + id: core-library-tests if: runner.os != 'Linux' - run: cargo test --locked -p openbitfun-core --lib + run: node scripts/ci/rust-stack-diagnostics.mjs --output "${{ runner.temp }}/rust-stack-diagnostics" -- --locked -p openbitfun-core --lib - name: Run portable Office document engine tests run: cargo test --locked -p openbitfun-office-documents - name: Run full core library tests on Linux + id: full-core-library-tests if: runner.os == 'Linux' - run: cargo test --locked -p openbitfun-core --features product-full --lib + # Capture the existing run; only stack overflows trigger bounded reruns. + # See scripts/ci/AGENTS.md for reuse and diagnostic limitations. + run: node scripts/ci/rust-stack-diagnostics.mjs --output "${{ runner.temp }}/rust-stack-diagnostics" -- --locked -p openbitfun-core --features product-full --lib + + - name: Upload Rust stack diagnostics + if: ${{ failure() && (steps.core-library-tests.outputs.stack_overflow == 'true' || steps.full-core-library-tests.outputs.stack_overflow == 'true') }} + uses: actions/upload-artifact@v6 + with: + name: rust-stack-diagnostics-${{ runner.os }} + path: ${{ runner.temp }}/rust-stack-diagnostics + if-no-files-found: warn + retention-days: 7 - name: Run desktop library tests if: runner.os != 'Windows' diff --git a/scripts/check-github-config.test.mjs b/scripts/check-github-config.test.mjs index 9dd1bc0431..6fdd91f6bd 100644 --- a/scripts/check-github-config.test.mjs +++ b/scripts/check-github-config.test.mjs @@ -590,8 +590,10 @@ test('keeps Rust CI independent, restore-only on PRs, and target-focused', () => const linuxFullCoreLibraryTests = rustJob.steps.find( (step) => step.name === 'Run full core library tests on Linux', ); + const linuxCoreCommand = 'node scripts/ci/rust-stack-diagnostics.mjs --output "${{ runner.temp }}/rust-stack-diagnostics" -- --locked -p openbitfun-core --features product-full --lib'; + const otherCoreCommand = 'node scripts/ci/rust-stack-diagnostics.mjs --output "${{ runner.temp }}/rust-stack-diagnostics" -- --locked -p openbitfun-core --lib'; const coreLibraryTestSteps = rustJob.steps.filter( - (step) => /^cargo test --locked -p openbitfun-core\b.*\s--lib$/.test(step.run ?? ''), + (step) => /^(?:cargo test|node scripts\/ci\/rust-stack-diagnostics\.mjs .* --) --locked -p openbitfun-core\b.*\s--lib$/.test(step.run ?? ''), ); const desktopLibraryTests = rustJob.steps.find( (step) => step.name === 'Run desktop library tests', @@ -608,7 +610,7 @@ test('keeps Rust CI independent, restore-only on PRs, and target-focused', () => ); assert.equal( coreLibraryTests?.run, - 'cargo test --locked -p openbitfun-core --lib', + otherCoreCommand, ); assert.equal( linuxFullCoreLibraryTests?.if, @@ -616,18 +618,31 @@ test('keeps Rust CI independent, restore-only on PRs, and target-focused', () => ); assert.equal( linuxFullCoreLibraryTests?.run, - 'cargo test --locked -p openbitfun-core --features product-full --lib', - ); + linuxCoreCommand, + ); + assert.equal(coreLibraryTests?.id, 'core-library-tests'); + assert.equal(coreLibraryTests?.['continue-on-error'], undefined); + assert.equal(linuxFullCoreLibraryTests?.id, 'full-core-library-tests'); + assert.equal(linuxFullCoreLibraryTests?.['continue-on-error'], undefined); + const stackArtifact = rustJob.steps.find((step) => step.name === 'Upload Rust stack diagnostics'); + assert.equal(stackArtifact?.if, "${{ failure() && (steps.core-library-tests.outputs.stack_overflow == 'true' || steps.full-core-library-tests.outputs.stack_overflow == 'true') }}"); + assert.equal(stackArtifact?.uses, 'actions/upload-artifact@v6'); + assert.equal(stackArtifact?.with?.path, '${{ runner.temp }}/rust-stack-diagnostics'); + assert.equal(stackArtifact?.with?.['retention-days'], 7); + assert.equal(stackArtifact?.with?.name, 'rust-stack-diagnostics-${{ runner.os }}'); + assert.equal(rustJob.steps.find( + (step) => step.name === 'Verify Rust stack diagnostic contracts', + )?.run, 'node --test scripts/ci/rust-stack-diagnostics.test.mjs'); assert.deepEqual( coreLibraryTestSteps.map((step) => ({ if: step.if, run: step.run })), [ { if: "runner.os != 'Linux'", - run: 'cargo test --locked -p openbitfun-core --lib', + run: otherCoreCommand, }, { if: "runner.os == 'Linux'", - run: 'cargo test --locked -p openbitfun-core --features product-full --lib', + run: linuxCoreCommand, }, ], 'Core library validation must contain exactly the reviewed complementary steps', diff --git a/scripts/ci/AGENTS.md b/scripts/ci/AGENTS.md new file mode 100644 index 0000000000..3c318226ef --- /dev/null +++ b/scripts/ci/AGENTS.md @@ -0,0 +1,86 @@ +# CI helper scripts + +Keep normal validation gates unchanged when adding failure diagnostics. Do not +change feature sets, increase the gating test stack, or accept a diagnostic +rerun as a substitute for the original result. Child processes must set +`windowsHide: true`. + +## Rust stack-overflow diagnostics + +`rust-stack-diagnostics.mjs` wraps an existing `cargo test` command. It records +test output and reads Cargo's JSON artifact messages to identify the exact test +executables, features, and profiles. Successful runs and ordinary test failures +do not trigger extra commands. There is no second build, debugger installation, +or change to the default stack/debug profile on the successful CI path. + +```bash +node scripts/ci/rust-stack-diagnostics.mjs --output /tmp/rust-stack-diagnostics -- --locked -p openbitfun-core --features product-full --lib +``` + +Arguments after the first `--` are passed to `cargo test`, including optional +libtest arguments after a second `--`. The wrapper owns `--message-format`. +Use a dedicated output directory per invocation. CI enables it for the core +library suite on Linux, macOS, and Windows, retaining `product-full` only on +Linux. Other native libtest commands can use the same wrapper and upload pattern +without hard-coded package/test names. + +When a failing run prints Rust's stack-overflow signature or Windows reports +`STATUS_STACK_OVERFLOW` (`0xc00000fd`): + +- Save the original log, Cargo result, artifact metadata, and toolchain version. +- Validate the exact test name against the built binaries' `--list` output. + Ambiguous names, worker threads, and discovery failures retain evidence and + stop without claiming an isolated reproduction. A native overflow without a + named test thread also retains evidence without guessing which test failed. +- Run the one matching test with the original stack setting, under the platform + debugger if available, and with `RUST_MIN_STACK=16777216` as a comparison. + The reruns use the owning package directory and reconstructed loader paths. +- Bound all diagnostics to three minutes total: discovery at most 30 seconds, + debugger at most 60 seconds, and each isolated run at most 30 seconds. POSIX + timeout cleanup kills the diagnostic process group; Windows uses + `taskkill /PID /T /F`, reserving up to five seconds for cleanup. If tree + cleanup fails, report it explicitly and terminate the direct child. +- Preserve the original Cargo exit code regardless of diagnostic outcomes. + +Download `rust-stack-diagnostics-Linux`, `rust-stack-diagnostics-macOS`, or +`rust-stack-diagnostics-Windows` after its upload step completes. Start +with `summary.json` and `cargo-test.log`, then compare `original-stack.log`, +the debugger log, and `large-stack.log`. A successful large-stack run suggests stack +pressure; it does not distinguish recursion from large async state. Zero tests, +timeouts, missing libraries/debugger, and independent rerun errors are not a +successful reproduction. These are isolated reruns, not a capture of the +original process; shared-state/order-dependent failures may not recur. + +Platform adapters: + +| Host | Debugger | Loader environment | Debugger log | +| --- | --- | --- | --- | +| Linux | GDB from PATH | `LD_LIBRARY_PATH` | `gdb.log` | +| macOS | LLDB from PATH (Xcode command-line tools) | `DYLD_FALLBACK_LIBRARY_PATH`, also set in LLDB's target environment for SIP | `lldb.log` | +| Windows | CDB from PATH or the matching architecture under Windows Kits 10 Debuggers | case-insensitive PATH | `cdb.log` | + +CDB is the console component of Debugging Tools for Windows; a WinDbg GUI-only +installation is not enough. Do not launch GUI debuggers or install SDKs in CI. +Debugger absence or launch restrictions are recorded and do not prevent the +large-stack comparison. GDB disables debuginfod; CDB uses local PDB paths without +symbol-server downloads. LLDB uses batch crash commands; CDB stops on stack +overflow, access violation, fast-fail, and fatal application-exit exceptions. + +Automatic reruns support native Linux/macOS/Windows libtest targets, not doctests, +custom harnesses, cross-target runners, or custom runner environment injection. +Debuggers use the original debug information; stripped CI builds may yield only +symbols/addresses. No automatic rebuild with debug info is attempted. If more +evidence is needed, reproduce locally with debug info or add a targeted future +layout/checkpoint probe. Logs contain normal test output; never log credentials. + +## Focused verification + +```bash +node --test scripts/ci/rust-stack-diagnostics.test.mjs +node --test --test-name-pattern='keeps Rust CI independent' scripts/check-github-config.test.mjs +``` + +For workflow changes also run `pnpm run check:github-config`. Some unrelated +shell fixtures require Linux tools and do not work under Windows Bash bridges. +Script fixtures do not establish live remote-workspace, relay, Peer Device, or +Detached Dispatch behavior. diff --git a/scripts/ci/rust-stack-diagnostics.mjs b/scripts/ci/rust-stack-diagnostics.mjs new file mode 100644 index 0000000000..999fbca9c3 --- /dev/null +++ b/scripts/ci/rust-stack-diagnostics.mjs @@ -0,0 +1,270 @@ +import { spawn } from 'node:child_process'; +import { appendFileSync, existsSync, mkdirSync, writeFileSync } from 'node:fs'; +import path from 'node:path'; +import { createInterface } from 'node:readline'; +import { pathToFileURL } from 'node:url'; + +// Stream output rather than retaining a full build log in memory. Diagnostic +// POSIX diagnostics use process groups; Windows uses taskkill's process tree. +export function runProcess(command, args, { env = process.env, cwd, timeoutMs, + onLine = () => {}, } = {}) { + return new Promise((resolve) => { + const grouped = Boolean(timeoutMs) && process.platform !== 'win32'; + const child = spawn(command, args, { + env, cwd, windowsHide: true, detached: grouped, stdio: ['ignore', 'pipe', 'pipe'], + }); + let timedOut = false; + let error; + let cleanup; + let cleanupError; + const readers = [child.stdout, child.stderr].map((stream, index) => { + const reader = createInterface({ input: stream, crlfDelay: Infinity }); + reader.on('line', (line) => onLine(line, index === 0 ? 'stdout' : 'stderr')); + return reader; + }); + const timer = timeoutMs && setTimeout(() => { + timedOut = true; + try { + if (grouped) process.kill(-child.pid, 'SIGKILL'); + else if (child.pid) { + cleanup = new Promise((done) => { + const killer = spawn(path.win32.join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'taskkill.exe'), + ['/PID', String(child.pid), '/T', '/F'], { + windowsHide: true, stdio: 'ignore', timeout: 5_000, killSignal: 'SIGKILL', + }); + killer.on('error', (err) => { cleanupError = err.message; }); + killer.on('close', (code) => { + if (code !== 0) { + cleanupError ??= `taskkill exited with ${code}; descendant cleanup could not be confirmed.`; + child.kill('SIGKILL'); + // Do not hang on inherited pipes if tree cleanup was unavailable. + child.stdout.destroy(); + child.stderr.destroy(); + } + done(); + }); + }); + } + } catch { /* The child may have exited just before the timer. */ } + }, timeoutMs); + child.on('error', (err) => { error = err.message; }); + child.on('close', async (code, signal) => { + clearTimeout(timer); + readers.forEach((reader) => reader.close()); + await cleanup; + resolve({ code: code ?? 1, signal, timedOut, ...(error && { error }), + ...(cleanupError && { cleanupError }) }); + }); + }); +} + +export function overflowThread(line) { + return line.match(/thread '([^'\r\n]+)'(?: \(\d+\))? has overflowed its stack/)?.[1]; +} + +export function loaderEnvironment(platform, env, libraryPaths) { + const result = { ...env }; + const key = platform === 'win32' ? 'PATH' + : platform === 'darwin' ? 'DYLD_FALLBACK_LIBRARY_PATH' : 'LD_LIBRARY_PATH'; + const existingKey = platform === 'win32' + ? Object.keys(env).find((name) => name.toUpperCase() === key) ?? key : key; + let previous = env[existingKey]; + if (platform === 'darwin' && previous === undefined) { + previous = [env.HOME && path.posix.join(env.HOME, 'lib'), '/usr/local/lib', '/usr/lib'].filter(Boolean).join(':'); + } + if (platform === 'win32') { + // Node sorts duplicate case variants on Windows and passes just one onward. + for (const name of Object.keys(result)) if (name.toUpperCase() === key) delete result[name]; + } + result[existingKey] = [...libraryPaths, ...(previous ? [previous] : [])].join(platform === 'win32' ? ';' : ':'); + return result; +} + +export function debuggerPlan(platform, executable, testArgs, env, commandFile, + { fileExists = existsSync, arch = process.arch } = {}) { + if (platform === 'darwin') { + return { name: 'lldb', command: 'lldb', env, args: ['--batch', '--no-lldbinit', + // SIP can strip DYLD_* from LLDB's own environment; set the inferior's + // loader path explicitly through LLDB's target settings as well. + '-o', `settings set target.env-vars ${JSON.stringify(`DYLD_FALLBACK_LIBRARY_PATH=${env.DYLD_FALLBACK_LIBRARY_PATH}`)}`, + '-o', 'run', '-k', 'thread backtrace -c 80 all', '-k', 'register read', + '-k', 'disassemble --pc --count 16', '--', executable, ...testArgs] }; + } + if (platform === 'win32') { + const getEnv = (key) => env[Object.keys(env).find((name) => name.toUpperCase() === key.toUpperCase())]; + const sdkArch = arch === 'ia32' ? 'x86' : arch; + const candidates = (getEnv('PATH') ?? '').split(';').filter(Boolean) + .map((dir) => path.win32.join(dir.replace(/^"|"$/g, ''), 'cdb.exe')); + for (const root of [getEnv('ProgramFiles(x86)'), getEnv('ProgramFiles')].filter(Boolean)) { + candidates.push(path.win32.join(root, 'Windows Kits', '10', 'Debuggers', sdkArch, 'cdb.exe')); + } + // CDB is the console debugger from Debugging Tools for Windows. Never + // launch the WinDbg GUI or install an SDK as part of a failed CI run. + const command = candidates.find(fileExists) ?? 'cdb.exe'; + const trace = '.ecxr; ~* kb 0n80; r; u @$ip L10; q'; + return { name: 'cdb', command, + env: { ...env, _NT_SYMBOL_PATH: '', _NT_ALT_SYMBOL_PATH: '' }, + commands: ['sov', 'av', '0xc0000409', '0x40000015'] + .map((event) => `sxe -c "${trace}" ${event}`).concat('g').join('\n'), + args: ['-G', '-y', path.win32.dirname(executable), '-cf', commandFile, executable, ...testArgs] }; + } + return { name: 'gdb', command: 'gdb', env, args: ['--batch', '--nx', + '-ex', 'set pagination off', '-ex', 'set debuginfod enabled off', + '-ex', 'handle SIGSEGV stop print nopass', '-ex', 'handle SIGABRT stop print nopass', + '-ex', 'run', '-ex', 'thread apply all bt 80', '-ex', 'info registers', + '-ex', 'x/16i $pc', '--args', executable, ...testArgs] }; +} + +export async function runCargoTests({ cargoArgs, outputDir, env = process.env, + platform = process.platform, run = runProcess, print = console.log }) { + // Own Cargo's message format so the executable always comes from this exact + // feature/profile build, never a stale glob or a second cargo invocation. + if (cargoArgs.some((arg) => arg.startsWith('--message-format'))) { + throw new Error('The diagnostic wrapper owns --message-format.'); + } + outputDir = path.resolve(outputDir); + mkdirSync(outputDir, { recursive: true }); + const logPath = path.join(outputDir, 'cargo-test.log'); + writeFileSync(logPath, ''); + const artifacts = new Map(); + const libraryPaths = new Set(); + let thread; + let overflowDetected = false; + const args = ['test', '--message-format=json-render-diagnostics', ...cargoArgs]; + const original = await run('cargo', args, { env, onLine(line, stream) { + // Cargo JSON and libtest text share stdout. Ignore only recognized Cargo + // records; test output that happens to be JSON must remain visible. + if (stream === 'stdout' && line.startsWith('{')) { + try { + const record = JSON.parse(line); + if (record.reason === 'compiler-artifact') { + if (record.profile?.test && record.executable && record.manifest_path) { + artifacts.set(record.executable, record); + } + return; + } + if (record.reason === 'build-script-executed') { + for (const entry of record.linked_paths ?? []) { + libraryPaths.add(entry.replace(/^(native|dependency|crate|framework|all)=/, '')); + } + return; + } + if (record.reason === 'build-finished') return; + } catch { /* A test may print a non-JSON line starting with a brace. */ } + } + appendFileSync(logPath, `${line}\n`); + print(line); + thread = overflowThread(line) ?? thread; + overflowDetected ||= Boolean(thread) || /fatal runtime error: stack overflow|STATUS_STACK_OVERFLOW|0xc00000fd/i.test(line); + } }); + if (original.error) print(original.error); + overflowDetected ||= platform === 'win32' && (original.code >>> 0) === 0xc00000fd; + if (original.code === 0 || !overflowDetected) return original.code; + + // Write evidence before any diagnostic subprocess: timeouts, missing debuggers, + // and unsuccessful isolated reproduction must never erase the first crash. + const report = { command: ['cargo', ...args], original, thread: thread ?? null, platform, + cwd: process.cwd(), rustMinStack: env.RUST_MIN_STACK ?? null, + artifacts: [...artifacts.values()], stages: [] }; + const save = () => writeFileSync(path.join(outputDir, 'summary.json'), `${JSON.stringify(report, null, 2)}\n`); + save(); + if (env.GITHUB_OUTPUT) appendFileSync(env.GITHUB_OUTPUT, 'stack_overflow=true\n'); + const deadline = Date.now() + 180_000; + async function stage(name, command, stageArgs, options = {}) { + const lines = []; + const stagePath = path.join(outputDir, `${name}.log`); + writeFileSync(stagePath, `${JSON.stringify([command, ...stageArgs])}\n`); + // Reserve Windows' bounded process-tree cleanup inside the total budget. + const remaining = deadline - Date.now() - (platform === 'win32' ? 5_000 : 0); + const result = remaining <= 0 ? { code: 1, timedOut: true } : await run(command, stageArgs, { + env, ...options, timeoutMs: Math.max(1, Math.min(options.timeoutMs ?? 30_000, remaining)), + onLine(line) { + appendFileSync(stagePath, `${line}\n`); + // Only --list output and toolchain paths need parsing, with a bound. + if (options.capture && lines.length < 50_000) lines.push(line); + }, + }); + report.stages.push({ name, ...result }); + save(); + return { ...result, lines }; + } + + try { + if (!['linux', 'darwin', 'win32'].includes(platform)) { + report.note = `Automatic stack diagnosis is unsupported on ${platform}.`; + return original.code; + } + await stage('rustc', 'rustc', ['-Vv'], { timeoutMs: 5_000 }); + if (!thread) { + report.note = 'Stack overflow was reported without a named test thread. Evidence was retained; no isolated rerun was attempted.'; + return original.code; + } + const libdir = await stage('rustc-libdir', 'rustc', ['--print', 'target-libdir'], + { timeoutMs: 5_000, capture: true }); + if (libdir.code === 0 && libdir.lines.length === 1) libraryPaths.add(libdir.lines[0]); + // Cargo normally extends the dynamic loader path when launching tests. + // Reuse paths from this build rather than changing features or rebuilding. + for (const artifact of artifacts.values()) { + libraryPaths.add(path.dirname(artifact.executable)); + libraryPaths.add(path.dirname(path.dirname(artifact.executable))); + } + const diagnosticEnv = loaderEnvironment(platform, env, libraryPaths); + // Match the complete name, not a substring. Worker/main thread failures + // cannot safely be mapped to a test; ambiguous multi-target names also stop. + const candidates = []; + const listingDeadline = Date.now() + 30_000; + for (const artifact of artifacts.values()) { + if (Date.now() >= listingDeadline) { + report.note = 'Test discovery exceeded its time budget; no isolated rerun was attempted.'; + return original.code; + } + const listed = await stage(`list-${report.stages.length}`, artifact.executable, + [thread, '--exact', '--list'], { + cwd: path.dirname(artifact.manifest_path), env: diagnosticEnv, capture: true, + timeoutMs: Math.min(10_000, listingDeadline - Date.now()), + }); + if (listed.code !== 0) { + report.note = 'A test target could not be listed; target selection is incomplete.'; + return original.code; + } + if (listed.lines.includes(`${thread}: test`)) candidates.push(artifact); + } + if (candidates.length !== 1) { + report.note = `Expected one exact libtest match; found ${candidates.length}. No isolated rerun was attempted.`; + return original.code; + } + const selected = candidates[0]; + report.selectedExecutable = selected.executable; + const cwd = path.dirname(selected.manifest_path); + // --include-ignored ensures a previously explicitly selected ignored test + // really executes, instead of reporting a misleading zero-test success. + const testArgs = [thread, '--exact', '--include-ignored', '--nocapture', '--test-threads=1']; + await stage('original-stack', selected.executable, testArgs, { cwd, env: diagnosticEnv }); + const commandFile = path.join(outputDir, 'cdb-commands.txt'); + const debuggerRun = debuggerPlan(platform, selected.executable, testArgs, diagnosticEnv, commandFile); + if (debuggerRun.commands) writeFileSync(commandFile, `${debuggerRun.commands}\n`); + report.debugger = debuggerRun.name; + await stage(debuggerRun.name, debuggerRun.command, debuggerRun.args, + { cwd, env: debuggerRun.env, timeoutMs: 60_000 }); + await stage('large-stack', selected.executable, testArgs, { + cwd, env: { ...diagnosticEnv, RUST_MIN_STACK: '16777216' }, + }); + report.note = 'Reruns are diagnostic only. Compare logs; the original Cargo failure remains the gate. Large-stack success suggests stack pressure but does not establish its cause.'; + } catch (error) { + report.diagnosticError = String(error); + } finally { + save(); + print(`Stack-overflow diagnostics saved to ${outputDir}; preserving Cargo exit ${original.code}.`); + } + return original.code; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const args = process.argv.slice(2); + if (args[0] !== '--output' || !args[1] || args[2] !== '--' || args.length < 4) { + console.error('Usage: node scripts/ci/rust-stack-diagnostics.mjs --output -- '); + process.exitCode = 1; + } else { + process.exitCode = await runCargoTests({ outputDir: args[1], cargoArgs: args.slice(3) }); + } +} diff --git a/scripts/ci/rust-stack-diagnostics.test.mjs b/scripts/ci/rust-stack-diagnostics.test.mjs new file mode 100644 index 0000000000..0e5bae45f0 --- /dev/null +++ b/scripts/ci/rust-stack-diagnostics.test.mjs @@ -0,0 +1,276 @@ +import assert from 'node:assert/strict'; +import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { test } from 'node:test'; +import { debuggerPlan, loaderEnvironment, overflowThread, runCargoTests, runProcess } from './rust-stack-diagnostics.mjs'; + +const testName = 'some_module::tests::large_future'; +const ok = { code: 0, signal: null, timedOut: false }; +function fixture(t) { + const root = mkdtempSync(path.join(tmpdir(), 'openbitfun-stack-diagnostic-')); + t.after(() => { + assert.equal(path.dirname(root), path.resolve(tmpdir())); + rmSync(root, { recursive: true, force: true }); + }); + const artifact = { + reason: 'compiler-artifact', profile: { test: true, debuginfo: 0 }, + features: ['custom-feature'], executable: path.join(root, 'target', 'debug', 'deps', 'tests'), + manifest_path: path.join(root, 'crate', 'Cargo.toml'), + }; + return { root, artifact, calls: [], env: { GITHUB_OUTPUT: path.join(root, 'outputs') } }; +} + +function fakeRunner(f, { code = 101, thread = testName, match = true, + extraArtifact, gdbMissing = false, listFails = false, diagnosticThrows = false } = {}) { + return async (command, args, options) => { + f.calls.push({ command, args, ...options }); + const emit = (line, stream = 'stdout') => options.onLine?.(line, stream); + if (command === 'cargo') { + emit(JSON.stringify(f.artifact)); + if (extraArtifact) emit(JSON.stringify(extraArtifact)); + emit('{"message":"test JSON must not disappear"}'); + emit('compiler warning', 'stderr'); + if (thread) emit(`thread '${thread}' (7057) has overflowed its stack`, 'stderr'); + return { ...ok, code }; + } + if (diagnosticThrows) throw new Error('diagnostic fixture failure'); + if (command === 'rustc' && args.includes('target-libdir')) emit('/toolchain/lib'); + if (args.includes('--list')) { + emit(`${match ? testName : `${testName}_other`}: test`); + return { ...ok, code: listFails ? 1 : 0 }; + } + if (command === 'gdb' && gdbMissing) return { ...ok, code: 1, error: 'spawn gdb ENOENT' }; + emit('running 1 test'); + return ok; + }; +} + +async function execute(f, overrides = {}) { + return runCargoTests({ cargoArgs: ['--locked', '-p', 'example', '--features', 'custom-feature', '--lib'], + outputDir: f.root, env: f.env, platform: 'linux', print: () => {}, + run: fakeRunner(f), ...overrides }); +} + +test('recognizes old and current Rust overflow signatures but not ordinary panic text', () => { + assert.equal(overflowThread(`thread '${testName}' has overflowed its stack`), testName); + assert.equal(overflowThread(`thread '${testName}' (7057) has overflowed its stack`), testName); + assert.equal(overflowThread(`thread '${testName}' panicked at source.rs:1`), undefined); +}); + +for (const platform of ['linux', 'darwin', 'win32']) { + for (const [label, code, thread] of [['success', 0, testName], ['ordinary failure', 101, null]]) { + test(`${platform} ${label} runs Cargo exactly once with no diagnostics or stack override`, async (t) => { + const f = fixture(t); + assert.equal(await execute(f, { platform, run: fakeRunner(f, { code, thread }) }), code); + assert.equal(f.calls.length, 1); + assert.equal(f.calls[0].command, 'cargo'); + assert.deepEqual(f.calls[0].args, ['test', '--message-format=json-render-diagnostics', + '--locked', '-p', 'example', '--features', 'custom-feature', '--lib']); + assert.equal(f.calls[0].env.RUST_MIN_STACK, undefined); + assert.equal(existsSync(f.env.GITHUB_OUTPUT), false); + assert.equal(existsSync(path.join(f.root, 'summary.json')), false); + assert.match(readFileSync(path.join(f.root, 'cargo-test.log'), 'utf8'), /test JSON must not disappear/); + }); + } +} + +test('loader paths retain platform defaults and avoid duplicate Windows PATH keys', () => { + assert.equal(loaderEnvironment('linux', { LD_LIBRARY_PATH: '/old' }, ['/new']).LD_LIBRARY_PATH, '/new:/old'); + assert.equal(loaderEnvironment('darwin', { HOME: '/Users/test' }, ['/new']).DYLD_FALLBACK_LIBRARY_PATH, + '/new:/Users/test/lib:/usr/local/lib:/usr/lib'); + const env = { Path: 'C:\\old', PATH: 'C:\\duplicate' }; + const windows = loaderEnvironment('win32', env, ['C:\\new']); + assert.equal(windows.Path, 'C:\\new;C:\\old'); + assert.equal(Object.hasOwn(windows, 'PATH'), false); + assert.equal(env.PATH, 'C:\\duplicate'); +}); + +test('macOS debugger uses batch crash commands and supplies the inferior loader path', () => { + const plan = debuggerPlan('darwin', '/test path/tests', [testName, '--exact'], + { DYLD_FALLBACK_LIBRARY_PATH: '/library path:/usr/lib' }); + assert.equal(plan.command, 'lldb'); + assert.ok(plan.args.includes('--no-lldbinit')); + assert.ok(plan.args.includes('--batch')); + assert.ok(plan.args.includes('settings set target.env-vars "DYLD_FALLBACK_LIBRARY_PATH=/library path:/usr/lib"')); + assert.deepEqual(plan.args.slice(plan.args.indexOf('-k'), plan.args.indexOf('--')), + ['-k', 'thread backtrace -c 80 all', '-k', 'register read', '-k', 'disassemble --pc --count 16']); + assert.deepEqual(plan.args.slice(-4), ['--', '/test path/tests', testName, '--exact']); +}); + +test('Windows discovers the SDK console debugger and uses local symbols and an explicit command file', () => { + const expected = 'C:\\Program Files (x86)\\Windows Kits\\10\\Debuggers\\x64\\cdb.exe'; + const plan = debuggerPlan('win32', 'C:\\test path\\tests.exe', [testName], + { 'ProgramFiles(x86)': 'C:\\Program Files (x86)', _NT_SYMBOL_PATH: 'srv*https://example.test/symbols' }, + 'C:\\logs\\cdb-commands.txt', { arch: 'x64', fileExists: (file) => file === expected }); + assert.equal(plan.command, expected); + assert.deepEqual(plan.args, ['-G', '-y', 'C:\\test path', '-cf', 'C:\\logs\\cdb-commands.txt', 'C:\\test path\\tests.exe', testName]); + assert.equal(plan.env._NT_SYMBOL_PATH, ''); + assert.equal(plan.env._NT_ALT_SYMBOL_PATH, ''); + for (const exception of ['sov', 'av', '0xc0000409', '0x40000015']) assert.ok(plan.commands.includes(`" ${exception}`)); + assert.ok(plan.commands.includes('~* kb 0n80')); + assert.ok(plan.commands.endsWith('\ng')); +}); + +for (const [platform, debuggerName] of [['darwin', 'lldb'], ['win32', 'cdb']]) { + test(`${platform} reruns preserve failure and continue after a missing debugger`, async (t) => { + const f = fixture(t); + const fake = fakeRunner(f); + const run = async (command, args, options) => { + const result = await fake(command, args, options); + if (command === 'lldb' || command.endsWith('cdb.exe')) return { ...ok, code: 1, error: 'ENOENT' }; + return result; + }; + assert.equal(await execute(f, { platform, run }), 101); + assert.equal(f.calls.filter((call) => call.command === 'cargo').length, 1); + const report = JSON.parse(readFileSync(path.join(f.root, 'summary.json'), 'utf8')); + assert.equal(report.debugger, debuggerName); + assert.equal(report.stages.find((stage) => stage.name === debuggerName).error, 'ENOENT'); + assert.equal(report.stages.at(-1).name, 'large-stack'); + assert.equal(f.calls.at(-1).env.RUST_MIN_STACK, '16777216'); + if (platform === 'win32') assert.match(readFileSync(path.join(f.root, 'cdb-commands.txt'), 'utf8'), /sxe/); + }); +} + +test('overflow uses the exact built artifact and package cwd, retaining original failure after passing reruns', async (t) => { + const f = fixture(t); + f.env.RUST_MIN_STACK = '2097152'; + assert.equal(await execute(f), 101); + assert.equal(f.calls.filter((call) => call.command === 'cargo').length, 1); + const reruns = f.calls.filter((call) => call.command === f.artifact.executable && !call.args.includes('--list')); + assert.equal(reruns.length, 2); + for (const call of reruns) { + assert.deepEqual(call.args, [testName, '--exact', '--include-ignored', '--nocapture', '--test-threads=1']); + assert.equal(call.cwd, path.dirname(f.artifact.manifest_path)); + assert.ok(call.timeoutMs > 0 && call.timeoutMs <= 30_000); + } + assert.equal(reruns[0].env.RUST_MIN_STACK, '2097152'); + assert.equal(reruns[1].env.RUST_MIN_STACK, '16777216'); + assert.equal(f.env.RUST_MIN_STACK, '2097152'); + const gdb = f.calls.find((call) => call.command === 'gdb'); + assert.ok(gdb.args.includes('thread apply all bt 80')); + assert.ok(gdb.args.includes('handle SIGSEGV stop print nopass')); + assert.equal(gdb.env.RUST_MIN_STACK, '2097152'); + assert.ok(gdb.timeoutMs <= 60_000); + assert.match(readFileSync(f.env.GITHUB_OUTPUT, 'utf8'), /stack_overflow=true/); + const report = JSON.parse(readFileSync(path.join(f.root, 'summary.json'), 'utf8')); + assert.equal(report.original.code, 101); + assert.equal(report.selectedExecutable, f.artifact.executable); + assert.deepEqual(report.artifacts[0].features, ['custom-feature']); +}); + +test('Windows stack-overflow NTSTATUS is preserved without assuming Cargo exits with 101', async (t) => { + const f = fixture(t); + const status = 0xc00000fd; + assert.equal(await execute(f, { platform: 'win32', run: fakeRunner(f, { code: status }) }), status); + const report = JSON.parse(readFileSync(path.join(f.root, 'summary.json'), 'utf8')); + assert.equal(report.original.code, status); +}); + +for (const status of [0xc00000fd, -1073741571]) { + test(`Windows unnamed stack overflow (${status}) retains evidence without guessing a test`, async (t) => { + const f = fixture(t); + assert.equal(await execute(f, { + platform: 'win32', run: fakeRunner(f, { code: status, thread: null }), + }), status); + const report = JSON.parse(readFileSync(path.join(f.root, 'summary.json'), 'utf8')); + assert.equal(report.thread, null); + assert.match(report.note, /without a named test thread/); + assert.equal(f.calls.some((call) => call.args.includes('--list')), false); + assert.match(readFileSync(f.env.GITHUB_OUTPUT, 'utf8'), /stack_overflow=true/); + }); +} + +for (const [label, options] of [ + ['worker thread', { thread: 'tokio-runtime-worker', match: false }], + ['substring only', { match: false }], + ['listing failure', { listFails: true }], +]) { + test(`${label} preserves evidence without running zero tests as a reproduction`, async (t) => { + const f = fixture(t); + assert.equal(await execute(f, { run: fakeRunner(f, options) }), 101); + assert.equal(f.calls.some((call) => call.command === 'gdb'), false); + assert.equal(f.calls.some((call) => call.args.includes('--nocapture')), false); + assert.ok(existsSync(path.join(f.root, 'summary.json'))); + }); +} + +test('ambiguous test names across targets do not select an arbitrary binary', async (t) => { + const f = fixture(t); + const extraArtifact = { ...f.artifact, executable: `${f.artifact.executable}-other` }; + assert.equal(await execute(f, { run: fakeRunner(f, { extraArtifact }) }), 101); + assert.equal(f.calls.filter((call) => call.args.includes('--list')).length, 2); + assert.equal(f.calls.some((call) => call.command === 'gdb'), false); +}); + +test('missing GDB still permits the large-stack comparison and records its error', async (t) => { + const f = fixture(t); + assert.equal(await execute(f, { run: fakeRunner(f, { gdbMissing: true }) }), 101); + const report = JSON.parse(readFileSync(path.join(f.root, 'summary.json'), 'utf8')); + assert.match(report.stages.find((stage) => stage.name === 'gdb').error, /ENOENT/); + assert.equal(report.stages.at(-1).name, 'large-stack'); +}); + +test('diagnostic exceptions preserve the original failure and partial report', async (t) => { + const f = fixture(t); + assert.equal(await execute(f, { run: fakeRunner(f, { diagnosticThrows: true }) }), 101); + const report = JSON.parse(readFileSync(path.join(f.root, 'summary.json'), 'utf8')); + assert.match(report.diagnosticError, /diagnostic fixture failure/); +}); + +test('subprocess output streams both channels and preserves a nonzero exit', async () => { + const lines = []; + const result = await runProcess(process.execPath, ['-e', + 'process.stdout.write("out\\n"); process.stderr.write("err\\n"); process.exitCode = 7;'], + { onLine: (line, stream) => lines.push([line, stream]) }); + assert.equal(result.code, 7); + assert.deepEqual(lines.sort(), [['err', 'stderr'], ['out', 'stdout']]); +}); + +test('subprocess timeout terminates a stalled diagnostic', async () => { + const result = await runProcess(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { timeoutMs: 100 }); + assert.equal(result.timedOut, true); + assert.notEqual(result.code, 0); +}); + +test('native timeout terminates diagnostic descendants as well as the parent', { timeout: 10_000 }, async () => { + let descendant; + try { + const result = await runProcess(process.execPath, ['-e', ` + const { spawn } = require('node:child_process'); + const child = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { + windowsHide: true, stdio: 'ignore' + }); + console.log(child.pid); + setInterval(() => {}, 1000); + `], { timeoutMs: 1_000, onLine: (line) => { if (/^\d+$/.test(line)) descendant = Number(line); } }); + assert.ok(descendant, 'The fixture must start its descendant before the timeout'); + assert.equal(result.timedOut, true); + assert.equal(result.cleanupError, undefined); + let alive = true; + for (let attempt = 0; attempt < 50 && alive; attempt++) { + try { + process.kill(descendant, 0); + // Linux may retain a dead, reparented zombie briefly until it is reaped. + if (process.platform === 'linux') { + alive = !/\) Z /.test(readFileSync(`/proc/${descendant}/stat`, 'utf8')); + } + } catch (error) { + if (['ESRCH', 'ENOENT'].includes(error.code)) alive = false; + else throw error; + } + if (alive) await new Promise((resolve) => setTimeout(resolve, 10)); + } + assert.equal(alive, false, 'The diagnostic descendant must not survive its parent'); + } finally { + if (descendant) { + try { process.kill(descendant, 'SIGKILL'); } catch { /* Already terminated. */ } + } + } +}); + +test('missing executable is diagnostic data, not an unhandled process error', async () => { + const result = await runProcess('openbitfun-nonexistent-diagnostic-command', []); + assert.notEqual(result.code, 0); + assert.match(result.error, /ENOENT/); +});