Skip to content

fix(gateway): the completion gateway resolves and walks its chain as generateText and streamText do - #341

Merged
jddunn merged 2 commits into
masterfrom
fix/gateway-resolves-its-chain
Oct 12, 2026
Merged

jddunn merged 2 commits into
masterfrom
fix/gateway-resolves-its-chain

Conversation

@jddunn

@jddunn jddunn commented Oct 12, 2026 •

Copy link
Copy Markdown
Member

The completion gateway built its hop list as the caller's chain or the policy chain, unresolved, so the checks generateText's and streamText's walks make never applied to a GMI turn's fallback hops (#139): a model in routerParams.excludedModelIds was sent, an entry lacking an explicitly required capability was tried, the policy chain's entry for the first model was retried, every refill ran, and the policy chain's Claude legs ran after a refusal.

  • resolve() resolves the chain once with resolveFallbackChain (the route's excluded models and explicit capabilities, each entry checked as it will be sent; the policy chain's entry for the first model dropped; standing legs and refills marked).
  • Each CompletionResolution carries the walk's state; every fallback hop passes gateFallbackEntry (a refill only while a standing leg is owed one, no policy-chain Claude leg after a refusal).
  • resolve(route, after, failure) takes the error the previous hop failed with, and the GMI passes it. A hop that cannot start counts as an availability failure.
  • Passed-over entries are reported through onHopSkipped, which the GMI writes to its reasoning trace.

Tests: completionGateway.test.ts (the #139 case with a provider default and a provider:-prefixed id, the failed first model's ladder entry, refusals vs. outages over the real catalog's mature ladder, a standing leg that cannot start owing a refill) and GMI.completion-gateway.test.ts (a GMI turn whose first model refuses passes over a policy-chain Claude leg to the next leg).

Closes #139.

Summary by Sourcery

Align completion fallback resolution and walking with generateText and streamText so each hop respects routing constraints and failure-aware fallback behavior.

Bug Fixes:

  • Make the completion gateway apply the same resolved fallback-chain walking rules as generateText and streamText, preventing excluded or unsupported models and inappropriate policy legs from being attempted.
  • Pass provider failure context through fallback resolution so refusals and availability failures select the correct subsequent hops.

Enhancements:

  • Report skipped fallback entries through completion callbacks and include them in GMI reasoning traces.

Tests:

  • Add coverage for exclusions, capability filtering, failed-primary handling, refusal versus outage walks, refill behavior, and GMI policy-chain skips.

…generateText and streamText do

createCompletionGateway built its hop list as the caller's chain or the
policy chain, unresolved, so the checks the walkers make never applied to a
GMI turn's fallback hops: a model in routerParams.excludedModelIds was sent,
an entry lacking an explicitly required capability was tried, the policy
chain's entry for the first model was retried, every refill ran, and the
policy chain's Claude legs ran after a refusal.

The gateway now resolves the chain once with resolveFallbackChain, keeps the
walk's state on each resolution, and gates every fallback hop with
gateFallbackEntry. resolve() takes the error the previous hop failed with;
the GMI passes it, so a refusal passes over the Claude legs and a standing
leg that failed on availability is owed the next ranked model. A hop that
cannot start counts as an availability failure. Passed-over entries are
reported through onHopSkipped, which the GMI writes to its reasoning trace.

Closes #139.
@jddunn
jddunn requested a review from Victor-Evogor as a code owner October 12, 2026 14:45
@sourcery-ai

sourcery-ai Bot commented Oct 12, 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 4 days and 15 hours by commenting @sourcery-ai review. Upgrade to get a review now.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 12, 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-12T14:48:17.189789Z fcf9710 PR opened
ℹ️ 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.

@sourcery-ai

sourcery-ai Bot commented Oct 12, 2026

Copy link
Copy Markdown

Reviewer's Guide

The completion gateway now resolves and walks fallback chains with the same filtering and stateful semantics as generateText and streamText, including refusal-aware gating, availability-driven refills, and skipped-hop diagnostics; GMI passes failure context through and records those skips, with regression tests covering the affected scenarios.

Sequence diagram for stateful completion fallback walking

sequenceDiagram
    participant GMI
    participant Gateway as CompletionGateway
    participant Resolver as FallbackWalk
    participant Provider

    GMI->>Gateway: resolve(route)
    Gateway->>Resolver: resolveFallbackChain(fallbacks, requirements)
    Resolver-->>Gateway: resolved chain and INITIAL_FALLBACK_WALK
    Gateway->>Resolver: gateFallbackEntry(walk, entry)
    Gateway->>Provider: start hop
    Provider-->>Gateway: completion or failure
    Gateway-->>GMI: resolution with walk state
    GMI->>Gateway: resolve(route, failedResolution, failure)
    Gateway->>Resolver: advanceFallbackWalk(walk, walkRole, failure)
    Gateway->>Resolver: gateFallbackEntry(updatedWalk, nextEntry)
    alt entry is passed over
        Gateway-->>GMI: onHopSkipped(provider, model, reason)
    else entry can run
        Gateway->>Provider: start fallback hop
    end
Loading

File-Level Changes

Change Details Files
Make completion fallback chains resolve once and follow the same stateful walk semantics as text generation.
  • Resolve exclusions, required capabilities, policy-primary duplication, standing legs, and refills before serving hops.
  • Carry walk state across resolutions and gate refills and refusal-sensitive entries.
  • Treat failed-to-start hops as availability failures that can advance refill state.
  • Report every skipped fallback entry through the route callback.
src/api/runtime/completionGateway.ts
Propagate fallback failures and skipped-hop diagnostics through GMI turns.
  • Pass the prior hop's error into subsequent gateway resolution.
  • Write skipped-hop reasons into the reasoning trace.
src/cognition/substrate/GMI.ts
Add regression coverage for resolved chains, walk state, availability handling, and GMI refusal behavior.
  • Verify exclusions and capability/policy-chain filtering, refusal versus outage traversal, and refill behavior.
  • Verify a non-startable standing leg advances the walk.
  • Verify GMI skips policy Claude legs after a refusal and reaches the next fallback.
src/api/runtime/__tests__/completionGateway.test.ts
src/cognition/substrate/__tests__/GMI.completion-gateway.test.ts

Assessment against linked issues

Issue Objective Addressed Explanation
#139 Resolve the completion gateway’s fallback chain once using the same filtering as generateText and streamText, including excluded model IDs and explicitly required capabilities. ✅
#139 Add a gateway regression test proving an excluded provider-default model is not attempted on a fallback hop. ✅

Possibly linked issues


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

@coderabbitai

coderabbitai Bot commented Oct 12, 2026

Copy link
Copy Markdown

Warning

Review limit reached

  • Run on-demand review

This review includes 4 billable files and costs up to $1.00.

  • 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 14 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
  • Configuration used: Repository: framerslab/agentos/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Team
  • Run ID: 6c8c3f1a-ca34-4a1f-8118-bbb366b7d9dc

📥 Commits

Reviewing files that changed from the base of the PR and between 2293b0d and fcf9710.


📒 Files selected for processing (4)
  • src/api/runtime/__tests__/completionGateway.test.ts
  • src/api/runtime/completionGateway.ts
  • src/cognition/substrate/GMI.ts
  • src/cognition/substrate/__tests__/GMI.completion-gateway.test.ts

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

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

Copy link
Copy Markdown

PR Summary by Qodo

Align completion gateway fallback walks with generateText and streamText

🐞 Bug fix 🧪 Tests 🕐 20-40 Minutes

Grey Divider

AI Description

• Resolve gateway fallback chains against model exclusions and explicit capability requirements
 before attempting hops.
• Track failures and refusals so refills and policy-chain Claude hops follow the shared fallback
 rules.
• Trace skipped hops and cover gateway behavior and a full GMI turn.
Diagram

graph TD
  GMI["GMI turn"] --> Gateway["Completion gateway"] --> Resolve["Resolve chain"] --> Gate{"Run hop?"} --> Provider["Model provider"]
  Provider -- "failure" --> State["Walk state"] --> Gate
  Resolve -- "excluded entry" --> Trace["Reasoning trace"]
  Gate -- "skipped entry" --> Trace
Loading
High-Level Assessment

Reusing the existing fallback-chain resolver and walk helpers is the best fit: it aligns gateway behavior with generateText and streamText without duplicating policy rules or broadly refactoring their walkers.

Files changed (4) +220 / -7

Bug fix (2) +73 / -6
completionGateway.tsResolve and gate completion fallback hops +70/-5

Resolve and gate completion fallback hops

• Resolves each route's fallback chain once using explicit capability requirements and model exclusions. Carries walk state between resolutions, uses the previous hop's failure to gate subsequent entries, and reports skipped entries through a callback.

src/api/runtime/completionGateway.ts

GMI.tsPass hop failures to the gateway and trace skipped entries +3/-1

Pass hop failures to the gateway and trace skipped entries

• Passes the failed attempt's error into the next gateway resolution so refusal and availability rules apply. Writes passed-over fallback entries and their reasons to the reasoning trace.

src/cognition/substrate/GMI.ts

Tests (2) +147 / -1
completionGateway.test.tsCover resolved chains and stateful fallback walks +124/-1

Cover resolved chains and stateful fallback walks

• Adds tests for excluded models, policy-chain primary deduplication, refusal and outage behavior, and refills owed when a standing leg cannot start. Exercises the real fallback catalog and records skipped-hop reasons.

src/api/runtime/tests/completionGateway.test.ts

GMI.completion-gateway.test.tsVerify refusal handling through a GMI turn +23/-0

Verify refusal handling through a GMI turn

• Adds a turn-level test showing that a primary refusal skips a policy-chain Claude leg, serves the next leg, and records the skip in the reasoning trace.

src/cognition/substrate/tests/GMI.completion-gateway.test.ts

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

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

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. Refusals reach Claude for some agents 🐞 Bug ≡ Correctness
Description
gatewayFor() wraps resolve() for agents with an onFallback listener but forwards only route
and after, dropping the newly passed outcome.error. When such an agent's model fails with
content_filter, advanceFallbackWalk() receives undefined and never records the refusal, so
policy-chain Claude hops remain eligible.
Code

src/cognition/substrate/GMI.ts[1815]

+              const next = await gateway.resolve(route, failedHop, outcome.error);
Evidence
GMI passes the failed attempt's error, but the wrapper used when an agent has an onFallback listener
discards it. The gateway advances its walk using that missing value, while the shared walk records a
refusal only when the error carries code content_filter; the gate skips policy Claude entries only
after that refusal is recorded.

src/cognition/substrate/GMI.ts[1810-1815]
src/api/gmi.ts[226-242]
src/api/runtime/completionGateway.ts[585-589]
src/api/generateText.ts[1869-1904]

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 agent-level fallback-listener wrapper discards the failure argument passed by GMI, preventing the gateway from recognizing content refusals and skipping policy-chain Claude hops.
## Fix Focus Areas
- src/api/gmi.ts[228-242]
## Recommended Fix
Accept the third `failure` argument in the wrapper's `resolve` function and forward it to `base.resolve` after `after`. Add a test that exercises a GMI agent with an `onFallback` listener and a content-refusal fallback.

ⓘ 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 commit Qodo's fix in one click with committable suggestions (GitHub & GitLab)

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

throw new GMIError(`LLM provider error: ${outcome.error.message}`, GMIErrorCode.LLM_PROVIDER_ERROR, { turnId, providerId: failedHop.providerId, hop: failedHop.hop });
}
const next = await gateway.resolve(route, failedHop);
const next = await gateway.resolve(route, failedHop, outcome.error);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Action required

1. Refusals reach claude for some agents 🐞 Bug ≡ Correctness

gatewayFor() wraps resolve() for agents with an onFallback listener but forwards only route
and after, dropping the newly passed outcome.error. When such an agent's model fails with
content_filter, advanceFallbackWalk() receives undefined and never records the refusal, so
policy-chain Claude hops remain eligible.
Agent Prompt
## Issue description
The agent-level fallback-listener wrapper discards the failure argument passed by GMI, preventing the gateway from recognizing content refusals and skipping policy-chain Claude hops.
## Fix Focus Areas
- src/api/gmi.ts[228-242]
## Recommended Fix
Accept the third `failure` argument in the wrapper's `resolve` function and forward it to `base.resolve` after `after`. Add a test that exercises a GMI agent with an `onFallback` listener and a content-refusal fallback.

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

@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: fcf9710d10

ℹ️ 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".

throw new GMIError(`LLM provider error: ${outcome.error.message}`, GMIErrorCode.LLM_PROVIDER_ERROR, { turnId, providerId: failedHop.providerId, hop: failedHop.hop });
}
const next = await gateway.resolve(route, failedHop);
const next = await gateway.resolve(route, failedHop, outcome.error);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Forward the failure through the agent gateway wrapper

When an agent() is configured with onFallback, gatewayFor() in src/api/gmi.ts wraps resolve as (route, after) => base.resolve(..., after) and silently discards this new third argument. Consequently, a content-filter refusal is treated as an availability failure: refusalSeen remains false, refills may be incorrectly owed, and policy-default Claude legs are attempted instead of skipped. Forward failure from the wrapper; the added GMI test injects the base gateway directly and therefore does not exercise this observable public-agent path.

AGENTS.md reference: AGENTS.md:L53-L53

Useful? React with 👍 / 👎.

@jddunn
jddunn merged commit b4c8280 into master Oct 12, 2026
9 checks passed
@jddunn
jddunn deleted the fix/gateway-resolves-its-chain branch October 12, 2026 14:50
github-actions Bot pushed a commit that referenced this pull request Oct 12, 2026
## [0.13.67](v0.13.66...v0.13.67) (2026-10-12)

### fix

* **agency:** the post-approval check reads the approved input, and output guards receive tool-call chunks (#340) ([a81d09d](a81d09d))
* **api:** send the routing keys of customModelParams with the planning call (#329) ([7271cc3](7271cc3))
* **gateway:** the completion gateway resolves and walks its chain as generateText and streamText do (#341) ([b4c8280](b4c8280))
jddunn added a commit that referenced this pull request Oct 12, 2026
…he walkers' tier, and its skips wait for a walk (#346)

Folds of the cold read of #341 (one P1, five P2s, each verified against the code):

- **P1.** `agent({ runtime: 'gmi' })` wraps the completion gateway when the agent sets `onFallback` (`gatewayFor` in `src/api/gmi.ts`), and the wrapper passed only the route and the failed hop to `resolve()`. The error was dropped, so a refusal was walked as an outage: the policy chain's Claude legs ran after it, and a refusing standing leg owed a refill. The wrapper forwards it.
- The gateway's chain read its tier from `route.policyTier` alone; it now uses `resolvePolicyTier` as the walkers do (route params, the call's own tier, the host policy's, the router's).
- The entries the chain's one-time resolution passes over are held on the first hop and reported when a walk starts, so a turn the first model answers traces nothing (the walkers log their skips only when they walk).
- `onFallback` receives the error the previous hop failed with, instead of a placeholder.
- Tests: the `gmi()` refusal case with `onFallback` set (`gmi-runtime.session.test.ts`); in `completionGateway.test.ts`, the refill test on a tagged chain (it fails on the parent: a standing leg that cannot start owes a refill, one that refuses does not), expectations computed from the walk's rule rather than from the live ladder's length, the host-policy tier, and `onFallback`'s error.
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.

Completion gateway: fallback hops are not resolved through resolveFallbackChain

1 participant