Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
1aaead4
fix: auto-scaffold Fact Checker agent during init and cast (#1222)
tamirdresher Jun 7, 2026
010f6fc
fix(upgrade): auto-scaffold Rai + Fact Checker on squad upgrade (#1222)
tamirdresher Jun 7, 2026
d41b046
Merge pull request #1223 from tamirdresher/fix/1222-fact-checker-auto…
bradygaster Jun 7, 2026
e5c1800
fix(permissions): use 'approve-once' for Copilot CLI v1.0.54+ contrac…
bradygaster Jun 9, 2026
a081832
feat: Squad.Agents.AI - Microsoft Agent Framework adapter for the Squ…
tamirdresher Jun 9, 2026
28962e2
ci(Squad.Agents.AI): switch NuGet publish to Trusted Publishing (OIDC…
tamirdresher Jun 9, 2026
647f337
fix(Squad.Agents.AI): expose SessionConfig + default OnPermissionRequ…
tamirdresher Jun 10, 2026
cc37a2f
Squad.Agents.AI 0.2.0: bump to MAF 1.10.0-rc1 / SDK 1.0.0 GA — file-I…
tamirdresher Jun 10, 2026
39ee9c7
fix: address pre-existing Copilot review comments from PR #1212 (#1258)
bradygaster Jun 11, 2026
611a82b
fix: expose memory tools via MCP + route writes through governed pipe…
bradygaster Jun 11, 2026
eeb68f2
docs(skills): update path references from .squad/skills/ to .copilot/…
bradygaster Jun 11, 2026
c11274d
feat(init): prompt to add @copilot as a team member during squad init…
bradygaster Jun 11, 2026
5824b60
docs: align skills path + state-backend upgrade flow (#1241, #1226) (…
bradygaster Jun 11, 2026
152bbf0
Squad.Agents.AI 0.3.0: first-class subagent observability (#1265)
tamirdresher Jun 11, 2026
d3c2d84
chore(lockfile): sync package-lock with package.json after v0.10.0 bu…
tamirdresher Jun 11, 2026
f79b03a
fix(bump-build): also update package-lock workspace entries (#1267)
tamirdresher Jun 11, 2026
da17eef
fix: release pipeline version pinning (#1203, #1204) (#1250)
bradygaster Jun 11, 2026
ce15d6b
chore: include CHANGELOG.md in published npm tarball (#1257)
bradygaster Jun 11, 2026
c076ffb
Squad.Agents.AI 0.4.0: default-on subagent observability + Aspire-sty…
tamirdresher Jun 11, 2026
dfc5b94
Squad.Agents.AI 0.5.0: auto-inject --agent squad (CLI parity by defau…
tamirdresher Jun 11, 2026
edcc39d
Squad.Agents.AI 0.5.1: fix 0.5.0 regression — use --agent CLI flag (n…
tamirdresher Jun 11, 2026
217e0bd
Add squad registry add/list/remove for discovery-only peer squads (#1…
tamirdresher Jun 12, 2026
2ca906d
fix(cli): stop writing squad_state to ~/.copilot/mcp-config.json on e…
tamirdresher Jun 13, 2026
84ce747
fix(sdk): wire team.md/routing.md/casting state on \squad preset appl…
tamirdresher Jun 13, 2026
68e2774
fix(docs): tell coordinator to roster Fact Checker on first-time cast…
tamirdresher Jun 13, 2026
16c6b25
fix(sdk): plumb Fact Checker like Rai — rich charter at init + .squad…
tamirdresher Jun 13, 2026
76ba4e7
fix(skills): rename squad disambiguation skill to squad-help (superse…
tamirdresher Jun 13, 2026
918cbd4
fix(prompt): coordinator must probe for squad_state/memory tools befo…
tamirdresher Jun 13, 2026
608f858
feat(skills): make /squad a real slash command (user-invocable: true …
tamirdresher Jun 13, 2026
40f78f2
fix(skills): install bundled skills to .github/skills/ (closes #1126)…
tamirdresher Jun 13, 2026
6afd067
feat(sdk): bundle cross-squad-communication skill (#5 cross-squad pro…
tamirdresher Jun 13, 2026
b79e64a
fix(coordinator): route "spawn a squad" / "another squad" prompts thr…
tamirdresher Jun 13, 2026
89a1b96
fix(sdk,cli): bundle missing skills on init + strip fabricated tiered…
tamirdresher Jun 13, 2026
942270b
docs: add feature pages for preset, cross-squad discover/delegate, an…
tamirdresher Jun 14, 2026
f9f77c0
docs: add feature pages for remaining 8 v0.10 features (tiered-memory…
tamirdresher Jun 14, 2026
caef438
docs(state-backends): document pre-commit hook, post-upgrade flow, an…
tamirdresher Jun 14, 2026
ae6f4e7
docs: clarify that .squad/casting/* files are identity, not two-layer…
tamirdresher Jun 14, 2026
567f447
fix(state-backend): conditional .gitignore entries for two-layer/orph…
tamirdresher Jun 14, 2026
9917fa1
chore: promote v0.10.1 dev → main (38 commits including v0.10 stabili…
tamirdresher Jun 14, 2026
1e1a9d7
docs(blog): v0.10 stabilisation insider release post
tamirdresher Jun 14, 2026
286fa23
fix(docs): rephrase 'fenced code block' row in skill-security-scanner…
tamirdresher Jun 14, 2026
d4457ab
fix(blog): use American 'Stabilization' (cspell dict is en_US)
tamirdresher Jun 14, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Squad.Agents.AI 0.4.0: default-on subagent observability + Aspire-sty…
…le connection-string lookup (#1271)

Two small but high-impact changes that remove ~30 lines of boilerplate from every
consumer (Aspire and otherwise) and make the OpenTelemetry story self-explanatory.

## 1. EmitSubagentActivities (default true) — telemetry independent of callback

Today, the per-subagent OpenTelemetry Activity emission is a side-effect of setting
`OnSubagentTrace`. A host that just wants `squad.subagent {Name}` spans in their
backend has to wire a callback they don't need. `Microsoft.Agents.AI.Squad` is
silent until then.

0.4.0 makes activity emission the default:

* New `SquadAgentOptions.EmitSubagentActivities` (defaults to `true`).
* `SquadAgent` installs `SquadSubagentTraceMapper` whenever
  `EmitSubagentActivities || OnSubagentTrace != null`, so spans flow with zero
  extra wiring.
* `OnSubagentTrace` becomes a pure customisation hook (logging, dashboards,
  metrics) — independent of telemetry. Set `EmitSubagentActivities = false` to
  opt out of built-in spans when you want to handle telemetry yourself.

Plus richer span shape: every lifecycle phase is now an
`ActivityEvent` on the live subagent span (visible as annotated markers on the
timeline in Aspire / Jaeger / etc.):

* `squad.subagent.start`        — on SubagentStarted
* `squad.subagent.message`      — on AssistantMessage (with message_preview tag)
* `squad.subagent.completed`    — on SubagentCompleted
* `squad.subagent.failed`       — on SubagentFailed

Net effect for a consumer:

  builder.Services.AddOpenTelemetry()
      .WithTracing(t => t.AddSource(SquadAgentDiagnostics.ActivitySourceName));
  builder.Services.AddSquadAgent(o => o.SquadFolderPath = "/team");

…and the dashboard lights up. No callback wiring, no Activity.Current?.AddEvent
plumbing in the host.

## 2. Aspire-style connection-string lookup (with legacy fallback)

Aspire injects connection strings under the literal resource name —
e.g. an AppHost that calls `builder.AddSquad("research-squad", ...)` exposes
`ConnectionStrings:research-squad` to the consumer. The 0.3.0 SDK only looked at
`ConnectionStrings:squad-research-squad` (prefixed), so Aspire consumers had to
manually call `Configuration.GetConnectionString(name)`, parse the URI, and feed
`SquadFolderPath` into the configure callback themselves.

0.4.0 tries the literal name first and falls back to the legacy prefixed form:

| Style                                | Example                                     | Lookup                                     |
|--------------------------------------|---------------------------------------------|--------------------------------------------|
| Aspire-style direct (tried first)    | `AddSquadAgent("research-squad")`         | `ConnectionStrings:research-squad`       |
| Legacy prefixed fallback             | `AddSquadAgent("research")`               | `ConnectionStrings:squad-research`       |

Both work. Existing consumers using `ConnectionStrings:squad-{name}` continue
unchanged; new Aspire consumers get the natural one-line registration.

## Tests

54 → 64 tests, all passing on net8.0/9.0/10.0.

New `SquadAgentDefaultObservabilityTests` covers:

* Default-on activity emission (without consumer callback)
* Opt-out path (`EmitSubagentActivities = false`) — span suppression + callback
  still fires
* Each ActivityEvent name (`start` / `message` / `completed` / `failed`)
* Connection-string precedence: Aspire-direct preferred, prefixed fallback used,
  same rule applies for keyed registrations

Existing `SquadSubagentTraceTests` and the new class share an
`[Collection("SquadActivityListeners")]` so they run serially — process-global
`ActivityListener` state caused cross-test pollution otherwise.

## Files

* `src/Squad.Agents.AI/SquadAgentOptions.cs` — new `EmitSubagentActivities`
  property + reworked `OnSubagentTrace` XML doc to clarify independence.
* `src/Squad.Agents.AI/SquadAgent.cs` — install trace mapper when telemetry OR
  callback is requested.
* `src/Squad.Agents.AI/SquadSubagentTraceMapper.cs` — accept
  `emitActivities` flag; gate `StartActivity`/`Dispose` on it; add
  `ActivityEvent` annotations at every lifecycle boundary.
* `src/Squad.Agents.AI/SquadAgentOptionsConfigurator.cs` — accept a list of
  candidate connection-string names; first non-empty wins.
* `src/Squad.Agents.AI/SquadServiceCollectionExtensions.cs` — new
  `GetConnectionStringNames` returns `[name, "squad-"+name]` so both Aspire
  and legacy conventions resolve.
* `src/Squad.Agents.AI/Squad.Agents.AI.csproj` — bump 0.3.0 → 0.4.0.
* `src/Squad.Agents.AI/README.md` — new "Subagent observability" section,
  updated "Aspire / configuration path" section, two new option rows in the
  Key Options table.

## Backward compatibility

Fully backward compatible. The two-arg `SquadSubagentTraceMapper` constructor
defaults `emitActivities` to `true`, `EmitSubagentActivities` defaults to
`true`, and the legacy `ConnectionStrings:squad-{name}` lookup still resolves.
Net change for an existing consumer that had OnSubagentTrace set: nothing (mapper
runs in both 0.3.0 and 0.4.0 because OnSubagentTrace is non-null). Net change
for a consumer that did NOT set OnSubagentTrace but did AddSource: they now get
spans they always asked for.

Co-authored-by: Tamir Dresher <tamirdresher@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
  • Loading branch information
3 people authored Jun 11, 2026
commit c076ffbd9c92a95cf29072b16ad5e09f9dda595a
44 changes: 43 additions & 1 deletion src/Squad.Agents.AI/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,14 @@ Use `GitHubTokenProvider` only when the host owns token retrieval, such as Key V

`AddSquadAgent()` reads `ConnectionStrings:squad` through `IConfiguration.GetConnectionString("squad")`. In environment variables, use `ConnectionStrings__squad`.

Named registrations select a named connection string. For example, `AddSquadAgent("research")` reads `ConnectionStrings:squad-research`; in environment variables, use `ConnectionStrings__squad-research`.
Named registrations support both connection-string conventions:

| Style | Example | Looks up |
|---|---|---|
| **Aspire-style direct** (tried first) | `AddSquadAgent("research-squad")` | `ConnectionStrings:research-squad` |
| **Legacy prefixed fallback** | `AddSquadAgent("research")` | `ConnectionStrings:squad-research` |

So when an Aspire AppHost registers a Squad resource via `builder.AddSquad("research-squad", ...)` and a downstream project does `.WithReference(researchSquad)`, the consumer can resolve the agent with a single `builder.Services.AddKeyedSquadAgent("research-squad")` call — the SDK finds the Aspire-injected connection string automatically. Existing consumers using the prefixed form continue to work; the SDK tries the literal name first and falls back to `squad-{name}` if the direct lookup is empty.

Supported connection string forms:

Expand All @@ -143,6 +150,39 @@ 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.

## 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.

Two-line wiring is all that is required — no manual callback plumbing:

```csharp
using OpenTelemetry.Trace;
using Squad.Agents.AI;

builder.Services.AddOpenTelemetry()
.WithTracing(t => t.AddSource(SquadAgentDiagnostics.ActivitySourceName));

builder.Services.AddSquadAgent(o => o.SquadFolderPath = @"C:\team");
```

When the coordinator's `task` tool spawns specialists, the host's tracer (Jaeger, Zipkin, Application Insights, or the Aspire dashboard's **Traces** view) shows one `squad.subagent` span per spawn, each tagged with `squad.subagent.name`, `squad.subagent.display_name`, `squad.subagent.sdk_agent_id`, and `squad.subagent.reply_preview` — plus timeline events for every lifecycle transition.

**Turning telemetry off.** Set `EmitSubagentActivities = false` to suppress Squad's built-in spans (for example, when you want to drive observability entirely from your own callback or avoid double-counting). The `OnSubagentTrace` callback continues to fire either way — it is the customization seam, independent of telemetry.

```csharp
builder.Services.AddSquadAgent(o =>
{
o.SquadFolderPath = @"C:\team";
o.EmitSubagentActivities = false; // disable built-in OTel emission
o.OnSubagentTrace = trace => // handle telemetry yourself
{
if (trace.Kind == SquadAgentTraceEventKind.SubagentStarted)
MyMetrics.IncrementSpawn(trace.SubagentName!);
};
});
```

## Key options

| Option | Purpose |
Expand All @@ -157,6 +197,8 @@ Parsed URI query keys: `teamRoot`, `cliPath`, `cwd`, `cliArgs` (semicolon-separa
| `TraceEvents` | Enables verbose SDK logging and emits a startup warning when enabled. |
| `AgentName` | Display name for the resulting `AIAgent`; defaults to `Squad`. |
| `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. |

## Security

Expand Down
2 changes: 1 addition & 1 deletion src/Squad.Agents.AI/Squad.Agents.AI.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<PackageReadmeFile>README.md</PackageReadmeFile>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<Version>0.3.0</Version>
<Version>0.4.0</Version>
</PropertyGroup>
<ItemGroup>
<Compile Remove="samples/**/*.cs" />
Expand Down
13 changes: 8 additions & 5 deletions src/Squad.Agents.AI/SquadAgent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -139,13 +139,16 @@ private static SquadAgentState BuildStateInternal(SquadAgentOptions options, ILo
sessionConfig.SystemMessage = new SystemMessageConfig { Content = options.Instructions };
}

// Wire OnSubagentTrace before ConfigureSession so consumer-supplied ConfigureSession
// callbacks can still override or chain behind our defaults (e.g. compose multiple OnEvent
// handlers, replace IncludeSubAgentStreamingEvents, etc.).
// Install the subagent trace mapper when EITHER:
// - EmitSubagentActivities is on (default true) — to emit OTel spans + events
// - OnSubagentTrace is set — to forward typed events to the consumer
// The two concerns are independent; the mapper handles whichever combination is active.
SquadSubagentTraceMapper? traceMapper = null;
if (options.OnSubagentTrace is not null)
if (options.EmitSubagentActivities || options.OnSubagentTrace is not null)
{
traceMapper = new SquadSubagentTraceMapper(options.OnSubagentTrace);
traceMapper = new SquadSubagentTraceMapper(
options.OnSubagentTrace,
emitActivities: options.EmitSubagentActivities);
sessionConfig.IncludeSubAgentStreamingEvents = true;
sessionConfig.OnEvent = traceMapper.OnSessionEvent;
}
Expand Down
60 changes: 54 additions & 6 deletions src/Squad.Agents.AI/SquadAgentOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@
/// Gets or sets a delegate that customizes the <see cref="SessionConfig"/> used to
/// construct the inner <see cref="Microsoft.Agents.AI.AIAgent"/>. The delegate runs
/// after Squad has applied its defaults (including an <c>ApproveAll</c>
/// <see cref="SessionConfig.OnPermissionRequest"/> handler and the

Check warning on line 118 in src/Squad.Agents.AI/SquadAgentOptions.cs

View workflow job for this annotation

GitHub Actions / Pack and publish NuGet package

XML comment has cref attribute 'OnPermissionRequest' that could not be resolved

Check warning on line 118 in src/Squad.Agents.AI/SquadAgentOptions.cs

View workflow job for this annotation

GitHub Actions / Pack and publish NuGet package

XML comment has cref attribute 'OnPermissionRequest' that could not be resolved
/// <see cref="Instructions"/> as the appended system message), so it can override or
/// extend any session-scoped setting such as the permission handler, tool list,
/// model name, or hooks.
Expand Down Expand Up @@ -144,23 +144,24 @@
/// </summary>
/// <remarks>
/// <para>
/// Setting this callback has three side effects:
/// Setting this callback has two side effects:
/// </para>
/// <list type="number">
/// <item><see cref="GitHub.Copilot.SessionConfigBase.IncludeSubAgentStreamingEvents"/> is forced to
/// <see langword="true"/> so subagent assistant messages flow up to the parent session (otherwise
/// the subagent's reply stays inside its own session and never reaches the callback).</item>
/// <item>An <see cref="System.Diagnostics.ActivitySource"/> named
/// <see cref="SquadAgentDiagnostics.ActivitySourceName"/> emits one <see cref="System.Diagnostics.Activity"/>
/// per subagent dispatch, tagged with <c>squad.subagent.name</c> and a preview of the subagent's
/// reply. Hosts that <c>.AddSource(SquadAgentDiagnostics.ActivitySourceName)</c> on their
/// OpenTelemetry tracer get these spans in their backend (e.g. the Aspire dashboard).</item>
/// <item><see cref="ConfigureSession"/> may still override <see cref="GitHub.Copilot.SessionConfigBase.OnEvent"/>
/// or <see cref="GitHub.Copilot.SessionConfigBase.IncludeSubAgentStreamingEvents"/>; consumers
/// that need a stacked event handler should call <c>OnSubagentTrace</c> from inside their
/// <see cref="ConfigureSession"/> callback to compose the two.</item>
/// </list>
/// <para>
/// OpenTelemetry telemetry is independent — it is controlled by
/// <see cref="EmitSubagentActivities"/> (default <see langword="true"/>) and emits whether or
/// not this callback is set. Use <c>OnSubagentTrace</c> when you want to layer extra behaviour
/// (custom logging, dashboards, audit trails) on top of the built-in spans.
/// </para>
/// <para>
/// Consumer callback exceptions are caught and swallowed so a misbehaving subscriber cannot tear
/// down the SDK event loop. Add your own try/catch + logging inside the callback if you need to
/// surface those errors.
Expand All @@ -172,7 +173,7 @@
/// {
/// if (trace.Kind == SquadAgentTraceEventKind.SubagentStarted)
/// Console.WriteLine($"[spawn] {trace.SubagentName} (id={trace.SdkAgentId})");
/// else if (trace.Kind == SquadAgentTraceEventKind.AssistantMessage && trace.SdkAgentId is not null)

Check warning on line 176 in src/Squad.Agents.AI/SquadAgentOptions.cs

View workflow job for this annotation

GitHub Actions / Pack and publish NuGet package

XML comment has badly formed XML -- 'Whitespace is not allowed at this location.'

Check warning on line 176 in src/Squad.Agents.AI/SquadAgentOptions.cs

View workflow job for this annotation

GitHub Actions / Pack and publish NuGet package

XML comment has badly formed XML -- 'The character(s) '&' cannot be used at this location.'

Check warning on line 176 in src/Squad.Agents.AI/SquadAgentOptions.cs

View workflow job for this annotation

GitHub Actions / Pack and publish NuGet package

XML comment has badly formed XML -- 'Whitespace is not allowed at this location.'

Check warning on line 176 in src/Squad.Agents.AI/SquadAgentOptions.cs

View workflow job for this annotation

GitHub Actions / Pack and publish NuGet package

XML comment has badly formed XML -- 'The character(s) '&' cannot be used at this location.'
/// Console.WriteLine($"[{trace.SdkAgentId}] {trace.Content}");
/// };
/// </code>
Expand All @@ -180,6 +181,53 @@
[JsonIgnore]
public Action<SquadAgentTraceEvent>? OnSubagentTrace { get; set; }

/// <summary>
/// Gets or sets whether to emit OpenTelemetry <see cref="System.Diagnostics.Activity"/> spans
/// and lifecycle events for each subagent dispatch. Defaults to <see langword="true"/>.
/// </summary>
/// <remarks>
/// <para>
/// When <see langword="true"/>, an <see cref="System.Diagnostics.ActivitySource"/> named
/// <see cref="SquadAgentDiagnostics.ActivitySourceName"/> opens one
/// <see cref="System.Diagnostics.Activity"/> per subagent dispatch (tagged with
/// <c>squad.subagent.name</c>, <c>squad.subagent.display_name</c>, <c>squad.subagent.sdk_agent_id</c>,
/// and <c>squad.subagent.reply_preview</c>). Each subagent lifecycle phase
/// (<c>squad.subagent.start</c>, <c>squad.subagent.message</c>, <c>squad.subagent.completed</c>,
/// <c>squad.subagent.failed</c>) is also added as a <see cref="System.Diagnostics.ActivityEvent"/>
/// on the live subagent span so the timeline view in dashboards (e.g. Aspire) shows annotated
/// timestamps for every state transition.
/// </para>
/// <para>
/// Hosts that <c>.AddSource(SquadAgentDiagnostics.ActivitySourceName)</c> on their OpenTelemetry
/// tracer get these spans in their backend automatically — no need to set
/// <see cref="OnSubagentTrace"/>.
/// </para>
/// <para>
/// Set this to <see langword="false"/> to disable Squad's built-in telemetry (e.g. when you
/// want to handle observability entirely from your own <see cref="OnSubagentTrace"/> callback,
/// or to avoid double-counting if another layer in your stack is already emitting equivalent
/// spans).
/// </para>
/// </remarks>
/// <example>
/// <code>
/// // Default (recommended): just AddSource and the dashboard lights up.
/// builder.Services.AddOpenTelemetry()
/// .WithTracing(t => t.AddSource(SquadAgentDiagnostics.ActivitySourceName));
///
/// builder.Services.AddSquadAgent(opts => opts.SquadFolderPath = "/team");
///
/// // Opt out (custom telemetry):
/// builder.Services.AddSquadAgent(opts =>
/// {
/// opts.SquadFolderPath = "/team";
/// opts.EmitSubagentActivities = false;
/// opts.OnSubagentTrace = trace => MyMetrics.Increment(trace.Kind.ToString());
/// });
/// </code>
/// </example>
public bool EmitSubagentActivities { get; set; } = true;

private static readonly string[] TokenPatterns = { "TOKEN", "KEY", "SECRET", "HMAC", "PASSWORD", "CREDENTIAL" };

private static bool IsTokenKey(string key)
Expand Down
99 changes: 66 additions & 33 deletions src/Squad.Agents.AI/SquadAgentOptionsConfigurator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,39 +4,72 @@
namespace Squad.Agents.AI;

/// <summary>
/// Binds SquadAgentOptions from a configured connection string.
/// Runs before user-supplied configure lambda; user settings always win.
/// </summary>
internal sealed class SquadAgentOptionsConfigurator : IConfigureNamedOptions<SquadAgentOptions>
{
private readonly IConfiguration _configuration;
private readonly string _optionsName;
private readonly string _connectionStringName;

public SquadAgentOptionsConfigurator(IConfiguration configuration)
: this(configuration, Options.DefaultName, SquadServiceCollectionExtensions.DefaultConnectionStringName)
{
}

internal SquadAgentOptionsConfigurator(
IConfiguration configuration,
string optionsName,
string connectionStringName)
{
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
_optionsName = optionsName ?? Options.DefaultName;
_connectionStringName = connectionStringName ?? throw new ArgumentNullException(nameof(connectionStringName));
}

public void Configure(SquadAgentOptions options) => Configure(Options.DefaultName, options);

public void Configure(string? name, SquadAgentOptions options)
{
if (!string.Equals(name ?? Options.DefaultName, _optionsName, StringComparison.Ordinal))
return;

var connectionString = _configuration.GetConnectionString(_connectionStringName);

/// Binds SquadAgentOptions from a configured connection string.
/// Runs before user-supplied configure lambda; user settings always win.
/// </summary>
/// <remarks>
/// <para>
/// Resolves the connection string by trying each candidate name in order and using the first
/// one that returns a non-empty value. This lets a single registration accept both the
/// Aspire-style direct name (e.g. <c>ConnectionStrings:research-squad</c>) and the legacy
/// prefixed name (<c>ConnectionStrings:squad-research</c>) without breaking either convention.
/// </para>
/// </remarks>
internal sealed class SquadAgentOptionsConfigurator : IConfigureNamedOptions<SquadAgentOptions>
{
private readonly IConfiguration _configuration;
private readonly string _optionsName;
private readonly string[] _connectionStringNames;

public SquadAgentOptionsConfigurator(IConfiguration configuration)
: this(configuration, Options.DefaultName, new[] { SquadServiceCollectionExtensions.DefaultConnectionStringName })
{
}

internal SquadAgentOptionsConfigurator(
IConfiguration configuration,
string optionsName,
string connectionStringName)
: this(
configuration,
optionsName,
new[] { connectionStringName ?? throw new ArgumentNullException(nameof(connectionStringName)) })
{
}

internal SquadAgentOptionsConfigurator(
IConfiguration configuration,
string optionsName,
string[] connectionStringNames)
{
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
_optionsName = optionsName ?? Options.DefaultName;
_connectionStringNames = connectionStringNames ?? throw new ArgumentNullException(nameof(connectionStringNames));
if (_connectionStringNames.Length == 0)
throw new ArgumentException("At least one connection string name must be supplied.", nameof(connectionStringNames));
}

public void Configure(SquadAgentOptions options) => Configure(Options.DefaultName, options);

public void Configure(string? name, SquadAgentOptions options)
{
if (!string.Equals(name ?? Options.DefaultName, _optionsName, StringComparison.Ordinal))
return;

// Try each candidate name in order; first non-empty wins. This lets a single
// AddSquadAgent("research") call resolve either ConnectionStrings:research
// (Aspire-style) or ConnectionStrings:squad-research (legacy SDK convention).
string? connectionString = null;
foreach (var candidate in _connectionStringNames)
{
var value = _configuration.GetConnectionString(candidate);
if (!string.IsNullOrWhiteSpace(value))
{
connectionString = value;
break;
}
}

if (string.IsNullOrWhiteSpace(connectionString))
return;

Expand Down
39 changes: 31 additions & 8 deletions src/Squad.Agents.AI/SquadServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -166,9 +166,9 @@ private static IServiceCollection AddSquadAgentCore(
ArgumentNullException.ThrowIfNull(services);

var optionsName = GetOptionsName(name);
var connectionStringName = GetConnectionStringName(name);
var connectionStringNames = GetConnectionStringNames(name);

RegisterOptionsInfrastructure(services, optionsName, connectionStringName, configure);
RegisterOptionsInfrastructure(services, optionsName, connectionStringNames, configure);

// Register SquadAgent with specified lifetime
services.Add(new ServiceDescriptor(
Expand Down Expand Up @@ -208,9 +208,9 @@ private static IServiceCollection AddKeyedSquadAgentCore(

// Use the serviceKey as the options name when no explicit name is given
var optionsName = GetOptionsName(name ?? serviceKey);
var connectionStringName = GetConnectionStringName(name ?? serviceKey);
var connectionStringNames = GetConnectionStringNames(name ?? serviceKey);

RegisterOptionsInfrastructure(services, optionsName, connectionStringName, configure);
RegisterOptionsInfrastructure(services, optionsName, connectionStringNames, configure);

// Register keyed SquadAgent
services.Add(new ServiceDescriptor(
Expand Down Expand Up @@ -243,15 +243,15 @@ private static IServiceCollection AddKeyedSquadAgentCore(
private static void RegisterOptionsInfrastructure(
IServiceCollection services,
string optionsName,
string connectionStringName,
string[] connectionStringNames,
Action<SquadAgentOptions>? configure)
{
// Register connection string configurator FIRST (runs before user callback)
services.AddSingleton<IConfigureOptions<SquadAgentOptions>>(sp =>
new SquadAgentOptionsConfigurator(
sp.GetRequiredService<IConfiguration>(),
optionsName,
connectionStringName));
connectionStringNames));

if (configure is not null)
{
Expand All @@ -277,8 +277,31 @@ private static string GetOptionsName(string? name)
return string.IsNullOrWhiteSpace(name) ? Options.DefaultName : name;
}

private static string GetConnectionStringName(string? name)
/// <summary>
/// Returns the candidate IConfiguration ConnectionStrings: keys to try for a logical name.
/// Tried in order; first non-empty value wins.
/// </summary>
/// <remarks>
/// For a bare registration (<paramref name="name"/> null or whitespace) we look up the
/// historical default key <c>squad</c>.
/// <para>
/// For a named registration we try the literal name first
/// (e.g. <c>ConnectionStrings:research-squad</c> — the Aspire convention where the
/// resource name IS the connection string key), then fall back to the legacy prefixed
/// form (<c>ConnectionStrings:squad-research</c>) so existing consumers continue to work
/// without changes.
/// </para>
/// </remarks>
private static string[] GetConnectionStringNames(string? name)
{
return string.IsNullOrWhiteSpace(name) ? DefaultConnectionStringName : $"{DefaultConnectionStringName}-{name}";
if (string.IsNullOrWhiteSpace(name))
return new[] { DefaultConnectionStringName };

var prefixed = $"{DefaultConnectionStringName}-{name}";
// Avoid duplicate lookups when the caller passes a name that's already prefixed
// (e.g. AddSquadAgent("squad-research") → just look up "squad-research" once).
return string.Equals(name, prefixed, StringComparison.Ordinal)
? new[] { name }
: new[] { name, prefixed };
}
}
Loading
Loading