Repository navigation
feat: HTTP session events API (snapshots + SSE stream) - #371
Merged
Merged
Conversation
6 tasks done
huang195
force-pushed
the
feat/session-events-api
branch
from
May 5, 2026 21:54
a915e3e to
2ba43d4
Compare
huang195
added a commit
to huang195/kagenti-extensions
that referenced
this pull request
May 5, 2026
PR rossoctl#371 added MarshalJSON for SessionEvent and String() for Direction and SessionPhase so the wire format uses readable strings. It did not add the matching Unmarshal side — so an off-process Go consumer trying to decode the same payload back into a SessionEvent failed with "cannot unmarshal string into Go struct field". First surfaced while writing the abctl apiclient. Fixing it here rather than shipping a client-side mirror struct so every future Go consumer of the API gets round-trippable types from authlib. - Direction: add MarshalJSON + UnmarshalJSON (string <-> enum). - SessionPhase: same. - SessionEvent: extract the wire layout into a shared sessionEventWire struct; Marshal writes to it, Unmarshal reads from it. durationMs <-> time.Duration symmetry is explicit. Unknown direction/phase strings decode to the zero-value member without error, keeping downstream consumers tolerant of future enum additions. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Hai Huang <[email protected]>
recordInboundSession fell back to Store.ActiveSession() when the A2A
request had no contextId yet (first turn of a new conversation). After
a previous conversation had already rekeyed its bucket from "default"
to a real contextId, ActiveSession() returned that previous conversation's
bucket. The new conversation's request events then landed in the prior
session, contaminating it.
When the current conversation's response arrived with its own freshly
assigned contextId, rekeyInboundSession called Rekey("default", new-id) —
but "default" no longer existed (events went to the prior bucket
instead), so Rekey was a no-op. recordInboundResponseSession then
appended the final event to the new contextId, producing a
1-event orphan session.
Observed live as: four sessions of 45, 23, 23, and 1 events instead of
one session per conversation. abctl made it visible; the same bug
existed silently prior.
Fix: inbound events trust A2A.SessionID as-is. Empty means a new
conversation — bootstrap into DefaultSessionID so the rekey on the
response can cleanly migrate the bucket. Never fall back to
ActiveSession() for inbound events — that fallback is only sound for
outbound correlation. Extracted inboundSessionID() helper so the
request-phase and response-phase recorders share the same rule.
Regression test asserts the fix directly: seed ActiveSession with
"prev-ctx", record a fresh inbound request with empty SessionID,
assert it lands in DefaultSessionID and prev-ctx is untouched.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
Prep for externalizing the session store over HTTP. Two additions: - Subscribe() returns a *Subscription + cancel func. Internally holds a per-subscriber buffered channel (cap 64) and an atomic drop counter. Append publishes events non-blockingly via publishLocked; a full channel increments drops and discards the event. Append stays fast even with a stalled consumer. Close() fans out channel closes to every live subscriber so in-flight consumers unblock on shutdown, and closeOnce per subscriber keeps cancel + Close idempotent. - ListSessions() returns a []SessionSummary (id, createdAt, updatedAt, eventCount, active) sorted by UpdatedAt descending. No event payload is copied, so the list endpoint stays cheap even with large sessions. Unit tests cover receive after append, cancel stops delivery, slow consumer drops without blocking Append, fan-out to multiple subscribers, and Store.Close closing subscriber channels. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Hai Huang <[email protected]>
Prep for externalizing session events over HTTP. Three shapes change:
- Direction gets a String() method ("inbound"/"outbound"). Replaces
the duplicate directionName helper from session/store.go, which
now calls e.Direction.String() directly.
- SessionEvent gets a MarshalJSON that emits Direction and Phase as
strings (Go's default stringifies ints and time.Duration as
nanoseconds — both awkward for CLI consumption) and Duration as
durationMs.
- Every extension struct and session-level struct (MCPExtension,
A2AExtension, InferenceExtension, EventIdentity, EventError,
SessionView, etc.) gets lower-camel JSON tags with omitempty so
the wire format is consistent and compact.
Unit tests on the marshaler cover readable enums and omitempty.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
New package authlib/sessionapi exposes AuthBridge's in-memory session
store over HTTP. Intended for operators debugging the plugin pipeline
via kubectl port-forward, and for a future abctl TUI.
Endpoints:
- GET /v1/sessions — JSON list of active sessions
- GET /v1/sessions/{id} — JSON snapshot of one session's events (404 if missing)
- GET /v1/events — SSE stream of new events, optional ?session= filter
- GET /healthz — liveness
The SSE handler subscribes to the store, emits event:/id:/data:
frames for each incoming event, and sends a keep-alive comment every
30s (configurable per-Server via WithHeartbeatInterval so tests don't
hang). On disconnect the subscription is cancelled to free the
buffered channel. Accumulated drop counts from a slow client are
surfaced at WARN each heartbeat.
Trust model: no auth. Addr comes from ListenerConfig.SessionAPIAddr;
binds should only be reachable in-cluster or via port-forward,
never behind ingress.
httptest-based coverage: each endpoint, SSE framing, session filter,
heartbeat cadence, and 404 behavior.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
Final wiring for the session events HTTP server: - ListenerConfig.SessionAPIAddr string: new field, yaml:"session_api_addr". - ApplyPreset: default ":9094" across every mode. To disable, set session.enabled: false — main.go skips the API server whenever the session store itself is nil, so no separate API-only kill switch is needed in v1. - main.go: after startStatServer, construct sessionapi.New when SessionAPIAddr is non-empty and sessions is non-nil, spawn the serve goroutine with the standard ErrServerClosed pattern, call Shutdown during the graceful-shutdown block. - CLAUDE.md: bump the port-mapping table with :9093 (stats) and :9094 (session API), and add a Session Events API section with endpoint reference, trust-model note, and curl examples for port-forward usage. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Hai Huang <[email protected]>
Review feedback: the ?session= filter on /v1/events only fired when the event had an A2A extension, because A2A was the only struct that carried a session field. Outbound MCP and Inference events have no protocol-native session, so the filter's `event.A2A != nil` guard bailed and foreign-session events passed through. An operator filtering to one session would still see cross-session tool calls and LLM traffic mixed in. Make SessionEvent self-describing: - Add SessionEvent.SessionID. Stamped by Store.Append so every event knows its bucket, regardless of protocol. - Store.Rekey rewrites SessionID on all already-recorded events so snapshot reads and live stream agree after a "default" -> contextId rekey. - SSE handler filter simplifies to `event.SessionID != filter` and now works uniformly for A2A, MCP, Inference, and future protocols. Also addressed same-batch: - EventError.Message was missing a json tag, serializing as "Message" and breaking the lower-camel wire format. - Local id counter in handleStream dropped atomic.AddUint64 (it's function-local, no concurrent reader) for plain id++. - publishLocked gained a doc comment noting fan-out runs under the lock — fine for the 1-few-consumer debug load, flag for refactor if that assumption ever changes. New tests: Append stamps SessionID; Rekey rewrites all event IDs; SSE filter guards against regression on outbound MCP events. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Hai Huang <[email protected]>
Review feedback: preset default opens :9094 on every mode, so
upgrading authbridge silently starts a new network listener. The
trust model is documented in CLAUDE.md but the surface behavior is
surprising. Emit a WARN at startup naming the model:
session API listening - UNAUTHENTICATED; contains raw user
content; never expose via ingress
Cheap; gives operators a clear heads-up in pod logs. Matches the
stats-server precedent (:9093 is also all-interfaces by design).
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
huang195
added a commit
to huang195/kagenti-extensions
that referenced
this pull request
May 5, 2026
PR rossoctl#371 added MarshalJSON for SessionEvent and String() for Direction and SessionPhase so the wire format uses readable strings. It did not add the matching Unmarshal side — so an off-process Go consumer trying to decode the same payload back into a SessionEvent failed with "cannot unmarshal string into Go struct field". First surfaced while writing the abctl apiclient. Fixing it here rather than shipping a client-side mirror struct so every future Go consumer of the API gets round-trippable types from authlib. - Direction: add MarshalJSON + UnmarshalJSON (string <-> enum). - SessionPhase: same. - SessionEvent: extract the wire layout into a shared sessionEventWire struct; Marshal writes to it, Unmarshal reads from it. durationMs <-> time.Duration symmetry is explicit. Unknown direction/phase strings decode to the zero-value member without error, keeping downstream consumers tolerant of future enum additions. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Hai Huang <[email protected]>
huang195
force-pushed
the
feat/session-events-api
branch
from
May 5, 2026 21:58
2ba43d4 to
fb3d4de
Compare
esnible
approved these changes
May 5, 2026
huang195
added a commit
to huang195/kagenti-extensions
that referenced
this pull request
May 5, 2026
PR rossoctl#371 added MarshalJSON for SessionEvent and String() for Direction and SessionPhase so the wire format uses readable strings. It did not add the matching Unmarshal side — so an off-process Go consumer trying to decode the same payload back into a SessionEvent failed with "cannot unmarshal string into Go struct field". First surfaced while writing the abctl apiclient. Fixing it here rather than shipping a client-side mirror struct so every future Go consumer of the API gets round-trippable types from authlib. - Direction: add MarshalJSON + UnmarshalJSON (string <-> enum). - SessionPhase: same. - SessionEvent: extract the wire layout into a shared sessionEventWire struct; Marshal writes to it, Unmarshal reads from it. durationMs <-> time.Duration symmetry is explicit. Unknown direction/phase strings decode to the zero-value member without error, keeping downstream consumers tolerant of future enum additions. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Hai Huang <[email protected]>
3 of 9 tasks
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.
Summary
Adds an HTTP endpoint that externalizes AuthBridge's in-memory session store so operators can debug the plugin pipeline via
kubectl port-forwardand (in a follow-up PR) drive an interactive TUI.Three endpoints on a new port (
:9094by default):GET /v1/sessions- JSON list of active sessions with summariesGET /v1/sessions/{id}- JSON snapshot of a single session eventsGET /v1/events- SSE stream of new events, optional?session=filter, 30-second heartbeatWhat changes
session.StoreSubscribe() (*Subscription, func())registers a consumer that receives every appended event via a buffered channel (cap 64). Non-blocking fan-out inAppend; slow consumers drop events and increment a per-subscriber counter.Close()closes subscriber channels idempotently.ListSessions() []SessionSummaryreturns metadata-only summaries (id, createdAt, updatedAt, eventCount, active) for the list endpoint, sorted most-recent-first.Serialization (
pipeline/)Direction.String()replaces the localdirectionNamehelper.SessionEvent.MarshalJSONemitsdirection/phaseas strings anddurationMsinstead of raw nanoseconds.MCPExtension,A2AExtension,InferenceExtension,EventIdentity,EventError,SessionView, etc.) gets lower-cameljsontags +omitemptyfor consistent wire format.sessionapi/(new package)observe/statserver.goshape: constructorNew(addr, store, opts...),ListenAndServe,Shutdown. Useshttp.ServeMuxwith method-qualified routes.event:/id:/data:frames, sends heartbeat comments at the configured interval (WithHeartbeatIntervalfor tests), cancels subscription on client disconnect, logs WARN on accumulated drops.httptest-driven tests cover empty list, populated list, 404, JSON enum readability, SSE delivery + framing, heartbeat cadence, and?session=filtering.Wiring
ListenerConfig.SessionAPIAddr string- new field, defaults to:9094viaApplyPresetfor all three modes.main.gostarts the server whenSessionAPIAddr != ""ANDsessions != nil. To disable, setsession.enabled: false.authbridge/CLAUDE.mdupdated with a Session Events API section; port table now lists:9093(stats) and:9094(session API); includeskubectl port-forward+curlexamples.Trust model
No authentication. Bind only on in-cluster addresses, never behind ingress. Payloads may contain raw user messages, LLM completions, and tool results. Matches the existing stats endpoint trust model.
Test plan
Store.Subscribe(5 cases),SessionEvent.MarshalJSON(2 cases),Direction.String,sessionapi.Server(8 cases covering each endpoint, SSE framing, heartbeat, filter).curl http://localhost:9094/v1/sessionsis empty before any query, then lists the active session after.curl -N http://localhost:9094/v1/eventsstreamed 23 SSE frames during a "weather in new york" query, covering the full conversation: inbound request with user prompt, MCP handshake x2, tool call with city arg, two LLM calls with full completion text, inbound response withdurationMs=4697and the rekeyed contextId./v1/sessions/{id}returned 200 with 23 events;/v1/sessions/does-not-existreturned 404.Out of scope
abctlTUI - follow-up PR once this is merged.Assisted-By: Claude (Anthropic AI) [email protected]