From 9b31b093707a4d091b053b0267ba336f6385ae5a Mon Sep 17 00:00:00 2001 From: Tamir Dresher Date: Thu, 11 Jun 2026 18:03:50 +0300 Subject: [PATCH 1/2] Squad.Agents.AI 0.5.0: auto-inject --agent squad (CLI parity by default) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The whole point of SquadAgent is to wrap a Squad coordinator team — but the 0.4.x SDK launched the underlying copilot.exe with the CLI's built-in generic agent. The coordinator therefore had no instructions to eager-execute, fan out, or dispatch via the task tool, so it role-played responses inline. Concretely: this SDK call builder.Services.AddSquadAgent(o => o.SquadFolderPath = teamRoot); did NOT behave the same as running copilot --agent squad interactively against the same team root. Consumers had to remember to add `opts.CliArgs.Add(""--agent""); opts.CliArgs.Add(""squad"");` themselves, which is an SDK leak — the class is literally called SquadAgent. 0.5.0 makes --agent squad the SDK default: * New `SquadAgentOptions.AgentFileName` (defaults to `""squad""`). * On client construction, SquadAgent looks for `{teamRoot}/.github/agents/{AgentFileName}.agent.md`. If it exists, `--agent {AgentFileName}` is auto-prepended to the CLI args. * If the file is missing (folder not Squad-initialized), the inject is silently skipped and a Debug log line explains why. The CLI then starts with its default agent, which is what 0.4.x did anyway. * If the consumer already supplied `--agent X` in `CliArgs`, the explicit value wins and we do NOT add a second one. * Set `AgentFileName = null` (or whitespace) to opt out entirely. Net effect: SquadAgent.RunAsync now matches `copilot --agent squad` for any Squad-initialized team root, without the consumer doing anything. ## Tests 64 -> 71 tests, all passing on net8.0/9.0/10.0. New `SquadAgentDefaultAgentFlagTests` (uses a per-test temp dir to scaffold or omit the agent file deterministically): * Default AgentFileName is ""squad"" * Auto-inject when squad.agent.md exists * No inject when the file is missing (graceful degradation) * Explicit --agent in CliArgs wins (no second --agent added) * Custom AgentFileName=""data"" injects --agent data when data.agent.md exists * AgentFileName=null opts out entirely * AgentFileName=whitespace opts out entirely Backward compatibility: existing routing tests use a non-existent `C:\squad-team-root` path, so the file-existence check silently skips the inject — those tests continue to pass with no changes. ## Files * `src/Squad.Agents.AI/SquadAgentOptions.cs` — new `AgentFileName` property with XML doc covering the default, the opt-out, and the not-yet-initialized fallback. * `src/Squad.Agents.AI/SquadAgent.cs` — auto-inject logic in `CreateCopilotClient` (after the `--allow-all` block, before `options.CliArgs` are appended) with file-existence + already-supplied guards and a Debug log when the file is missing. * `src/Squad.Agents.AI/Squad.Agents.AI.csproj` — bump 0.4.0 -> 0.5.0. * `src/Squad.Agents.AI/README.md` — new ""Coordinator agent selection"" section with the precedence table; `AgentFileName` row added to Key Options table. * `+test/Squad.Agents.AI.Tests/SquadAgentDefaultAgentFlagTests.cs` Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/Squad.Agents.AI/README.md | 13 ++ src/Squad.Agents.AI/Squad.Agents.AI.csproj | 2 +- src/Squad.Agents.AI/SquadAgent.cs | 39 ++++ src/Squad.Agents.AI/SquadAgentOptions.cs | 29 +++ .../SquadAgentDefaultAgentFlagTests.cs | 212 ++++++++++++++++++ 5 files changed, 294 insertions(+), 1 deletion(-) create mode 100644 test/Squad.Agents.AI.Tests/SquadAgentDefaultAgentFlagTests.cs diff --git a/src/Squad.Agents.AI/README.md b/src/Squad.Agents.AI/README.md index 78a3d89d0..802829fd2 100644 --- a/src/Squad.Agents.AI/README.md +++ b/src/Squad.Agents.AI/README.md @@ -150,6 +150,18 @@ squad://localhost?teamRoot=C%3A%5Cteam&cliPath=C%3A%5Ctools%5Ccopilot.exe&cliArg Parsed URI query keys: `teamRoot`, `cliPath`, `cwd`, `cliArgs` (semicolon-separated), and `env` (`key=value;key2=value2`). Unknown URI host/protocol values are reserved for future use. +## Coordinator agent selection + +`SquadAgent` exists to wrap a Squad coordinator team, so it passes `--agent squad` to the underlying `copilot.exe` child process by default. That tells the CLI to load `.github/agents/squad.agent.md` as the agent definition — which is what teaches the coordinator to eager-execute, fan out, and dispatch through the `task` tool. Without it, the CLI uses its built-in generic agent and the coordinator role-plays responses inline instead of spawning real subagents — producing SDK behavior that does NOT match running `copilot --agent squad` interactively against the same team root. + +| Scenario | What the SDK does | +|---|---| +| Default — `squad.agent.md` exists | Auto-adds `--agent squad` | +| `squad.agent.md` not found at `.github/agents/` | Silently skips `--agent` (graceful degradation for not-yet-initialized teams; logs a Debug message) | +| Consumer set `AgentFileName = "data"` (and file exists) | Auto-adds `--agent data` | +| Consumer set `AgentFileName = null` | Skips `--agent` entirely | +| Consumer already supplied `--agent X` in `CliArgs` | Respects the explicit value; does not add a second `--agent` | + ## Subagent observability — first-class OpenTelemetry `Squad.Agents.AI` emits one OpenTelemetry `Activity` per subagent dispatch out of the box. Hosts that subscribe to the activity source see one `squad.subagent {Name}` span per spawn, with the subagent name as a tag and timeline annotations (`squad.subagent.start`, `squad.subagent.message`, `squad.subagent.completed`, `squad.subagent.failed`) marking every state transition. @@ -196,6 +208,7 @@ builder.Services.AddSquadAgent(o => | `ConfigureCopilotClient` | Advanced delegate for customizing `CopilotClientOptions`. Routing properties are guarded; see BYOK section. | | `TraceEvents` | Enables verbose SDK logging and emits a startup warning when enabled. | | `AgentName` | Display name for the resulting `AIAgent`; defaults to `Squad`. | +| `AgentFileName` | Name of the agent definition under `.github/agents/{name}.agent.md` to load via the CLI's `--agent` flag. Defaults to `"squad"`. Set to `null` to skip auto-injection; the file-existence check makes this safe to leave on for not-yet-initialized teams. | | `Instructions` | Optional system instructions passed to the inner Copilot agent. | | `EmitSubagentActivities` | Whether the SDK opens an OpenTelemetry `Activity` per subagent dispatch and annotates lifecycle events. Defaults to `true`. Set to `false` to handle telemetry from your own `OnSubagentTrace` callback. | | `OnSubagentTrace` | Optional callback invoked for every typed `SquadAgentTraceEvent`. Independent of `EmitSubagentActivities` — both can be on simultaneously. | diff --git a/src/Squad.Agents.AI/Squad.Agents.AI.csproj b/src/Squad.Agents.AI/Squad.Agents.AI.csproj index 40fa8553b..e2187fc5b 100644 --- a/src/Squad.Agents.AI/Squad.Agents.AI.csproj +++ b/src/Squad.Agents.AI/Squad.Agents.AI.csproj @@ -17,7 +17,7 @@ MIT README.md true - 0.4.0 + 0.5.0 diff --git a/src/Squad.Agents.AI/SquadAgent.cs b/src/Squad.Agents.AI/SquadAgent.cs index c54528063..147869f00 100644 --- a/src/Squad.Agents.AI/SquadAgent.cs +++ b/src/Squad.Agents.AI/SquadAgent.cs @@ -242,6 +242,45 @@ private static CopilotClient CreateCopilotClient(SquadAgentOptions options, ILog { combinedCliArgs.Add("--allow-all"); } + + // ── Default coordinator agent selection ──────────────────────────── + // SquadAgent wraps a Squad coordinator team. The CLI's `--agent squad` + // flag loads `.github/agents/squad.agent.md` as the agent definition, + // which is what teaches the coordinator to eager-execute, fan out, and + // dispatch via the task tool. Without it the CLI uses its generic + // agent and the coordinator role-plays responses inline instead of + // spawning subagents — which produces an SDK behaviour that does NOT + // match running `copilot --agent squad` interactively against the same + // team root. + // + // We auto-add `--agent {AgentFileName}` (default "squad") unless: + // 1. The host already supplied --agent explicitly in CliArgs + // 2. AgentFileName is null (explicit opt-out) + // 3. The agent file does not exist on disk (graceful degradation + // for folders that are not yet Squad-initialized) + // ─────────────────────────────────────────────────────────────────── + bool hostSuppliedAgent = options.CliArgs.Any(a => + string.Equals(a, "--agent", StringComparison.OrdinalIgnoreCase)); + if (!hostSuppliedAgent && !string.IsNullOrWhiteSpace(options.AgentFileName)) + { + var teamRoot = options.Cwd ?? options.SquadFolderPath; + if (!string.IsNullOrWhiteSpace(teamRoot)) + { + var agentFilePath = Path.Combine(teamRoot, ".github", "agents", $"{options.AgentFileName}.agent.md"); + if (File.Exists(agentFilePath)) + { + combinedCliArgs.Add("--agent"); + combinedCliArgs.Add(options.AgentFileName); + } + else + { + logger?.LogDebug( + "SquadAgentOptions.AgentFileName is '{AgentFileName}' but the file was not found at '{AgentFilePath}'. Skipping --agent argument; the CLI will fall back to its default agent.", + options.AgentFileName, agentFilePath); + } + } + } + combinedCliArgs.AddRange(options.CliArgs); // Only override the SDK's default child-process connection when the consumer diff --git a/src/Squad.Agents.AI/SquadAgentOptions.cs b/src/Squad.Agents.AI/SquadAgentOptions.cs index 295c76077..183f38c4d 100644 --- a/src/Squad.Agents.AI/SquadAgentOptions.cs +++ b/src/Squad.Agents.AI/SquadAgentOptions.cs @@ -82,6 +82,35 @@ public sealed class SquadAgentOptions /// public string AgentName { get; set; } = "Squad"; + /// + /// Gets or sets the Copilot CLI agent definition file (under .github/agents/) the + /// underlying copilot.exe child process should load via the CLI's --agent + /// flag. Defaults to "squad", which selects .github/agents/squad.agent.md + /// — the Squad coordinator system prompt that drives eager execution, parallel fan-out, + /// and dispatch through the task tool. + /// + /// + /// + /// The whole reason exists is to wrap a Squad coordinator team, + /// so the SDK passes --agent squad by default. Without it the CLI uses its built-in + /// generic agent and the coordinator role-plays responses inline instead of dispatching + /// real subagents — exactly the inconsistency between copilot --agent squad (CLI) + /// and SquadAgent.RunAsync (SDK) that this default eliminates. + /// + /// + /// When the named file does not exist at {team-root}/.github/agents/{AgentFileName}.agent.md + /// (e.g. the team root is not Squad-initialized yet), the SDK silently skips the + /// --agent argument so the CLI can still start with its default agent. + /// + /// + /// Set to to disable the auto-inject entirely. Set to a different + /// name (e.g. "data") to load a custom agent file. If the consumer already supplied + /// --agent in , that explicit value wins and the default is + /// not added. + /// + /// + public string? AgentFileName { get; set; } = "squad"; + /// /// Gets or sets optional system instructions passed to the inner Copilot-backed agent. /// diff --git a/test/Squad.Agents.AI.Tests/SquadAgentDefaultAgentFlagTests.cs b/test/Squad.Agents.AI.Tests/SquadAgentDefaultAgentFlagTests.cs new file mode 100644 index 000000000..a59264e95 --- /dev/null +++ b/test/Squad.Agents.AI.Tests/SquadAgentDefaultAgentFlagTests.cs @@ -0,0 +1,212 @@ +using System.Reflection; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Xunit; + +namespace Squad.Agents.AI.Tests; + +/// +/// Tests for the 0.5.0 behaviour where SquadAgent auto-injects +/// --agent {AgentFileName} into the underlying copilot.exe CLI args, so +/// the wrapped agent picks up .github/agents/squad.agent.md by default +/// — matching what copilot --agent squad does interactively. +/// +public class SquadAgentDefaultAgentFlagTests : IDisposable +{ + private readonly string _tempRoot; + + public SquadAgentDefaultAgentFlagTests() + { + // Each test gets its own throwaway team root so file-existence checks + // are deterministic and we can scaffold or omit the squad.agent.md file + // per scenario without contaminating siblings. + _tempRoot = Path.Combine(Path.GetTempPath(), "squad-agents-ai-tests", Guid.NewGuid().ToString("n")); + Directory.CreateDirectory(_tempRoot); + } + + public void Dispose() + { + try { Directory.Delete(_tempRoot, recursive: true); } + catch { /* best effort */ } + } + + private string ScaffoldAgentFile(string agentName) + { + var dir = Path.Combine(_tempRoot, ".github", "agents"); + Directory.CreateDirectory(dir); + var path = Path.Combine(dir, $"{agentName}.agent.md"); + File.WriteAllText(path, $"# {agentName}\n\nstub agent file for tests"); + return path; + } + + [Fact] + public void Options_AgentFileName_DefaultsToSquad() + { + var options = new SquadAgentOptions(); + Assert.Equal("squad", options.AgentFileName); + } + + [Fact] + public void AddSquadAgent_AutoInjectsAgentSquad_WhenSquadAgentMdExists() + { + ScaffoldAgentFile("squad"); + + var agent = CreateAgent(opts => + { + opts.SquadFolderPath = _tempRoot; + opts.Cwd = _tempRoot; + }); + + var args = GetConnectionArgs(agent); + AssertContainsAgent(args, "squad"); + } + + [Fact] + public void AddSquadAgent_DoesNotInjectAgent_WhenAgentFileMissing() + { + // No .github/agents/squad.agent.md scaffolded — the SDK should NOT + // pass --agent squad because the CLI would error on a missing file. + var agent = CreateAgent(opts => + { + opts.SquadFolderPath = _tempRoot; + opts.Cwd = _tempRoot; + }); + + var args = GetConnectionArgs(agent); + Assert.DoesNotContain("--agent", args); + } + + [Fact] + public void AddSquadAgent_RespectsExplicitAgentInCliArgs() + { + // Scaffold the default file so we'd auto-inject if the consumer hadn't + // already supplied --agent. + ScaffoldAgentFile("squad"); + ScaffoldAgentFile("data"); + + var agent = CreateAgent(opts => + { + opts.SquadFolderPath = _tempRoot; + opts.Cwd = _tempRoot; + opts.CliArgs.Add("--agent"); + opts.CliArgs.Add("data"); + }); + + var args = GetConnectionArgs(agent); + + // Exactly ONE --agent in the args, and it's "data" (the user-supplied one). + var agentIndices = args.Select((a, i) => (a, i)) + .Where(t => string.Equals(t.a, "--agent", StringComparison.OrdinalIgnoreCase)) + .Select(t => t.i) + .ToList(); + Assert.Single(agentIndices); + Assert.Equal("data", args[agentIndices[0] + 1]); + } + + [Fact] + public void AddSquadAgent_RespectsCustomAgentFileName_WhenFileExists() + { + ScaffoldAgentFile("data"); + + var agent = CreateAgent(opts => + { + opts.SquadFolderPath = _tempRoot; + opts.Cwd = _tempRoot; + opts.AgentFileName = "data"; + }); + + var args = GetConnectionArgs(agent); + AssertContainsAgent(args, "data"); + } + + [Fact] + public void AddSquadAgent_DoesNotInjectAgent_WhenAgentFileNameIsNull() + { + // Opt-out: setting AgentFileName=null disables the auto-inject even if + // squad.agent.md exists. Used when the consumer wants to drive the + // session with a custom SystemMessage instead of a charter file. + ScaffoldAgentFile("squad"); + + var agent = CreateAgent(opts => + { + opts.SquadFolderPath = _tempRoot; + opts.Cwd = _tempRoot; + opts.AgentFileName = null; + }); + + var args = GetConnectionArgs(agent); + Assert.DoesNotContain("--agent", args); + } + + [Fact] + public void AddSquadAgent_DoesNotInjectAgent_WhenAgentFileNameIsWhitespace() + { + ScaffoldAgentFile("squad"); + + var agent = CreateAgent(opts => + { + opts.SquadFolderPath = _tempRoot; + opts.Cwd = _tempRoot; + opts.AgentFileName = " "; + }); + + var args = GetConnectionArgs(agent); + Assert.DoesNotContain("--agent", args); + } + + // ── helpers ───────────────────────────────────────────────────────────── + + private static SquadAgent CreateAgent(Action configure) + { + var services = new ServiceCollection(); + services.AddSingleton(new ConfigurationBuilder().Build()); + services.AddLogging(); + services.AddSquadAgent(opts => + { + opts.CliPath = @"C:\fake-copilot\copilot.exe"; + configure(opts); + }); + return services.BuildServiceProvider().GetRequiredService(); + } + + private static IList GetConnectionArgs(SquadAgent agent) + { + var client = GetField(agent, "_copilotClient"); + var clientOptions = GetField(client, "_options"); + var connection = GetProperty(clientOptions, "Connection"); + Assert.NotNull(connection); + var args = GetProperty>(connection!, "Args"); + Assert.NotNull(args); + return args!; + } + + private static void AssertContainsAgent(IList args, string expectedName) + { + // CLI args must be a `--agent ` adjacent pair, not just two unrelated tokens. + for (var i = 0; i < args.Count - 1; i++) + { + if (string.Equals(args[i], "--agent", StringComparison.OrdinalIgnoreCase) && + string.Equals(args[i + 1], expectedName, StringComparison.Ordinal)) + { + return; + } + } + Assert.Fail($"Expected `--agent {expectedName}` in CLI args; got: [{string.Join(", ", args)}]"); + } + + private static T GetField(object instance, string fieldName) + { + var f = instance.GetType().GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic); + Assert.NotNull(f); + var v = f!.GetValue(instance); + Assert.NotNull(v); + return (T)v!; + } + + private static T? GetProperty(object instance, string propertyName) + { + var p = instance.GetType().GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + Assert.NotNull(p); + return (T?)p!.GetValue(instance); + } +} From 304ab35a61d6ba80c2e10a3c1c9adc582b05304d Mon Sep 17 00:00:00 2001 From: Tamir Dresher Date: Thu, 11 Jun 2026 18:14:12 +0300 Subject: [PATCH 2/2] amend: use SessionConfig.Agent instead of --agent CLI args MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GitHub.Copilot SDK's SessionConfigBase exposes an Agent (string) property that is the first-class equivalent of the Copilot CLI's --agent flag. It discovers and loads .github/agents/{name}.agent.md exactly the same way the CLI does, but without us having to munge CliArgs. Switch the 0.5.0 default-coordinator-agent implementation: - SquadAgent now sets sessionConfig.Agent = options.AgentFileName (default ""squad"") right after constructing the SessionConfig, before ConfigureSession runs. - Drop the --agent CliArgs hack (we no longer need to detect ""did the consumer already pass --agent?"" because ConfigureSession naturally wins over our default). - Tests now assert against sessionConfig.Agent via reflection over the inner DelegatingAIAgent — exactly what consumers using ConfigureSession would see. - README ""Coordinator agent selection"" section reworded to say ""sets SessionConfig.Agent"" instead of ""auto-adds --agent"". 71/71 tests still pass on net8.0/9.0/10.0. The fifth new test (ConfigureSession_CanOverrideAutoSetAgent) explicitly proves the ConfigureSession callback can replace the auto-set value, which is the clean override path now that --agent CliArgs is gone. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/Squad.Agents.AI/README.md | 14 +- src/Squad.Agents.AI/SquadAgent.cs | 68 +++--- src/Squad.Agents.AI/SquadAgentOptions.cs | 35 +-- .../SquadAgentDefaultAgentFlagTests.cs | 212 ------------------ .../SquadAgentDefaultAgentTests.cs | 194 ++++++++++++++++ 5 files changed, 249 insertions(+), 274 deletions(-) delete mode 100644 test/Squad.Agents.AI.Tests/SquadAgentDefaultAgentFlagTests.cs create mode 100644 test/Squad.Agents.AI.Tests/SquadAgentDefaultAgentTests.cs diff --git a/src/Squad.Agents.AI/README.md b/src/Squad.Agents.AI/README.md index 802829fd2..a6dff3e0c 100644 --- a/src/Squad.Agents.AI/README.md +++ b/src/Squad.Agents.AI/README.md @@ -152,15 +152,15 @@ Parsed URI query keys: `teamRoot`, `cliPath`, `cwd`, `cliArgs` (semicolon-separa ## Coordinator agent selection -`SquadAgent` exists to wrap a Squad coordinator team, so it passes `--agent squad` to the underlying `copilot.exe` child process by default. That tells the CLI to load `.github/agents/squad.agent.md` as the agent definition — which is what teaches the coordinator to eager-execute, fan out, and dispatch through the `task` tool. Without it, the CLI uses its built-in generic agent and the coordinator role-plays responses inline instead of spawning real subagents — producing SDK behavior that does NOT match running `copilot --agent squad` interactively against the same team root. +`SquadAgent` exists to wrap a Squad coordinator team, so the SDK sets `SessionConfig.Agent` to `"squad"` by default. That's the SDK-native equivalent of running `copilot --agent squad` from a terminal — it tells the wrapped Copilot session to load `.github/agents/squad.agent.md` as the agent definition, which is what teaches the coordinator to eager-execute, fan out, and dispatch through the `task` tool. Without it, the wrapped session uses its built-in generic agent and the coordinator role-plays responses inline instead of spawning real subagents — producing SDK behavior that does NOT match running `copilot --agent squad` interactively against the same team root. | Scenario | What the SDK does | |---|---| -| Default — `squad.agent.md` exists | Auto-adds `--agent squad` | -| `squad.agent.md` not found at `.github/agents/` | Silently skips `--agent` (graceful degradation for not-yet-initialized teams; logs a Debug message) | -| Consumer set `AgentFileName = "data"` (and file exists) | Auto-adds `--agent data` | -| Consumer set `AgentFileName = null` | Skips `--agent` entirely | -| Consumer already supplied `--agent X` in `CliArgs` | Respects the explicit value; does not add a second `--agent` | +| Default — `squad.agent.md` exists | Sets `sessionConfig.Agent = "squad"` | +| `squad.agent.md` not found at `.github/agents/` | Leaves `sessionConfig.Agent` unset (graceful degradation for not-yet-initialized teams) | +| Consumer sets `AgentFileName = "data"` (and file exists) | Sets `sessionConfig.Agent = "data"` | +| Consumer sets `AgentFileName = null` | Leaves `sessionConfig.Agent` unset | +| Consumer overrides `sessionConfig.Agent` inside `ConfigureSession` | The `ConfigureSession` callback runs after the default is applied, so it always wins | ## Subagent observability — first-class OpenTelemetry @@ -208,7 +208,7 @@ builder.Services.AddSquadAgent(o => | `ConfigureCopilotClient` | Advanced delegate for customizing `CopilotClientOptions`. Routing properties are guarded; see BYOK section. | | `TraceEvents` | Enables verbose SDK logging and emits a startup warning when enabled. | | `AgentName` | Display name for the resulting `AIAgent`; defaults to `Squad`. | -| `AgentFileName` | Name of the agent definition under `.github/agents/{name}.agent.md` to load via the CLI's `--agent` flag. Defaults to `"squad"`. Set to `null` to skip auto-injection; the file-existence check makes this safe to leave on for not-yet-initialized teams. | +| `AgentFileName` | Name of the agent definition under `.github/agents/{name}.agent.md` to load via `SessionConfig.Agent` (the SDK equivalent of the Copilot CLI's `--agent` flag). Defaults to `"squad"`. Set to `null` to skip auto-selection; the file-existence check makes this safe to leave on for not-yet-initialized teams. Override `sessionConfig.Agent` from inside `ConfigureSession` for full control. | | `Instructions` | Optional system instructions passed to the inner Copilot agent. | | `EmitSubagentActivities` | Whether the SDK opens an OpenTelemetry `Activity` per subagent dispatch and annotates lifecycle events. Defaults to `true`. Set to `false` to handle telemetry from your own `OnSubagentTrace` callback. | | `OnSubagentTrace` | Optional callback invoked for every typed `SquadAgentTraceEvent`. Independent of `EmitSubagentActivities` — both can be on simultaneously. | diff --git a/src/Squad.Agents.AI/SquadAgent.cs b/src/Squad.Agents.AI/SquadAgent.cs index 147869f00..afdca9653 100644 --- a/src/Squad.Agents.AI/SquadAgent.cs +++ b/src/Squad.Agents.AI/SquadAgent.cs @@ -134,6 +134,36 @@ private static SquadAgentState BuildStateInternal(SquadAgentOptions options, ILo ConfigDirectory = squadConfigDir, EnableConfigDiscovery = true, }; + + // ── Default coordinator agent selection ──────────────────────────── + // SquadAgent wraps a Squad coordinator team. The SDK's SessionConfig.Agent + // property is the first-class equivalent of the Copilot CLI's --agent flag — + // it selects which discovered agent definition (e.g. .github/agents/squad.agent.md) + // to load as the session's system prompt. Without it the CLI uses its built-in + // generic agent and the coordinator role-plays responses inline instead of + // dispatching real subagents — exactly the inconsistency between + // `copilot --agent squad` (CLI) and SquadAgent.RunAsync (SDK) that this + // default eliminates. + // + // We set Agent = AgentFileName (default "squad") unless: + // 1. The host explicitly configured a different Agent via ConfigureSession + // (handled implicitly — ConfigureSession runs after us and wins) + // 2. AgentFileName is null or whitespace (explicit opt-out) + // 3. The agent file does not exist at the conventional path on disk + // (graceful degradation for folders that are not yet Squad-initialized, + // where the CLI would error on `--agent squad`) + // ─────────────────────────────────────────────────────────────────── + if (!string.IsNullOrWhiteSpace(options.AgentFileName) && !string.IsNullOrWhiteSpace(teamRoot)) + { + var agentFilePath = Path.Combine(teamRoot, ".github", "agents", $"{options.AgentFileName}.agent.md"); + if (File.Exists(agentFilePath)) + { + sessionConfig.Agent = options.AgentFileName; + } + // If the file is missing we leave SessionConfig.Agent unset; the SDK will + // start with its default agent, which is what 0.4.x did anyway. + } + if (!string.IsNullOrEmpty(options.Instructions)) { sessionConfig.SystemMessage = new SystemMessageConfig { Content = options.Instructions }; @@ -243,44 +273,6 @@ private static CopilotClient CreateCopilotClient(SquadAgentOptions options, ILog combinedCliArgs.Add("--allow-all"); } - // ── Default coordinator agent selection ──────────────────────────── - // SquadAgent wraps a Squad coordinator team. The CLI's `--agent squad` - // flag loads `.github/agents/squad.agent.md` as the agent definition, - // which is what teaches the coordinator to eager-execute, fan out, and - // dispatch via the task tool. Without it the CLI uses its generic - // agent and the coordinator role-plays responses inline instead of - // spawning subagents — which produces an SDK behaviour that does NOT - // match running `copilot --agent squad` interactively against the same - // team root. - // - // We auto-add `--agent {AgentFileName}` (default "squad") unless: - // 1. The host already supplied --agent explicitly in CliArgs - // 2. AgentFileName is null (explicit opt-out) - // 3. The agent file does not exist on disk (graceful degradation - // for folders that are not yet Squad-initialized) - // ─────────────────────────────────────────────────────────────────── - bool hostSuppliedAgent = options.CliArgs.Any(a => - string.Equals(a, "--agent", StringComparison.OrdinalIgnoreCase)); - if (!hostSuppliedAgent && !string.IsNullOrWhiteSpace(options.AgentFileName)) - { - var teamRoot = options.Cwd ?? options.SquadFolderPath; - if (!string.IsNullOrWhiteSpace(teamRoot)) - { - var agentFilePath = Path.Combine(teamRoot, ".github", "agents", $"{options.AgentFileName}.agent.md"); - if (File.Exists(agentFilePath)) - { - combinedCliArgs.Add("--agent"); - combinedCliArgs.Add(options.AgentFileName); - } - else - { - logger?.LogDebug( - "SquadAgentOptions.AgentFileName is '{AgentFileName}' but the file was not found at '{AgentFilePath}'. Skipping --agent argument; the CLI will fall back to its default agent.", - options.AgentFileName, agentFilePath); - } - } - } - combinedCliArgs.AddRange(options.CliArgs); // Only override the SDK's default child-process connection when the consumer diff --git a/src/Squad.Agents.AI/SquadAgentOptions.cs b/src/Squad.Agents.AI/SquadAgentOptions.cs index 183f38c4d..a696c1174 100644 --- a/src/Squad.Agents.AI/SquadAgentOptions.cs +++ b/src/Squad.Agents.AI/SquadAgentOptions.cs @@ -83,30 +83,31 @@ public sealed class SquadAgentOptions public string AgentName { get; set; } = "Squad"; /// - /// Gets or sets the Copilot CLI agent definition file (under .github/agents/) the - /// underlying copilot.exe child process should load via the CLI's --agent - /// flag. Defaults to "squad", which selects .github/agents/squad.agent.md - /// — the Squad coordinator system prompt that drives eager execution, parallel fan-out, - /// and dispatch through the task tool. + /// Gets or sets the Squad coordinator agent definition file (under .github/agents/) to + /// load as the wrapped session's agent. Defaults to "squad", which selects + /// .github/agents/squad.agent.md — the Squad coordinator system prompt that drives + /// eager execution, parallel fan-out, and dispatch through the task tool. /// /// /// - /// The whole reason exists is to wrap a Squad coordinator team, - /// so the SDK passes --agent squad by default. Without it the CLI uses its built-in - /// generic agent and the coordinator role-plays responses inline instead of dispatching - /// real subagents — exactly the inconsistency between copilot --agent squad (CLI) - /// and SquadAgent.RunAsync (SDK) that this default eliminates. + /// The whole reason exists is to wrap a Squad coordinator team, so + /// the SDK sets by default. Without it, + /// the wrapped session uses its built-in generic agent and the coordinator role-plays + /// responses inline instead of dispatching real subagents — exactly the inconsistency + /// between copilot --agent squad (CLI) and SquadAgent.RunAsync (SDK) that this + /// default eliminates. /// /// - /// When the named file does not exist at {team-root}/.github/agents/{AgentFileName}.agent.md - /// (e.g. the team root is not Squad-initialized yet), the SDK silently skips the - /// --agent argument so the CLI can still start with its default agent. + /// When the named file does not exist at + /// {team-root}/.github/agents/{AgentFileName}.agent.md (e.g. the team root is not + /// Squad-initialized yet), the SDK silently leaves + /// unset so the session can still start with the SDK's default agent. /// /// - /// Set to to disable the auto-inject entirely. Set to a different - /// name (e.g. "data") to load a custom agent file. If the consumer already supplied - /// --agent in , that explicit value wins and the default is - /// not added. + /// Set to (or whitespace) to disable the auto-selection entirely. Set + /// to a different name (e.g. "data") to load a custom agent file. To override the + /// final value, set sessionConfig.Agent from inside — + /// that callback runs after this default is applied. /// /// public string? AgentFileName { get; set; } = "squad"; diff --git a/test/Squad.Agents.AI.Tests/SquadAgentDefaultAgentFlagTests.cs b/test/Squad.Agents.AI.Tests/SquadAgentDefaultAgentFlagTests.cs deleted file mode 100644 index a59264e95..000000000 --- a/test/Squad.Agents.AI.Tests/SquadAgentDefaultAgentFlagTests.cs +++ /dev/null @@ -1,212 +0,0 @@ -using System.Reflection; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Xunit; - -namespace Squad.Agents.AI.Tests; - -/// -/// Tests for the 0.5.0 behaviour where SquadAgent auto-injects -/// --agent {AgentFileName} into the underlying copilot.exe CLI args, so -/// the wrapped agent picks up .github/agents/squad.agent.md by default -/// — matching what copilot --agent squad does interactively. -/// -public class SquadAgentDefaultAgentFlagTests : IDisposable -{ - private readonly string _tempRoot; - - public SquadAgentDefaultAgentFlagTests() - { - // Each test gets its own throwaway team root so file-existence checks - // are deterministic and we can scaffold or omit the squad.agent.md file - // per scenario without contaminating siblings. - _tempRoot = Path.Combine(Path.GetTempPath(), "squad-agents-ai-tests", Guid.NewGuid().ToString("n")); - Directory.CreateDirectory(_tempRoot); - } - - public void Dispose() - { - try { Directory.Delete(_tempRoot, recursive: true); } - catch { /* best effort */ } - } - - private string ScaffoldAgentFile(string agentName) - { - var dir = Path.Combine(_tempRoot, ".github", "agents"); - Directory.CreateDirectory(dir); - var path = Path.Combine(dir, $"{agentName}.agent.md"); - File.WriteAllText(path, $"# {agentName}\n\nstub agent file for tests"); - return path; - } - - [Fact] - public void Options_AgentFileName_DefaultsToSquad() - { - var options = new SquadAgentOptions(); - Assert.Equal("squad", options.AgentFileName); - } - - [Fact] - public void AddSquadAgent_AutoInjectsAgentSquad_WhenSquadAgentMdExists() - { - ScaffoldAgentFile("squad"); - - var agent = CreateAgent(opts => - { - opts.SquadFolderPath = _tempRoot; - opts.Cwd = _tempRoot; - }); - - var args = GetConnectionArgs(agent); - AssertContainsAgent(args, "squad"); - } - - [Fact] - public void AddSquadAgent_DoesNotInjectAgent_WhenAgentFileMissing() - { - // No .github/agents/squad.agent.md scaffolded — the SDK should NOT - // pass --agent squad because the CLI would error on a missing file. - var agent = CreateAgent(opts => - { - opts.SquadFolderPath = _tempRoot; - opts.Cwd = _tempRoot; - }); - - var args = GetConnectionArgs(agent); - Assert.DoesNotContain("--agent", args); - } - - [Fact] - public void AddSquadAgent_RespectsExplicitAgentInCliArgs() - { - // Scaffold the default file so we'd auto-inject if the consumer hadn't - // already supplied --agent. - ScaffoldAgentFile("squad"); - ScaffoldAgentFile("data"); - - var agent = CreateAgent(opts => - { - opts.SquadFolderPath = _tempRoot; - opts.Cwd = _tempRoot; - opts.CliArgs.Add("--agent"); - opts.CliArgs.Add("data"); - }); - - var args = GetConnectionArgs(agent); - - // Exactly ONE --agent in the args, and it's "data" (the user-supplied one). - var agentIndices = args.Select((a, i) => (a, i)) - .Where(t => string.Equals(t.a, "--agent", StringComparison.OrdinalIgnoreCase)) - .Select(t => t.i) - .ToList(); - Assert.Single(agentIndices); - Assert.Equal("data", args[agentIndices[0] + 1]); - } - - [Fact] - public void AddSquadAgent_RespectsCustomAgentFileName_WhenFileExists() - { - ScaffoldAgentFile("data"); - - var agent = CreateAgent(opts => - { - opts.SquadFolderPath = _tempRoot; - opts.Cwd = _tempRoot; - opts.AgentFileName = "data"; - }); - - var args = GetConnectionArgs(agent); - AssertContainsAgent(args, "data"); - } - - [Fact] - public void AddSquadAgent_DoesNotInjectAgent_WhenAgentFileNameIsNull() - { - // Opt-out: setting AgentFileName=null disables the auto-inject even if - // squad.agent.md exists. Used when the consumer wants to drive the - // session with a custom SystemMessage instead of a charter file. - ScaffoldAgentFile("squad"); - - var agent = CreateAgent(opts => - { - opts.SquadFolderPath = _tempRoot; - opts.Cwd = _tempRoot; - opts.AgentFileName = null; - }); - - var args = GetConnectionArgs(agent); - Assert.DoesNotContain("--agent", args); - } - - [Fact] - public void AddSquadAgent_DoesNotInjectAgent_WhenAgentFileNameIsWhitespace() - { - ScaffoldAgentFile("squad"); - - var agent = CreateAgent(opts => - { - opts.SquadFolderPath = _tempRoot; - opts.Cwd = _tempRoot; - opts.AgentFileName = " "; - }); - - var args = GetConnectionArgs(agent); - Assert.DoesNotContain("--agent", args); - } - - // ── helpers ───────────────────────────────────────────────────────────── - - private static SquadAgent CreateAgent(Action configure) - { - var services = new ServiceCollection(); - services.AddSingleton(new ConfigurationBuilder().Build()); - services.AddLogging(); - services.AddSquadAgent(opts => - { - opts.CliPath = @"C:\fake-copilot\copilot.exe"; - configure(opts); - }); - return services.BuildServiceProvider().GetRequiredService(); - } - - private static IList GetConnectionArgs(SquadAgent agent) - { - var client = GetField(agent, "_copilotClient"); - var clientOptions = GetField(client, "_options"); - var connection = GetProperty(clientOptions, "Connection"); - Assert.NotNull(connection); - var args = GetProperty>(connection!, "Args"); - Assert.NotNull(args); - return args!; - } - - private static void AssertContainsAgent(IList args, string expectedName) - { - // CLI args must be a `--agent ` adjacent pair, not just two unrelated tokens. - for (var i = 0; i < args.Count - 1; i++) - { - if (string.Equals(args[i], "--agent", StringComparison.OrdinalIgnoreCase) && - string.Equals(args[i + 1], expectedName, StringComparison.Ordinal)) - { - return; - } - } - Assert.Fail($"Expected `--agent {expectedName}` in CLI args; got: [{string.Join(", ", args)}]"); - } - - private static T GetField(object instance, string fieldName) - { - var f = instance.GetType().GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic); - Assert.NotNull(f); - var v = f!.GetValue(instance); - Assert.NotNull(v); - return (T)v!; - } - - private static T? GetProperty(object instance, string propertyName) - { - var p = instance.GetType().GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); - Assert.NotNull(p); - return (T?)p!.GetValue(instance); - } -} diff --git a/test/Squad.Agents.AI.Tests/SquadAgentDefaultAgentTests.cs b/test/Squad.Agents.AI.Tests/SquadAgentDefaultAgentTests.cs new file mode 100644 index 000000000..92469a7ed --- /dev/null +++ b/test/Squad.Agents.AI.Tests/SquadAgentDefaultAgentTests.cs @@ -0,0 +1,194 @@ + using System.Reflection; +using GitHub.Copilot; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Xunit; + +namespace Squad.Agents.AI.Tests; + +/// +/// Tests for the 0.5.0 behaviour where SquadAgent auto-sets +/// (the SDK's first-class equivalent of +/// the Copilot CLI's --agent flag) to , +/// so the wrapped session picks up .github/agents/squad.agent.md by default — +/// matching copilot --agent squad from the terminal. +/// +public class SquadAgentDefaultAgentTests : IDisposable +{ + private readonly string _tempRoot; + + public SquadAgentDefaultAgentTests() + { + // Each test gets its own throwaway team root so file-existence checks + // are deterministic and we can scaffold or omit the squad.agent.md file + // per scenario without contaminating siblings. + _tempRoot = Path.Combine(Path.GetTempPath(), "squad-agents-ai-tests", Guid.NewGuid().ToString("n")); + Directory.CreateDirectory(_tempRoot); + } + + public void Dispose() + { + try { Directory.Delete(_tempRoot, recursive: true); } + catch { /* best effort */ } + } + + private string ScaffoldAgentFile(string agentName) + { + var dir = Path.Combine(_tempRoot, ".github", "agents"); + Directory.CreateDirectory(dir); + var path = Path.Combine(dir, $"{agentName}.agent.md"); + File.WriteAllText(path, $"# {agentName}\n\nstub agent file for tests"); + return path; + } + + [Fact] + public void Options_AgentFileName_DefaultsToSquad() + { + var options = new SquadAgentOptions(); + Assert.Equal("squad", options.AgentFileName); + } + + [Fact] + public void AddSquadAgent_AutoSetsSessionConfigAgentToSquad_WhenSquadAgentMdExists() + { + ScaffoldAgentFile("squad"); + + var agent = CreateAgent(opts => + { + opts.SquadFolderPath = _tempRoot; + opts.Cwd = _tempRoot; + }); + + var sessionConfig = GetInnerSessionConfig(agent); + Assert.Equal("squad", sessionConfig.Agent); + } + + [Fact] + public void AddSquadAgent_LeavesAgentUnset_WhenAgentFileMissing() + { + // No .github/agents/squad.agent.md scaffolded — the SDK should NOT + // set sessionConfig.Agent because the underlying session would error + // when asked to load a non-existent agent. + var agent = CreateAgent(opts => + { + opts.SquadFolderPath = _tempRoot; + opts.Cwd = _tempRoot; + }); + + var sessionConfig = GetInnerSessionConfig(agent); + Assert.Null(sessionConfig.Agent); + } + + [Fact] + public void AddSquadAgent_RespectsCustomAgentFileName_WhenFileExists() + { + ScaffoldAgentFile("data"); + + var agent = CreateAgent(opts => + { + opts.SquadFolderPath = _tempRoot; + opts.Cwd = _tempRoot; + opts.AgentFileName = "data"; + }); + + var sessionConfig = GetInnerSessionConfig(agent); + Assert.Equal("data", sessionConfig.Agent); + } + + [Fact] + public void AddSquadAgent_LeavesAgentUnset_WhenAgentFileNameIsNull() + { + // Opt-out: setting AgentFileName=null disables the auto-set even if + // squad.agent.md exists. Used when the consumer wants to drive the + // session with a custom SystemMessage instead of an agent file. + ScaffoldAgentFile("squad"); + + var agent = CreateAgent(opts => + { + opts.SquadFolderPath = _tempRoot; + opts.Cwd = _tempRoot; + opts.AgentFileName = null; + }); + + var sessionConfig = GetInnerSessionConfig(agent); + Assert.Null(sessionConfig.Agent); + } + + [Fact] + public void AddSquadAgent_LeavesAgentUnset_WhenAgentFileNameIsWhitespace() + { + ScaffoldAgentFile("squad"); + + var agent = CreateAgent(opts => + { + opts.SquadFolderPath = _tempRoot; + opts.Cwd = _tempRoot; + opts.AgentFileName = " "; + }); + + var sessionConfig = GetInnerSessionConfig(agent); + Assert.Null(sessionConfig.Agent); + } + + [Fact] + public void AddSquadAgent_ConfigureSession_CanOverrideAutoSetAgent() + { + // ConfigureSession runs AFTER the default is applied, so consumers retain + // full control — they can replace the auto-set value with anything else + // (or null it out) from inside their own callback. + ScaffoldAgentFile("squad"); + ScaffoldAgentFile("custom"); + + var agent = CreateAgent(opts => + { + opts.SquadFolderPath = _tempRoot; + opts.Cwd = _tempRoot; + opts.ConfigureSession = sessionConfig => + { + // Confirm the default was applied before this callback ran. + Assert.Equal("squad", sessionConfig.Agent); + sessionConfig.Agent = "custom"; + }; + }); + + var actualSessionConfig = GetInnerSessionConfig(agent); + Assert.Equal("custom", actualSessionConfig.Agent); + } + + // ── helpers ───────────────────────────────────────────────────────────── + + private static SquadAgent CreateAgent(Action configure) + { + var services = new ServiceCollection(); + services.AddSingleton(new ConfigurationBuilder().Build()); + services.AddLogging(); + services.AddSquadAgent(opts => + { + opts.CliPath = @"C:\fake-copilot\copilot.exe"; + configure(opts); + }); + return services.BuildServiceProvider().GetRequiredService(); + } + + /// + /// Reach into the SquadAgent → DelegatingAIAgent.InnerAgent → ChatClientAgent.SessionConfig + /// to assert against the SessionConfig the SDK was constructed with. + /// + private static SessionConfig GetInnerSessionConfig(SquadAgent agent) + { + var innerProp = typeof(Microsoft.Agents.AI.DelegatingAIAgent).GetProperty( + "InnerAgent", + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + Assert.NotNull(innerProp); + var inner = innerProp!.GetValue(agent); + Assert.NotNull(inner); + + var configField = inner!.GetType().GetField( + "_sessionConfig", + BindingFlags.Instance | BindingFlags.NonPublic); + Assert.NotNull(configField); + var config = configField!.GetValue(inner); + Assert.NotNull(config); + return (SessionConfig)config!; + } +}