Skip to content

fix(api): five defects from a cold read of the gmi() session runner - #165

Merged
jddunn merged 8 commits into
masterfrom
fix/gmi-session-review
Oct 8, 2026
Merged

jddunn merged 8 commits into
masterfrom
fix/gmi-session-review

Conversation

@jddunn

@jddunn jddunn commented Oct 8, 2026 •

Copy link
Copy Markdown
Member

Summary

A cold read of the gmi() session runner merged in #135 (src/api/runtime/gmiSession.ts, src/api/gmi.ts) found five places where a turn on the GMI path does less than the same turn through agent(). Each has an end-to-end case over stubbed provider classes that failed before its fix (run 37824347489, the tests alone: 7 failed, 9036 passed).

  1. The usage ledger is in step with the call. runGmiTurn started each ledger write and moved on, so send() returned before the row was on disk. With the ledger enabled, usage() reads the ledger alone, so a read right after a send missed the turn, and a process that exited once the call returned lost the row. The turn now waits for its ledger writes before it ends, as generateText writes its row before it returns. The wait sits in a try whose finally releases the turn lock.
  2. The usage observer hears a GMI turn. A host that meters spend through setGlobalLlmObserver heard nothing from this path. Each model call of a turn now fires one usage event beside its ledger row: a finished step with the provider, model and hop that served it, and an attempt that failed before any output and was billed, as an 'error' event. send() and generate() report under the generateText surface and stream() under streamText. Where generateText fires one event for a whole call, a GMI turn fires one per model call, as its ledger rows already were: each call of a turn can be served by another hop, so each is attributed to the provider that billed it, and the token totals are the same. Events carry no source: the path refuses a per-call source, as it refuses every per-call option outside its list.
  3. memoryProvider.observe runs on the provider. It was taken off the provider and called bare, so a provider built from a class lost this, the rejection was swallowed and nothing was recorded. An observe that threw outright failed a turn whose reply was already stored. It is now called on the provider, and a throw is warned about and left there.
  4. No user message is named after the session. A GMI names the turn's user message after the turn's user id and replays it under that name on a tool step and for multimodal input. On this path that id is the session id unless the caller named a user, and OpenAI answers HTTP 400 for a message name with a space or a slash in it (the pattern, as OpenAI's error states it). gmi()'s model-call hook now takes the name off user messages; tool results keep theirs.
  5. A turn's user message stays with its reply. When the session store refused a turn's first step (its pairing check fails for two tool calls under one id), the user message went with it and the later steps were stored alone. The message now goes with the first step the store keeps.

Linked issues

Follow-up to #135.

Type of change

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

How this was verified

CI on this pull request, nothing run locally. The first commit holds only the tests; its Test & Lint job (run 37824347489) failed in gmi-runtime.usage.test.ts (3 cases) and gmi-runtime.parity.test.ts (4 cases), each for the defect it names. The run on the head commit b8ebc01 (run 37825031126) is green: build, export check, lint, type check, and the full suite (725 files, 9058 tests passed, the seven new cases among them), with the batch-1 gate and the release dry run.

Migration notes

None for code. A host that registers a usage observer starts receiving events from agent({ runtime: 'gmi' }) and gmi() turns, one per model call.

Checklist

  • Tests cover the changed behavior.
  • Docs are updated. No published page describes these behaviours yet; the source comments are.
  • 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.

jddunn added 2 commits October 8, 2026 11:26
…rver, and three agent() behaviours hold

End-to-end cases over stubbed provider classes for what agent() gives a
caller and the GMI path has to keep:

- the usage ledger holds a turn by the time send() returns or a stream's
  text settles, so usage() read right after counts it;
- the process-wide usage observer hears each model call of a turn (a tool
  step, the answer, a billed attempt that failed before any output), under
  the surface the caller used;
- memoryProvider.observe runs on the provider, so a provider built from a
  class records the turn, and an observe that throws does not fail the turn;
- no user message is named after the session id;
- a step the session store refuses (two tool calls under one id) does not
  cost the turn its user message.
@coderabbitai

coderabbitai Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

  • Run on-demand review

This review includes 5 billable files and costs up to $1.25.

  • 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 25 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: 55bb1cfd-0a16-4e5a-9c0b-45b0ad308c08
📥 Commits

Reviewing files that changed from the base of the PR and between 833f2f7 and b8ebc01.

📒 Files selected for processing (5)
  • src/api/__tests__/gmi-runtime.parity.test.ts
  • src/api/__tests__/gmi-runtime.usage.test.ts
  • src/api/gmi.ts
  • src/api/runtime/gmiSession.ts
  • src/api/runtime/gmiTranscript.ts
  • Autopilot · 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 8, 2026

Copy link
Copy Markdown

Reviewer's Guide

This PR adds end-to-end regression tests for GMI parity and usage behavior, then updates the GMI session runner to await ledger persistence, report all model attempts, safely observe memory, omit invalid user-message names, and preserve user history when later step storage fails.

File-Level Changes

Change Details Files
Add end-to-end parity coverage for GMI session behavior.
  • Verify class-based memory providers retain method context and observer failures do not fail completed turns.
  • Verify session IDs are not propagated into provider user-message names.
  • Verify user history is preserved when a later tool step cannot be stored.
src/api/__tests__/gmi-runtime.parity.test.ts
Add end-to-end coverage for usage accounting across GMI turns.
  • Verify usage ledger rows are persisted before send and stream calls return.
  • Verify global usage observers receive tool-step, answer, streaming, and billed fallback-attempt events.
  • Verify ledger and aggregated usage include failed billed attempts and successful fallback usage.
src/api/__tests__/gmi-runtime.usage.test.ts
Fix the five GMI session-runner defects identified by the tests.
  • Await usage-ledger writes before completing a turn.
  • Emit global LLM usage events for every GMI model call, including billed failures and fallback attempts.
  • Invoke memory observation with the provider receiver and isolate observer errors after persistence.
  • Stop assigning the session/user ID to multimodal and subsequent-step user messages.
  • Persist the turn's user message independently when a later tool step is rejected by the session store.
src/api/runtime/gmiSession.ts
src/api/gmi.ts

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 added 6 commits October 8, 2026 11:27
…ssion store keeps

runGmiTurn gave the turn's user message to the turn's first step only.
When the store refused that step (its pairing check fails for a step whose
tool calls share one id, as OllamaProvider's streamed calls can), the user
message went with it, and the steps after it were stored alone: the
history showed an assistant reply with no message before it.

The message now stays with the turn until a step is kept, so the first
step the store takes carries it.
… a gmi() turn

runGmiTurn took observe off the provider and called it bare. A provider
built from a class reads `this` in observe, so the call threw inside the
method, the rejection was swallowed, and the provider recorded nothing.
An observe that threw outright (one that is not an async function) failed
the turn after its reply had been stored and its usage counted, so send()
rejected for a turn the history already held.

observe is now called on the provider, as agent() calls it, and a throw
is warned about and left there.
runGmiTurn started each usage ledger write and moved on. send() returned
before the row was on disk, so with the ledger enabled, where usage()
reads the ledger alone, usage() read right after a send missed the turn,
and a process that exited once the call returned lost the row.
generateText writes its row before it returns.

The turn now waits for its ledger writes before it ends. The wait sits
in a try whose finally releases the turn lock, so nothing thrown while a
turn is closing can leave the session's later turns waiting.
A host that meters model spend through setGlobalLlmObserver heard nothing
from a turn on the GMI path: generateText and streamText report each call
and each billed failed attempt to the observer, and runGmiTurn wrote the
usage ledger only.

Each model call of a turn now fires one usage event beside its ledger
row: a finished step with the provider, model and hop that served it, and
an attempt that failed before any output and was billed, as an 'error'
event. A folded turn (send, generate) reports under the generateText
surface and a streamed one under streamText, the surfaces the same calls
report under through agent(). A turn is metered call by call, as its
ledger rows are, so a tool loop or a fallback hop reports each request
with the provider that was billed for it.
A GMI names the turn's user message after the turn's user id and replays
it under that name on every model call after the turn's first (a tool
step) and for multimodal input. On the gmi() path that id is the session
id unless the caller named a user, so the request carried
`name: <session id>`. OpenAI checks a message name against a pattern and
answers HTTP 400 for one with a space or a slash in it, so a session id
such as 'support chat 1' failed the turn after its tool had run. agent()
names no message.

gmi()'s model-call hook now takes the name off user messages before the
request is sent; tool results keep theirs.
@jddunn
jddunn marked this pull request as ready for review October 8, 2026 18:42
@jddunn
jddunn requested a review from Victor-Evogor as a code owner October 8, 2026 18:42
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@sourcery-ai

sourcery-ai Bot commented Oct 8, 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 1 day and 11 hours by commenting @sourcery-ai review. Upgrade to get a review now.

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

Copy link
Copy Markdown

PR Summary by Qodo

Fix GMI session usage, memory, request names, and history

🐞 Bug fix 🧪 Tests 🕐 20-40 Minutes

Grey Divider

AI Description

• Persist GMI usage before turns finish and notify the global observer for each billed model call.
• Preserve memory observation, valid provider requests, and user-message history across rejected
 steps.
• Add end-to-end regressions using stubbed providers.
Diagram

graph TD
  Runner["GMI turn runner"] --> Hook["Model-call hook"]
  Runner --> Transcript["Transcript mapping"] --> Store[("Session store")]
  Runner --> Observer["Usage observer"]
  Runner --> Ledger[("Usage ledger")]
  Runner --> Memory["Memory provider"]
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Emit one aggregate usage event per turn
  • ➕ Simpler observer behavior and fewer events.
  • ➖ Loses attribution for tool-loop calls and billed attempts served by different fallback providers.

Recommendation: Keep per-model-call events alongside the existing per-call ledger rows: they preserve the provider and hop that incurred each charge. Awaiting ledger writes before completion also makes an immediate usage read consistent with the returned turn.

Files changed (5) +348 / -43

Bug fix (2) +154 / -37
gmi.tsRemove user-message names before GMI model calls +13/-0

Remove user-message names before GMI model calls

• The model-call hook strips names from user messages, including replayed messages, to prevent session identifiers from becoming invalid provider request names. Other message names remain unchanged.

src/api/gmi.ts

gmiSession.tsCorrect GMI turn metering, observation, and message retention +141/-37

Correct GMI turn metering, observation, and message retention

• Emits global observer events for finished calls and billed failed attempts, then awaits their ledger writes before ending the turn while ensuring the lock is released. Calls memory observation on its provider without failing the turn on a synchronous throw, and carries the user message forward until the store accepts a step.

src/api/runtime/gmiSession.ts

Tests (2) +187 / -0
gmi-runtime.parity.test.tsCover GMI session parity for memory, names, and history +80/-0

Cover GMI session parity for memory, names, and history

• Adds end-to-end cases confirming class-based memory observers retain their receiver, observation failures do not fail a stored reply, user messages reach providers without session-derived names, and rejected tool steps do not orphan the reply in history.

src/api/tests/gmi-runtime.parity.test.ts

gmi-runtime.usage.test.tsCover durable usage and per-call observer events +107/-0

Cover durable usage and per-call observer events

• Verifies ledger rows and usage totals immediately after sends and completed streams. Checks observer events for tool and answer steps, stream surfaces, and a billed failed attempt followed by a fallback.

src/api/tests/gmi-runtime.usage.test.ts

Documentation (1) +7 / -6
gmiTranscript.tsClarify when a step carries the turn's user message +7/-6

Clarify when a step carries the turn's user message

• Updates transcript conversion comments to reflect that the user message accompanies the first step accepted by the session store, rather than necessarily the first generated step.

src/api/runtime/gmiTranscript.ts

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

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0)

Grey Divider

Great, no issues found!

Qodo reviewed your code and found no material issues that require review

Grey Divider

Tip of the day
💡 Did you know, you can keep summaries lean with Findings visible per group, which tucks the rest behind a View link

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@jddunn
jddunn merged commit 5eec49c into master Oct 8, 2026
6 checks passed
github-actions Bot pushed a commit that referenced this pull request Oct 8, 2026
## [0.13.0](v0.12.24...v0.13.0) (2026-10-08)

### ⚠ BREAKING CHANGE

* **speech:** URL output (providerSpecificOptions.outputFormat 'url')
downloads only from hosts listed in audioUrlHosts, or in
MINIMAX_TTS_AUDIO_URL_HOSTS through SpeechRuntime; without one, synthesize()
throws instead of fetching. MiniMaxAsyncSpeechResponse.task_id is
number | string instead of string, and file_id is number | string instead
of number.

### feat

* **safety:** a persisted spend meter that processRequest reserves against before any provider call (#167) ([b9c2e91](b9c2e91))

### fix

* **api:** five defects from a cold read of the gmi() session runner (#165) ([5eec49c](5eec49c))
* **speech:** download MiniMax URL output only from allowed hosts, query async tasks with GET (#166) ([14b86bf](14b86bf))
@jddunn
jddunn deleted the fix/gmi-session-review branch October 10, 2026 18:59
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