@@ -420,27 +420,65 @@ def do(
420420 ) -> Self | Any :
421421 obj = self ._get_obj (inplace )
422422 target_sets = obj ._resolve_selector (sets )
423+
424+ if not target_sets :
425+ return {} if return_results else obj
426+
427+ index_lookup = {id (s ): idx for idx , s in enumerate (obj ._agentsets )}
428+
423429 if return_results :
424430
425- def make_key (i : int , s : AgentSet ) -> Any :
431+ def make_key (agentset : AgentSet ) -> Any :
426432 if key_by == "name" :
427- return s .name
433+ return agentset .name
428434 if key_by == "index" :
429- return i
435+ try :
436+ return index_lookup [id (agentset )]
437+ except KeyError as exc : # pragma: no cover - defensive
438+ raise ValueError (
439+ "AgentSet not found in registry; cannot key by index."
440+ ) from exc
430441 if key_by == "type" :
431- return type (s )
432- return s # backward-compatible: key by object
433-
434- return {
435- make_key (i , s ): s .do (
436- method_name , * args , return_results = True , inplace = inplace , ** kwargs
442+ return type (agentset )
443+ return agentset # backward-compatible: key by object
444+
445+ results : dict [Any , Any ] = {}
446+ for agentset in target_sets :
447+ key = make_key (agentset )
448+ if key_by == "type" and key in results :
449+ raise ValueError (
450+ "Multiple agent sets of the same type were selected; "
451+ "use key_by='name' or key_by='index' instead."
452+ )
453+ results [key ] = agentset .do (
454+ method_name ,
455+ * args ,
456+ return_results = True ,
457+ inplace = inplace ,
458+ ** kwargs ,
437459 )
438- for i , s in enumerate (target_sets )
439- }
440- obj ._agentsets = [
441- s .do (method_name , * args , return_results = False , inplace = inplace , ** kwargs )
442- for s in target_sets
443- ]
460+ return results
461+
462+ updates : list [tuple [int , AgentSet ]] = []
463+ for agentset in target_sets :
464+ try :
465+ registry_index = index_lookup [id (agentset )]
466+ except KeyError as exc : # pragma: no cover - defensive
467+ raise ValueError (
468+ "AgentSet not found in registry; cannot apply operation."
469+ ) from exc
470+ updated = agentset .do (
471+ method_name ,
472+ * args ,
473+ return_results = False ,
474+ inplace = inplace ,
475+ ** kwargs ,
476+ )
477+ updates .append ((registry_index , updated ))
478+
479+ for registry_index , updated in updates :
480+ obj ._agentsets [registry_index ] = updated
481+ obj ._recompute_ids ()
444482 return obj
445483
446484 @overload
0 commit comments