Skip to content

fix(agency): launched teams take an environment-routed agent's route, and a seated member keeps its own budget - #622

Merged
jddunn merged 17 commits into
masterfrom
fix/agency-review-threads
Oct 28, 2026
Merged

jddunn merged 17 commits into
masterfrom
fix/agency-review-threads

Conversation

@jddunn

@jddunn jddunn commented Oct 28, 2026 •

Copy link
Copy Markdown
Member

Summary

Fixes the findings the automated review of #382 left open, each checked against today's master, and the three the review of this pull request raised.

  • launch_agency on a gmi() agent whose provider and model come from the environment. The launched team's manager, synthesizers and temporary seats run on the provider and model the agent's persona resolved, the pair its own turns send on. Before, the child agency got no provider and no model, so agency() refused a parallel, debate or hierarchical team and the model got invalid_arguments. The team stays on that pair when the environment comes to prefer another provider after the agent's first call.
  • A persistent member seated in a team (sessionSeat(), or agencies.members through launch_agency) keeps its own budget. Each call of a seat's turn is checked against the member's budget and the budget the team's call carries, and charged to both. A team the member launches from its seat draws on both as well. A budget both draw on, such as a host budget the member's own draws on, is charged once, and so is the one spending total that budgets on one guard and one budgetId keep. Before, the team's budget replaced the member's, so a member's cap was neither checked nor charged on its seat's turns, nor on the teams it launched from them.
  • A refusal by the member's own budget ends the seat's call as a refusal by the launch's budget does: the seat is cut, the launch reports budget_exhausted, and its reason names the cap that refused.
  • TSDoc on LaunchStatus, LaunchRefusalCode, LaunchRefusal, LaunchUsage and LaunchSeatRecord.
  • Docs. GMI.md and COST_OPTIMIZATION.md say how a seat's turn, and a team it launches, is held to both budgets, and how a shared total is charged.

Two of the open threads on #382 were already fixed or do not apply, and are answered there. The public export of sessionSeat() merged in #533. The abort the launch's finally was asked to add is not reachable, since nothing between the start of the team's run and the abort that follows it can throw.

Linked issues

Findings from the automated review of #382. No tracking issue covers them.

Type of change

  • Bug fix
  • Feature
  • Performance
  • Documentation
  • Refactor
  • Tests
  • Build or CI

How this was verified

CI only. The tests came first, in src/api/__tests__/agency-launch-route-budgets.gmi.e2e.test.ts and src/api/runtime/__tests__/spendBudget.test.ts, and CI failed on each for the reason its finding names before its fix was pushed:

  • CI run 40696113992 (head e239208): the parallel launch from an agent routed by the environment was refused with invalid_arguments: Parallel strategy requires an agency-level model or provider for synthesis, and the seated member's own budget counted 0 tokens where 15 were expected.
  • CI run 40704041739 (head af1db1e), with those two fixed and green: the member that launched a team from its seat had 29 tokens on its own budget where 44 were expected.
  • CI run 40705699615 (head 010746a): green, every job.
  • CI run 40722815492 (head 6a1fbfa), the tests for the findings on this pull request: a seat's 0.30 call left a total the host's budget and the member's own share by guard and id at 0.60 where 0.30 was expected (end to end, and through bothBudgets() for a call and an outside cost); the seat whose member's own token cap refused its call was failed where cut was expected; and after the environment came to prefer another provider, the team's seats and synthesizer called that provider.
  • CI run 40727813764 (head abeb303): green, every job and every other check.

Migration notes

None. No public type loses a member and no default changes. A member that sets its own budget now has it applied on its seat's turns and on the teams it launches from them, which is what that option documents. A launch whose seat's call a member's own budget refuses now reports budget_exhausted where it reported failed.

Checklist

  • Tests cover the changed behavior.
  • Docs are updated.
  • The title follows Conventional Commits, with ! before the colon for a change that breaks users (feat!: or feat(api)!:).
  • No secrets or private data are included.
  • Every automated review thread is settled (how).
  • I have read this change and can explain every line.

Summary by Sourcery

Fix GMI agency launches to preserve the resolved model route and enforce member and team spending limits consistently.

Bug Fixes:

  • Ensure launched agency teams inherit the provider and model route resolved by their parent GMI, including routes selected from the environment.
  • Enforce persistent members’ own budgets alongside the enclosing team budget for seat turns and nested teams, while avoiding duplicate charges for shared budgets and spending totals.

Enhancements:

  • Add comprehensive TSDoc for agency launch statuses, refusals, usage, seat records, and budget behavior.

Documentation:

  • Document GMI budget support and the combined budget rules for seated members and teams they launch.

Tests:

  • Add end-to-end coverage for environment-routed launches, route stability, seated-member budget enforcement, nested launches, and shared budget accounting.
  • Add unit coverage for combined budget checks and deduplicated charging.

@coderabbitai

coderabbitai Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

  • Run on-demand review

This review includes 11 billable files and costs up to $2.75.

  • Ask an admin to make reviews automatic

Open in CodeRabbit

Reviews can continue after your included limit without a manual trigger. An admin must approve usage-based billing.

Or wait 17 minutes for your next included review.

Check out review usage here.

View limit details

Limit details: You’ve used all 4 included reviews currently available.

Learn how review limits work.

Review configuration:

Run configuration
Commits

Reviewing files that changed from the base of the PR and between 82a79c8 and abeb303.

Files selected for processing: 11
  • docs/GMI.md
  • docs/safety/COST_OPTIMIZATION.md
  • src/api/__tests__/agency-launch-route-budgets.gmi.e2e.test.ts
  • src/api/agent.ts
  • src/api/gmi.ts
  • src/api/runtime/__tests__/spendBudget.test.ts
  • src/api/runtime/agencyLaunch/gmiLaunchTool.ts
  • src/api/runtime/agencyLaunch/runLaunch.ts
  • src/api/runtime/agencyLaunch/sessionSeat.ts
  • src/api/runtime/agencyLaunch/types.ts
  • src/api/runtime/spendBudget.ts
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

@sourcery-ai

sourcery-ai Bot commented Oct 28, 2026

Copy link
Copy Markdown

Reviewer's Guide

This PR fixes agency launches for environment-routed gmi() agents by carrying the parent’s resolved route into team execution, while preserving persistent members’ own budgets alongside the launch budget with correct shared-budget accounting. It adds focused end-to-end tests for routing, seat failures, token usage, and launch results, plus API documentation and TSDoc updates.

File-Level Changes

Change Details Files
Added end-to-end coverage for environment-resolved launch routes and persistent-member budget enforcement.
  • Verifies a gmi() agent without explicit provider/model launches a parallel team using the route resolved by its first call, including seat and synthesizer calls.
  • Verifies persistent seats are checked against both member and launch budgets, with shared parent budgets charged only once.
  • Covers successful and rejected seat calls, launch status/provenance, token accounting, and resulting errors.
src/api/__tests__/agency-launch-route-budgets.gmi.e2e.test.ts
Propagated the launching agent’s resolved provider/model route into launched agency execution.
  • Ensures coordinator, seats, and synthesizer use the route selected for the parent agent when provider and model originate from environment resolution.
  • Preserves compatibility with the synthesizer’s non-streaming legacy execution path.
Implementation files not included in the supplied diff
Corrected budget composition and accounting for persistent agency members.
  • Keeps a seated member’s own budget active alongside the team call budget.
  • Checks each seat turn against both applicable budgets and avoids double-charging shared parent budgets.
Implementation files not included in the supplied diff
Documented launch status and budget behavior and corrected API guidance.
  • Added TSDoc for launch result, refusal, usage, and seat-record types.
  • Updated GMI documentation to describe budget support and dual-budget seat enforcement.
Documentation and type-definition files not included in the supplied diff

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@jddunn
jddunn marked this pull request as ready for review October 28, 2026 14:32
@jddunn
jddunn requested a review from Victor-Evogor as a code owner October 28, 2026 14:32
@sourcery-ai

sourcery-ai Bot commented Oct 28, 2026

Copy link
Copy Markdown

Sorry @jddunn, you've used your own review budget of 250,000 diff characters for the last 7 days.

You can request another review in 3 days and 14 hours by commenting @sourcery-ai review. Upgrade to get a review now.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-28T14:35:21.179994Z 010746a Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Summary by Qodo

Fix launched-team routing and persistent member budgets

🐞 Bug fix 🧪 Tests 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Route launched-team coordinators through the provider and model resolved by an
 environment-configured GMI agent.
• Enforce both team and member budgets on seated turns and teams launched from them, without
 double-charging shared ancestors.
• Add end-to-end coverage and correct GMI budget documentation and launch-type TSDoc.
Diagram

graph TD
  A["GMI agent"] --> B["Resolved route"] --> C["Launch agency"] --> D["Team coordinators"]
  C --> E["Persistent seat"] --> F{"Dual budget check"}
  E --> G["Nested team"] --> F
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Carry a collection of budgets through every call
  • ➕ Makes independent budget constraints explicit without a composite SpendBudget.
  • ➖ Requires broader changes to call contexts, metering, and launch interfaces; shared-ancestor deduplication is still necessary.

Recommendation: Keep the composite-budget approach: it preserves the existing single-budget interfaces while enforcing both constraints on seated and nested calls. Review the synchronous shared-ancestor deduplication carefully, since its correctness underpins charging each budget once.

Files changed (10) +351 / -21

Bug fix (4) +143 / -13
gmi.tsApply member and carried budgets to seated GMI turns +16/-6

Apply member and carried budgets to seated GMI turns

• Combines a seated member’s agent budget with a budget carried by a session send or stream, rather than replacing the member’s budget. Non-seat calls retain the existing per-call override behavior.

src/api/gmi.ts

gmiLaunchTool.tsGive launched teams the GMI agent’s resolved route +22/-2

Give launched teams the GMI agent’s resolved route

• Supplies the launching agent’s configured provider and model, or resolves them from the environment when neither is configured. This lets strategies requiring an agency-level route start on an environment-routed GMI agent.

src/api/runtime/agencyLaunch/gmiLaunchTool.ts

runLaunch.tsCarry a seated member’s combined budget into nested launches +9/-5

Carry a seated member’s combined budget into nested launches

• Uses the calling seat turn’s budget for a nested launch when available, falling back to its parent launch’s budget. Teams launched from a persistent member’s seat therefore draw on the member’s budget as well.

src/api/runtime/agencyLaunch/runLaunch.ts

spendBudget.tsCheck and charge two budgets without duplicate ancestor charges +96/-0

Check and charge two budgets without duplicate ancestor charges

• Introduces a composite budget that checks and records against both underlying budgets and reports the tighter remaining allowance. Synchronous reach tracking prevents a budget shared by their parent chains from being checked or charged twice for one operation.

src/api/runtime/spendBudget.ts

Tests (1) +159 / -0
agency-launch-route-budgets.gmi.e2e.test.tsCover launched-team routing and seated-member budgets +159/-0

Cover launched-team routing and seated-member budgets

• Adds provider-stubbed end-to-end tests for an environment-routed parallel launch, a persistent member’s permitted and refused seat calls, and a team launched from a member’s seat. Assertions cover route use, budget charges, and shared-ancestor deduplication.

src/api/tests/agency-launch-route-budgets.gmi.e2e.test.ts

Documentation (5) +49 / -8
GMI.mdDocument GMI spend budgets and seated-member accounting +6/-4

Document GMI spend budgets and seated-member accounting

• Corrects statements that GMI construction rejects budgets and lists supported per-call budget options. Explains how a seat and a team it launches are held to both the carried and member budgets without double-charging a shared budget.

docs/GMI.md

COST_OPTIMIZATION.mdCorrect the cost guide’s GMI budget guidance +1/-1

Correct the cost guide’s GMI budget guidance

• Replaces the claim that GMI agents reject budgets with a description of GMI model-call checks and seated-member budget enforcement.

docs/safety/COST_OPTIMIZATION.md

agent.tsClarify the agent budget contract for seats +2/-0

Clarify the agent budget contract for seats

• Documents that a seated member’s budget applies alongside its team’s carried budget, including to teams the member launches.

src/api/agent.ts

sessionSeat.tsDocument budget behavior of persistent seats +7/-2

Document budget behavior of persistent seats

• Clarifies that seat calls are checked against and charged to both the team-carried budget and the persistent member’s own budget.

src/api/runtime/agencyLaunch/sessionSeat.ts

types.tsDocument launch outcomes, refusals, usage, and route selection +33/-1

Document launch outcomes, refusals, usage, and route selection

• Adds TSDoc for launch status and refusal types, usage and seat records, and how a GMI agent supplies a launched team’s route.

src/api/runtime/agencyLaunch/types.ts

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Shared caps can be charged twice ✓ Resolved
Description
BothBudgets.record() forwards each call to both component budgets without deduplicating distinct
SpendBudget objects that share a CostGuard and budgetId, even though reachedBefore()
deduplicates budget objects. When a seated member’s budget and the team’s budget use that shared
account, one call increments its session and daily cost totals twice, causing later calls to hit the
cap early and the reported provider cost to be doubled.
Code

src/api/runtime/spendBudget.ts[R336-339]

+  override record(costUSD: number | undefined, tokens: number, what: string): void {
+    reachOnce('charge', () => {
+      this.first.record(costUSD, tokens, what);
+      this.second.record(costUSD, tokens, what);
Evidence
The module defines budgets with the same guard and ID as sharing one spending total. The new
composition records through both component objects, so two distinct objects using that account each
increment it for the same call; the changed implementation has no regression test covering this
case.

AGENTS.md: Provide Meaningful Tests for Changed Behavior: AGENTS.md: Provide Meaningful Tests for Changed Behavior: AGENTS.md: Provide Meaningful Tests for Changed Behavior: AGENTS.md: Provide Meaningful Tests for Changed Behavior: AGENTS.md: Provide Meaningful Tests for Changed Behavior: AGENTS.md: Provide Meaningful Tests for Changed Behavior: AGENTS.md: Provide Meaningful Tests for Changed Behavior: AGENTS.md: Provide Meaningful Tests for Changed Behavior
src/api/runtime/spendBudget.ts[336-340]
src/api/runtime/tests/spendBudget.test.ts[28-36]
src/api/runtime/spendBudget.ts[2-8]
src/api/runtime/spendBudget.ts[142-161]
src/api/runtime/spendBudget.ts[101-105]
src/safety/runtime/CostGuard.ts[122-130]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`BothBudgets.record()` charges a shared spending account twice when distinct component budgets use the same `CostGuard` and `budgetId`. Add regression coverage and ensure each call charges that account only once.
## Fix Focus Areas
- src/api/runtime/spendBudget.ts[93-118]
- src/api/runtime/spendBudget.ts[329-348]
- src/api/runtime/__tests__/spendBudget.test.ts[28-36]
## Recommended Fix
Deduplicate recording by the underlying guard and budget ID, or otherwise coordinate the component updates so a shared account receives one charge per call while preserving the checks and token-cap accounting required by each distinct budget object. Add a test using separate `SpendBudget` instances with the same guard and ID through `bothBudgets()`, and verify that shared cost and token totals increase only once.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

2. Launched teams can take the wrong route ✓ Resolved
Description
teamRoute() derives the coordinator route from construction-time opts or a fresh environment
lookup rather than the persona serving the launching call. If a generate() call overrides its
provider or model, or the environment changes after a session’s persona is built, the launched
team’s manager or synthesizer can use a different route or be refused despite the launching call
having a valid one.
Code

src/api/runtime/agencyLaunch/gmiLaunchTool.ts[R93-95]

+    // The call gmi()'s persona makes on the agent's first call, with no provider and no model named.
+    const { providerId, modelId } = resolveModelOption({ baseUrl: opts.baseUrl }, 'text');
+    return { provider: providerId, model: modelId };
Evidence
Per-call overrides produce a different persona, and session personas are cached after resolution;
the new launch lookup instead uses the original options or reads the environment again. The
resulting route is passed into the child agency.

src/api/gmi.ts[687-700]
src/api/gmi.ts[432-435]
src/api/gmi.ts[443-464]
src/api/runtime/agencyLaunch/gmiLaunchTool.ts[88-100]
src/api/runtime/agencyLaunch/runLaunch.ts[346-359]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The team route is resolved independently from static agent options, so it can differ from the launching GMI call’s effective provider and model.
## Fix Focus Areas
- src/api/runtime/agencyLaunch/gmiLaunchTool.ts[82-100]
- src/api/runtime/agencyLaunch/gmiLaunchTool.ts[265-271]
- src/api/gmi.ts[687-700]
## Recommended Fix
Carry the launching turn’s resolved provider and model into the launch host and use them for the child agency’s coordinator route. Cover both a per-call route override and an environment change after a session persona is initialized.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. A member's spent budget shows as a failed team ✓ Resolved
Description
turnBudget wraps a persistent seat's turn in bothBudgets(launchBudget, agentBudget), but only
the launch budget's onLimitReached sets state.exhausted. When the member's own budget refuses a
call, nothing reaches that callback, because the member's budget is a sibling of the launch budget,
not one of its ancestors. As a result cutWhen() stays false and the launch reports failed rather
than budget_exhausted. A nested launch from the same seat does get budget_exhausted when the
member's budget refuses, because its child budget's parent is the BothBudgets, so the reported
status depends on where the refusal happened.
Code

src/api/gmi.ts[R851-855]

+      const turnBudget = (carried: SpendBudget | SpendBudgetOptions | undefined): SpendBudget | undefined => {
+        const budget = asSpendBudget(carried);
+        if (!budget) return agentBudget;
+        return seat && agentBudget ? bothBudgets(budget, agentBudget) : budget;
+      };
Evidence
runLaunch sets state.exhausted only from the launch child budget's onLimitReached (line 616),
and statusOf returns budget_exhausted only when that flag is set (line 381).
SpendBudget.assertCanSpend runs a budget's own onLimitReached only when that budget refuses, or
when one of its options.parent ancestors refuses (spendBudget.ts lines 202-212).
BothBudgets.assertCanSpend checks first (the launch child) and then second (the member's own)
as separate budgets, so a refusal from second never reaches the child's callback. The new TSDoc on
LaunchStatus says budget_exhausted covers "a budget it draws on", and the PR now makes the
launch's seat calls draw on the member's own budget.

src/api/runtime/agencyLaunch/runLaunch.ts[607-618]
src/api/runtime/agencyLaunch/runLaunch.ts[378-392]
src/api/runtime/agencyLaunch/runLaunch.ts[501-501]
src/api/runtime/spendBudget.ts[196-214]
src/api/runtime/spendBudget.ts[329-334]
src/api/runtime/agencyLaunch/types.ts[152-157]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
When a persistent member is seated by launch_agency, each turn runs under `bothBudgets(launch.budget, memberBudget)`. A refusal from the member's own budget does not run the launch budget's `onLimitReached`, so `state.exhausted` stays false: `cutWhen()` returns false and the launch reports `failed` rather than `budget_exhausted`.
## Fix Focus Areas
- src/api/runtime/spendBudget.ts[329-334]
- src/api/gmi.ts[851-855]
- src/api/runtime/agencyLaunch/runLaunch.ts[607-618]
## Recommended Fix
In `BothBudgets.assertCanSpend`, catch the error thrown by `second.assertCanSpend`. If the error carries refusal info (`refusalInfo`), call `first.options.onLimitReached` with it when that option is a function, as the parent-refusal path in `SpendBudget.assertCanSpend` already does. Then rethrow. Add a test where the seated member's own budget refuses and the launch reports `budget_exhausted`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Tip of the day
💡 Did you know, you can turn on the rule miner and Qodo learns your standards from review history

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment thread src/api/runtime/spendBudget.ts Resolved
Comment thread src/api/gmi.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 010746a5e6

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/api/runtime/spendBudget.ts Resolved
…hreads

# Conflicts:
#	docs/GMI.md
#	docs/safety/COST_OPTIMIZATION.md
…get and the member's own share by guard and id
…h bothBudgets, for a call and an outside cost
…, and the launch reports the budget that refused
…ll resolved when the environment comes to prefer another provider
…s call as the launch's budget would, and the launch names the budget that refused
… the pair the agent's persona resolved, not the environment's at launch time
@jddunn
jddunn merged commit f1bc241 into master Oct 28, 2026
17 of 18 checks passed
@jddunn
jddunn deleted the fix/agency-review-threads branch October 28, 2026 16:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant