Skip to content
Merged
31 changes: 29 additions & 2 deletions demo/AgentCore.Demo/config/example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,12 @@ tools:
properties: { summary: { type: string } }
required: [ summary ]

# A marker, not code: it tells the model provider it may run a hosted web search, and only a
# provider that runs one acts on it. AgentToolCompiler drops this tool, per agent, for a model
# providers.llm[] never named webSearch: false for but whose adapter reports it cannot search —
# a warning at compile time, never a boot failure.
- { id: search, kind: builtin, uses: web.search }

# options.Bind("CloseCase", (string caseId, string reason) => ...) registers a typed method
# instead. Its parameters are the arguments, and their schema, so this declaration writes no
# parameters: at all. Writing one anyway is a boot failure: the two would drift apart.
Expand Down Expand Up @@ -225,6 +231,24 @@ agents:
# scoped agent with no scope open says it cannot look the answer up rather than searching
# everything. Set scoped: false on an agent that is meant to read the whole corpus.
knowledge: { mode: prefetch, limit: 5, citations: false }

# Every strategy here is deterministic: the same messages give the same result, from empty
# state. Summarization is not offered on purpose — a resumed call rebuilds a new session and
# re-derives from the replayed words, so a strategy that called a model would give one call two
# different histories. tool_result folds old tool-call groups into one short line each; the
# other three are truncate, sliding_window and context_window. trigger: names exactly one of
# tokens, messages, turns or groups — naming zero or two is a load error. keep: is how many
# newest groups the strategy never touches; foldResultChars: is how much of a tool result
# tool_result carries forward per fold. There is no per-agent opt-out: an omitted block inherits
# this one, so give compaction to some agents and not others by declaring the block on those
# agents instead of here.
#
# context_window here, not tool_result: tool_result folds only function tool calls, and the
# analyst agent below carries search, a hosted tool whose results are no such thing — tool_result
# would leave them growing the conversation forever. context_window folds tool_result's own work
# first and then truncates, and truncate drops whole groups regardless of what is inside them, so
# it still bounds a conversation a hosted tool is filling.
compaction: { strategy: context_window, trigger: { messages: 40 }, keep: 6, foldResultChars: 300 }
items:
# voice, scripted — one model round trip, no source labels spoken aloud. Inherits mode:
# prefetch, limit: 5, citations: false from defaults above.
Expand All @@ -235,7 +259,7 @@ agents:
- { id: closer, instructions: "<stage delta>", tools: [] }

# internal — everything on, and it searches every product on purpose
- { id: analyst, instructions: "<stage delta>", tools: [ lookup_order, create_case ],
- { id: analyst, instructions: "<stage delta>", tools: [ lookup_order, create_case, search ],
knowledge: { mode: tool, limit: 8, citations: true, scoped: false } }

# customer facing — tools yes, citations no. It sets two keys and inherits limit: 5.
Expand Down Expand Up @@ -289,7 +313,10 @@ providers:
- { kind: openai, model: gpt-4.1-mini, as: reply } # the voice path, chosen on latency
- { kind: openai, model: gpt-5.4-nano, as: fill } # the extractor, chosen on null discipline
- { kind: openai, model: gpt-4.1, as: judge } # evaluation only, chosen on judgement
- { kind: openai, model: gpt-4.1-nano, as: cheap } # ui.draw only, chosen on price
- { kind: openai, model: gpt-4.1-nano, as: cheap, webSearch: false } # ui.draw only, chosen on price
# webSearch: false above is a veto, not a default: omitted or true both leave the choice to the
# vendor's adapter. cheap only ever draws pictures, so vetoing it here costs nothing and stops a
# future search tool from ever running on the least capable model by accident.
# Three planes, and they are not duplicates. call is the media pipe and owns the inbound route.
# speech is recognition and synthesis. telephony is call control, which must outlive any one
# media leg because a warm transfer creates a second one.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
using AgentCore.Application.Configuration.Schema;

namespace AgentCore.Application.Configuration.Compilation;

/// <summary>One agent's <c>compaction:</c> block, fully resolved.</summary>
/// <param name="Strategy">The strategy to build.</param>
/// <param name="Trigger">The one condition that makes compaction run.</param>
/// <param name="Keep">How many newest groups the strategy never touches.</param>
/// <param name="FoldResultChars">How much of a tool result a fold carries forward.</param>
public sealed record ResolvedCompaction(
CompactionStrategyKind Strategy,
CompactionTriggerConfiguration Trigger,
int Keep,
int FoldResultChars);

/// <summary>
/// Composes one agent's <c>compaction:</c> block from <c>agents.defaults.compaction</c> and the
/// agent's own block, key by key.
/// </summary>
public static class AgentCompaction
{
/// <summary>The strategy used when neither the agent nor the defaults name one.</summary>
public const CompactionStrategyKind DefaultStrategy = CompactionStrategyKind.ToolResult;

/// <summary>The newest groups a strategy never touches, when nothing names a number.</summary>
public const int DefaultKeep = 4;

/// <summary>
/// How much of a tool result a fold carries forward, when nothing names a number. Enough for
/// the model to recognise what a tool already returned, and not enough to refill the window.
/// </summary>
public const int DefaultFoldResultChars = 200;

/// <summary>Composes one agent's resolved compaction settings.</summary>
/// <param name="defaults">The <c>agents.defaults</c> section, or <see langword="null"/>.</param>
/// <param name="agent">The agent to resolve.</param>
/// <returns>
/// The resolved settings, or <see langword="null"/> when neither the defaults nor the agent
/// declares a <c>compaction:</c> block.
/// </returns>
/// <exception cref="ArgumentException">The composed trigger names other than one condition.</exception>
public static ResolvedCompaction? Compose(AgentDefaults? defaults, AgentConfiguration agent)
{
ArgumentNullException.ThrowIfNull(agent);

var own = agent.Compaction;
var shared = defaults?.Compaction;

if (own is null && shared is null)
{
return null;
}

var trigger = own?.Trigger ?? shared?.Trigger ?? new CompactionTriggerConfiguration();

var named = new int?[] { trigger.Tokens, trigger.Messages, trigger.Turns, trigger.Groups }
.Count(value => value is not null);

if (named != 1)
{
// Zero would compact on every turn; two would leave the document silent about whether
// they are combined with All or Any.
throw new ArgumentException(
$"the agent '{agent.Id}' has a compaction trigger naming {named} conditions. It must "
+ "name exactly one of tokens, messages, turns or groups.",
nameof(agent));
}

return new ResolvedCompaction(
own?.Strategy ?? shared?.Strategy ?? DefaultStrategy,
trigger,
own?.Keep ?? shared?.Keep ?? DefaultKeep,
own?.FoldResultChars ?? shared?.FoldResultChars ?? DefaultFoldResultChars);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
using AgentCore.Application.Configuration.Parsing;
using AgentCore.Application.Configuration.Schema;
using AgentCore.Application.Knowledge;
using AgentCore.Application.Ports;
using AgentCore.Application.Runtime;
using AgentCore.Application.Runtime.Compaction;
using AgentCore.Application.Skills;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Compaction;
namespace AgentCore.Application.Configuration.Compilation;

internal static class AgentContextProviderCompiler
{
/// <summary>
/// The formatter an agent cites through when the host bound none. Stateless, so every agent in
/// every document reads the one instance.
/// </summary>
private static readonly SourceLocatorCitationFormatter DefaultCitations = new();

/// <summary>
/// Builds the context providers of one agent. <paramref name="clarification"/> and
/// <paramref name="clarificationProvider"/> are the document's ambiguity wiring (§7), the same
/// for every agent — built once by the caller rather than re-derived per agent.
/// </summary>
public static List<AIContextProvider> Build(
AgentDefaults? defaults,
AgentConfiguration item,
AgentCompilationContext context,
string pointer,
ResolvedClarification clarification,
ClarificationProvider? clarificationProvider)
{
List<AIContextProvider> providers = [new TurnContextProvider()];

// Bound ahead of the knowledge early-return below: channel 1 asks about a scope's fromState
// slots regardless of whether THIS agent composes its own knowledge: block, because the
// clarification is document-level state, not a per-agent search setting.
if (clarificationProvider is not null)
{
providers.Add(clarificationProvider);
}

if (item.Skills.Count > 0)
{
if (context.Skills is not { } catalog)
{
throw ConfigurationCompiler.Fail(
ConfigurationError.AppendPointer(pointer, "skills"),
$"the agent '{item.Id}' declares a skills: list and this host bound no skills "
+ "folder, so there is nothing to load. Call options.UseSkills(...) with the "
+ "folder that holds the SKILL.md directories, or remove the skills: list.");
}

providers.Add(SkillsProviderFactory.Create(catalog, item.Skills, context.Loggers));
}

ResolvedCompaction? compaction;
try
{
compaction = AgentCompaction.Compose(defaults, item);
}
catch (ArgumentException exception)
{
throw ConfigurationCompiler.Fail(
ConfigurationError.AppendPointer(ConfigurationError.AppendPointer(pointer, "compaction"), "trigger"),
exception.Message);
}

// Bound ahead of the knowledge early-return below, for the same reason: a compaction: block
// is independent of whether this agent composes a knowledge: block.
if (compaction is { } resolved)
{
#pragma warning disable MAAI001 // Compaction is evaluation-only in Microsoft.Agents.AI 1.17.0.
providers.Add(new CompactionProvider(
CompactionStrategyFactory.Create(resolved),
loggerFactory: context.Loggers));
#pragma warning restore MAAI001
}

if (AgentKnowledge.Compose(defaults, item) is not { } composed)
{
return providers;
}

if (context.Knowledge is not { } port)
{
throw ConfigurationCompiler.Fail(
ConfigurationError.AppendPointer(pointer, "knowledge"),
$"the agent '{item.Id}' declares a knowledge: block and this host registered no "
+ "knowledge vendor, so there is no store to read. Call "
+ "options.UseKnowledgeStores(...) with an adapter that serves "
+ $"{nameof(IKnowledgeRetrievalPort)}, or remove the knowledge: block.");
}

// The same document-level wiring channel 1 reads above, carried onto this agent's own
// resolved knowledge so the search side does not have to re-derive it.
var knowledge = composed with { Clarification = clarification };

providers.Add(KnowledgeProviderFactory.Create(
port,
knowledge,
item.Id,
context.Citations ?? DefaultCitations,
context.Loggers));

return providers;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
using AgentCore.Application.Configuration.Parsing;
using AgentCore.Application.Configuration.Schema;
using AgentCore.Application.Diagnostics;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace AgentCore.Application.Configuration.Compilation;

internal static class AgentToolCompiler
{
public static List<AITool>? Build(
AgentConfiguration item,
ModelReference? model,
Dictionary<string, ToolConfiguration> declared,
AgentCompilationContext context,
string pointer,
Func<string, AIAgent?> resolveAgent)
{
if (item.Tools.Count == 0)
{
return null;
}

List<AITool> tools = [];
for (var index = 0; index < item.Tools.Count; index++)
{
var id = item.Tools[index];

var toolPointer = ConfigurationError.AppendPointer(
ConfigurationError.AppendPointer(pointer, "tools"), index);

if (!declared.TryGetValue(id, out var tool))
{
if (context.Tools is { } discovered && discovered.Contains(id))
{
Add(tools, discovered.Resolve(id), item.Id, id, model, context);
continue;
}

if (context.Tools is null)
{
// No factory, so nothing this loop could have built anyway.
continue;
}

throw ConfigurationCompiler.Fail(toolPointer, $"the tool id '{id}' is not declared in tools:, and no tool source serves it.");
}

if (tool.Kind == ToolKind.Agent)
{
// A kind: agent tool needs no tool factory. Section 7 says section 8 adds no port,
// and this kind adds none either: the inner agent is already in the document.
Add(tools, AgentDelegationTool.Create(tool, ResolveInner(tool, resolveAgent, toolPointer)), item.Id, id, model, context);
continue;
}

if (context.Tools is { } registry)
{
if (!registry.Contains(id))
{
throw ConfigurationCompiler.Fail(toolPointer, $"the tool id '{id}' is declared, and no tool source serves it.");
}

Add(tools, registry.Resolve(id), item.Id, id, model, context);
}
}

return tools.Count == 0 ? null : tools;
}

/// <summary>Adds one tool, unless it is a hosted search this agent's model cannot run.</summary>
/// <remarks>
/// Tested by type and not by the builtin name, so a hosted search tool a host supplies through
/// its own <c>IToolSource</c> is covered by the same rule.
/// </remarks>
private static void Add(
List<AITool> tools,
AITool tool,
string agentId,
string toolId,
ModelReference? model,
AgentCompilationContext context)
{
if (tool is HostedWebSearchTool && !context.ChatClients.SupportsHostedWebSearch(model))
{
var logger = context.Loggers?.CreateLogger(typeof(AgentToolCompiler)) ?? NullLogger.Instance;
var modelDescription = model is { Ref.Length: > 0 } ? $"the model '{model.Ref}'" : "this agent's default model";
Log.HostedWebSearchDropped(logger, agentId, toolId, modelDescription);
return;
}

tools.Add(tool);
}

private static AIAgent ResolveInner(ToolConfiguration tool, Func<string, AIAgent?> resolveAgent, string pointer)
{
if (tool.Agent is not { Length: > 0 } id)
{
throw ConfigurationCompiler.Fail(pointer, $"the tool '{tool.Id}' is kind: agent and names no agent:.");
}

return resolveAgent(id)
?? throw ConfigurationCompiler.Fail(
pointer,
$"the tool '{tool.Id}' delegates to the agent '{id}', which agents.items does not declare.");
}
}
Loading
Loading