Repository navigation
.NET: add token and time budgets to LoopAgent - #9165
Open
Mark Licata (marklicata) wants to merge 5 commits into
Open
Mark Licata (marklicata) wants to merge 5 commits into
Mark Licata (marklicata) wants to merge 5 commits into
Conversation
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Mark Licata (marklicata)
temporarily deployed
to
github-app-auth
October 7, 2026 15:34 — with
GitHub Actions
Inactive
Mark Licata (marklicata)
temporarily deployed
to
github-app-auth
October 7, 2026 15:34 — with
GitHub Actions
Inactive
5 tasks done
Mark Licata (marklicata)
temporarily deployed
to
github-app-auth
October 7, 2026 15:34 — with
GitHub Actions
Inactive
5 tasks done
Mark Licata (marklicata)
temporarily deployed
to
github-app-auth
October 7, 2026 15:38 — with
GitHub Actions
Inactive
Contributor
There was a problem hiding this comment.
🟡 Changes recommended
Duration limits cannot interrupt blocked calls or streams, leaving wall-clock enforcement incomplete.
2 open findings
What changed in this PR
Adds opt-in resource budgets to .NET LoopAgent, complementing the Python work in #9164.
Changes:
- Adds token and duration limits with checks before evaluators.
- Introduces exit-reason constants for budget and iteration-cap stops.
- Adds non-streaming tests and updates all five public API baselines.
| File | Description |
|---|---|
| dotnet/tests/Microsoft.Agents.AI.UnitTests/Harness/Loop/LoopAgentBudgetTests.cs | Tests non-streaming budget stops and evaluator ordering. |
| dotnet/src/Microsoft.Agents.AI/PublicAPI/netstandard2.0/PublicAPI.Unshipped.txt | Records new budget APIs. |
| dotnet/src/Microsoft.Agents.AI/PublicAPI/net9.0/PublicAPI.Unshipped.txt | Records new budget APIs. |
| dotnet/src/Microsoft.Agents.AI/PublicAPI/net8.0/PublicAPI.Unshipped.txt | Records new budget APIs. |
| dotnet/src/Microsoft.Agents.AI/PublicAPI/net472/PublicAPI.Unshipped.txt | Records new budget APIs. |
| dotnet/src/Microsoft.Agents.AI/PublicAPI/net10.0/PublicAPI.Unshipped.txt | Records new budget APIs. |
| dotnet/src/Microsoft.Agents.AI/Harness/Loop/LoopExitReason.cs | Defines experimental exit-reason constants. |
| dotnet/src/Microsoft.Agents.AI/Harness/Loop/LoopAgentOptions.cs | Adds validated budget options. |
| dotnet/src/Microsoft.Agents.AI/Harness/Loop/LoopAgent.cs | Tracks budgets and stops subsequent iterations. |
🧠 Review effort: Balanced
💡 Add a code-review agent skill for context-aware, tailored reviews. Learn more in the docs.
Mark Licata (marklicata)
marked this pull request as ready for review
October 7, 2026 15:57
Mark Licata (marklicata)
temporarily deployed
to
github-app-auth
October 7, 2026 15:57 — with
GitHub Actions
Inactive
…g budget tests Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Mark Licata (marklicata)
temporarily deployed
to
github-app-auth
October 7, 2026 16:04 — with
GitHub Actions
Inactive
westey (westey-m)
requested changes
Oct 13, 2026
- Use Throw.IfLessThanOrEqual for MaxTokens validation. - Log a warning (once per run) when MaxTokens is set but the inner agent's response reports no token usage, in both RunAsync and RunStreamingAsync. - Document what MaxTokens counts: inner agent input+output tokens (TotalTokenCount, falling back to Input+Output); evaluator and judge usage is not counted. - Add tests for the warning, option validation, and judge usage exclusion. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Mark Licata (marklicata)
deployed
to
github-app-auth
October 13, 2026 15:42 — with
GitHub Actions
Active
Mark Licata (marklicata)
deployed
to
integration
October 13, 2026 15:42 — with
GitHub Actions
Active
Mark Licata (marklicata)
deployed
to
integration
October 13, 2026 15:42 — with
GitHub Actions
Active
ChatClientAgent now adds the usage of the sub-agents it invokes to its own AgentResponse.Usage, in both RunAsync and RunStreamingAsync, so that LoopAgentOptions.MaxTokens also counts sub-agent tokens. - An internal AsyncLocal SubAgentUsageScope (modelled on ServedModelScope) holds a lock-based usage accumulator per ChatClientAgent run. It is set up before context providers run and re-established after each streaming yield. - AsAIFunction adds the sub-agent's reported usage to the caller's scope and clears the scope for the sub-agent's own run, so A -> B -> C counts each layer once. Concurrent tool invocations are summed safely. - FunctionInvokingChatClient overwrites response usage with its own model call totals, so the merge happens after it returns. Streaming runs end with a usage-only update carrying the sub-agent total. - BackgroundAgentsProvider charges each successful background run once, to the parent run that first observes its completion (context provision or the wait/result tools). Runs that finish after the last parent run, or are only finalized at release, are not counted. - OpenTelemetryAgent keeps reporting each agent's own usage on its invoke_agent span; the rolled-up sub-agent usage is excluded. - Failed or cancelled sub-agents and agents invoked directly from custom tools are not counted. No public API changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Mark Licata (marklicata)
deployed
to
github-app-auth
October 13, 2026 16:39 — with
GitHub Actions
Active
Mark Licata (marklicata)
deployed
to
github-app-auth
October 13, 2026 16:39 — with
GitHub Actions
Active
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Mark Licata (marklicata)
deployed
to
github-app-auth
October 13, 2026 16:52 — with
GitHub Actions
Active
Mark Licata (marklicata)
deployed
to
integration
October 13, 2026 16:52 — with
GitHub Actions
Active
Mark Licata (marklicata)
deployed
to
integration
October 13, 2026 16:52 — with
GitHub Actions
Active
This branch was successfully deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.


Motivation & Context
Autonomous loops need explicit resource limits. Without them, a confused or looping agent can burn tokens indefinitely or hold a session open on a slow external tool, and neither is safe for production. This adds token and wall-clock budgets to
LoopAgent.This is the .NET half of the work previously proposed in #8994, split per language at the reviewers' request. The Python counterpart is #9164 and uses the same exit-reason strings.
Description & Review Guide
What are the major changes?
LoopAgentOptions.MaxTokens(long?) andMaxDuration(TimeSpan?)LoopAgent(non-streaming) stampsLoopExitReason.TokenBudgetExceeded/TimeBudgetExceededon budget stops andLoopExitReason.IterationCapReachedwhenMaxIterationsfiresLoopExitReason:[Experimental]static class withAdditionalPropertiesKey,IterationCapReached,TokenBudgetExceeded,TimeBudgetExceededPublicAPI.Unshipped.txtupdated for all 5 target frameworksWhat is the impact of these changes?
Opt-in;
LoopAgentwithout budgets behaves as today.LoopExitReasonis also introduced by the .NET signal-protocol PR; whichever lands second unions the constants during its merge frommain.What do you want reviewers to focus on?
AdditionalPropertiesSub-agent usage
MaxTokensalso counts sub-agent tokens. An internalAsyncLocalscope onChatClientAgentrolls the usage of sub-agents called viaAsAIFunctionandBackgroundAgentsProviderinto the parent'sAgentResponse.Usage. This applies to bothRunAsyncandRunStreamingAsync; a streaming run ends with a usage-only update. Each layer of A→B→C is counted once. Theinvoke_agenttelemetry spans still report each agent's own usage, and there is no public API change.Known gaps, documented on
MaxTokens:RunAsyncaren't counted.Related Issue
Part of #8862, together with #9164 for Python. The issue is closed manually once both PRs have merged.
Contribution Checklist
🤖 Generated with Claude Code