|
| 1 | +using System.Text.Json; |
| 2 | +using Microsoft.Extensions.DependencyInjection; |
| 3 | +using Microsoft.Extensions.Logging; |
| 4 | +using SharpClaw.Code.Agents.Abstractions; |
| 5 | +using SharpClaw.Code.Agents.Agents; |
| 6 | +using SharpClaw.Code.Agents.Models; |
| 7 | +using SharpClaw.Code.Protocol.Enums; |
| 8 | +using SharpClaw.Code.Protocol.Events; |
| 9 | +using SharpClaw.Code.Protocol.Models; |
| 10 | +using SharpClaw.Code.Protocol.Serialization; |
| 11 | +using SharpClaw.Code.Tools.Abstractions; |
| 12 | +using SharpClaw.Code.Tools.Models; |
| 13 | + |
| 14 | +namespace SharpClaw.Code.Agents.Internal; |
| 15 | + |
| 16 | +/// <summary> |
| 17 | +/// Executes delegated subagent tasks as bounded read-only child runs. |
| 18 | +/// </summary> |
| 19 | +public sealed class SubAgentOrchestrator( |
| 20 | + IServiceProvider serviceProvider, |
| 21 | + IToolExecutor toolExecutor, |
| 22 | + ILogger<SubAgentOrchestrator> logger) : ISubAgentOrchestrator |
| 23 | +{ |
| 24 | + /// <inheritdoc /> |
| 25 | + public async Task<SubAgentBatchExecutionResult> ExecuteAsync( |
| 26 | + SubAgentBatchRequest request, |
| 27 | + ToolExecutionContext context, |
| 28 | + CancellationToken cancellationToken) |
| 29 | + { |
| 30 | + ArgumentNullException.ThrowIfNull(request); |
| 31 | + ArgumentNullException.ThrowIfNull(context); |
| 32 | + |
| 33 | + if (request.Tasks is not { Length: > 0 }) |
| 34 | + { |
| 35 | + throw new InvalidOperationException("The subagent request must include at least one task."); |
| 36 | + } |
| 37 | + |
| 38 | + if (request.Tasks.Length > SubAgentToolContract.MaxTasks) |
| 39 | + { |
| 40 | + throw new InvalidOperationException($"The subagent request exceeds the limit of {SubAgentToolContract.MaxTasks} tasks."); |
| 41 | + } |
| 42 | + |
| 43 | + var runs = request.Tasks |
| 44 | + .Select((task, index) => ExecuteSingleAsync(task, index, context, cancellationToken)) |
| 45 | + .ToArray(); |
| 46 | + var completedRuns = await Task.WhenAll(runs).ConfigureAwait(false); |
| 47 | + |
| 48 | + var taskResults = completedRuns.Select(static run => run.TaskResult).ToArray(); |
| 49 | + var events = completedRuns.SelectMany(static run => run.Events).ToArray(); |
| 50 | + var result = new SubAgentBatchResult( |
| 51 | + Tasks: taskResults, |
| 52 | + CompletedCount: taskResults.Count(static task => task.Succeeded), |
| 53 | + FailedCount: taskResults.Count(static task => !task.Succeeded)); |
| 54 | + |
| 55 | + return new SubAgentBatchExecutionResult(result, events); |
| 56 | + } |
| 57 | + |
| 58 | + private async Task<SingleTaskExecutionResult> ExecuteSingleAsync( |
| 59 | + SubAgentTaskRequest task, |
| 60 | + int index, |
| 61 | + ToolExecutionContext parentContext, |
| 62 | + CancellationToken cancellationToken) |
| 63 | + { |
| 64 | + ArgumentNullException.ThrowIfNull(task); |
| 65 | + var goal = task.Goal?.Trim(); |
| 66 | + var expectedOutput = task.ExpectedOutput?.Trim(); |
| 67 | + if (string.IsNullOrWhiteSpace(goal) || string.IsNullOrWhiteSpace(expectedOutput)) |
| 68 | + { |
| 69 | + throw new InvalidOperationException("Each subagent task requires both goal and expectedOutput."); |
| 70 | + } |
| 71 | + |
| 72 | + var taskId = $"subtask-{index + 1:D2}-{Guid.NewGuid():N}"; |
| 73 | + var delegatedTask = new DelegatedTaskContract( |
| 74 | + taskId, |
| 75 | + goal, |
| 76 | + expectedOutput, |
| 77 | + NormalizeConstraints(task.Constraints)); |
| 78 | + |
| 79 | + try |
| 80 | + { |
| 81 | + var subAgentWorker = serviceProvider.GetRequiredService<SubAgentWorker>(); |
| 82 | + var result = await subAgentWorker.RunAsync( |
| 83 | + new AgentRunContext( |
| 84 | + SessionId: parentContext.SessionId, |
| 85 | + TurnId: parentContext.TurnId, |
| 86 | + Prompt: goal, |
| 87 | + WorkingDirectory: parentContext.WorkingDirectory, |
| 88 | + Model: string.IsNullOrWhiteSpace(parentContext.Model) ? "default" : parentContext.Model!, |
| 89 | + PermissionMode: PermissionMode.ReadOnly, |
| 90 | + OutputFormat: OutputFormat.Text, |
| 91 | + ToolExecutor: toolExecutor, |
| 92 | + Metadata: BuildChildMetadata(parentContext), |
| 93 | + ParentAgentId: parentContext.AgentId, |
| 94 | + DelegatedTask: delegatedTask, |
| 95 | + PrimaryMode: PrimaryMode.Plan, |
| 96 | + ToolMutationRecorder: null, |
| 97 | + ConversationHistory: null, |
| 98 | + IsInteractive: false, |
| 99 | + ApprovalSettings: ApprovalSettings.Empty), |
| 100 | + cancellationToken).ConfigureAwait(false); |
| 101 | + |
| 102 | + return new SingleTaskExecutionResult( |
| 103 | + new SubAgentTaskResult( |
| 104 | + TaskId: taskId, |
| 105 | + Goal: goal, |
| 106 | + ExpectedOutput: expectedOutput, |
| 107 | + Succeeded: true, |
| 108 | + Output: string.IsNullOrWhiteSpace(result.Output) ? "(no output)" : result.Output.Trim(), |
| 109 | + ErrorMessage: null, |
| 110 | + AgentId: result.AgentId), |
| 111 | + result.Events ?? []); |
| 112 | + } |
| 113 | + catch (OperationCanceledException) |
| 114 | + { |
| 115 | + throw; |
| 116 | + } |
| 117 | + catch (Exception exception) |
| 118 | + { |
| 119 | + logger.LogWarning( |
| 120 | + exception, |
| 121 | + "Delegated subagent task {TaskId} failed for session {SessionId}, turn {TurnId}.", |
| 122 | + taskId, |
| 123 | + parentContext.SessionId, |
| 124 | + parentContext.TurnId); |
| 125 | + |
| 126 | + return new SingleTaskExecutionResult( |
| 127 | + new SubAgentTaskResult( |
| 128 | + TaskId: taskId, |
| 129 | + Goal: goal, |
| 130 | + ExpectedOutput: expectedOutput, |
| 131 | + Succeeded: false, |
| 132 | + Output: null, |
| 133 | + ErrorMessage: exception.Message, |
| 134 | + AgentId: SubAgentWorker.SubAgentId), |
| 135 | + []); |
| 136 | + } |
| 137 | + } |
| 138 | + |
| 139 | + private static string[] NormalizeConstraints(string[]? constraints) |
| 140 | + => constraints? |
| 141 | + .Where(static value => !string.IsNullOrWhiteSpace(value)) |
| 142 | + .Select(static value => value.Trim()) |
| 143 | + .Distinct(StringComparer.Ordinal) |
| 144 | + .ToArray() |
| 145 | + ?? []; |
| 146 | + |
| 147 | + private static Dictionary<string, string> BuildChildMetadata(ToolExecutionContext parentContext) |
| 148 | + { |
| 149 | + var metadata = new Dictionary<string, string>(StringComparer.Ordinal); |
| 150 | + if (parentContext.Metadata is not null |
| 151 | + && parentContext.Metadata.TryGetValue("provider", out var provider) |
| 152 | + && !string.IsNullOrWhiteSpace(provider)) |
| 153 | + { |
| 154 | + metadata["provider"] = provider; |
| 155 | + } |
| 156 | + |
| 157 | + metadata[SharpClawWorkflowMetadataKeys.AgentAllowedToolsJson] = JsonSerializer.Serialize( |
| 158 | + SubAgentToolContract.AllowedReadOnlyTools, |
| 159 | + ProtocolJsonContext.Default.StringArray); |
| 160 | + return metadata; |
| 161 | + } |
| 162 | + |
| 163 | + private sealed record SingleTaskExecutionResult( |
| 164 | + SubAgentTaskResult TaskResult, |
| 165 | + IReadOnlyList<RuntimeEvent> Events); |
| 166 | +} |
0 commit comments