Skip to content

agent: HTTP endpoints data plane - #4779

Merged
paulwe merged 54 commits into
masterfrom
theo/agent-endpoints
Oct 6, 2026
Merged

paulwe merged 54 commits into
masterfrom
theo/agent-endpoints

Conversation

@theomonnom

@theomonnom theomonnom commented Aug 20, 2026 •

Copy link
Copy Markdown
Member

OSS core for agent HTTP endpoints. Complete and testable on a single self-hosted livekit-server.

  • Front on the server mux at /agents/{agent_name}/{deployment}/{path}: exact web-framework (starlette) route matching (typed params incl. multi-segment path, FULL/PARTIAL 405, trailing-slash normalization during routing rather than 307 redirects), per-endpoint public access, typed 401/404/405/503, and the retry table.
  • Worker connection: one WebTransport (QUIC) session per worker. A control stream carries registration/status/GoAway (the same WorkerMessage/ServerMessage exchange the old /agent WebSocket used); each HTTP request is a fresh QUIC stream carrying one opaque HTTP/1.1 exchange, half-closed to signal request-complete. The worker serves it in-process (ASGI bridge); no user-facing listener.
  • Method-aware route matching for the cross-node layer: canonical path prefixes + method-qualified terminal keys (cfset).
  • Extension hooks: a pluggable Fallback hook + exported registry scope hooks let the cloud layer add multi-node presence and relay without forking the front.
  • Conformance worker (Go test infra) + acceptance suite: correctness gate (byte-exact large bodies, SSE), HOL, retry safety, truncation abort, no-local-listener.
  • Legacy WebSocket /agent control transport still supported for endpoint-less (job-dispatch) workers.
  • Auth middleware reads access_token from the query string only (form POST bodies must pass through untouched).

Depends on livekit/protocol#1728.

Serve worker-declared FastAPI routes at /agents/{deployment}/{path} without
any worker-side listener: workers dial a fixed pool of wires speaking
AgentHttp.Frame, the server opens multiplexed streams carrying one opaque
HTTP/1.1 exchange each (two-level credit flow control, prioritized write
scheduler, attach epoch fencing). The front does starlette-exact manifest
matching with per-endpoint public access, typed 401/404/405, a retry table,
and SSE/WebSocket passthrough; a pluggable fallback hook lets multi-node
deployments resolve misses elsewhere. Includes a conformance client, a
manual sidecar, and the acceptance suite.

The auth middleware now reads access_token from the query string only:
FormValue consumed the bodies of proxied url-encoded POSTs.
Behind a load balancer a data wire may reach a node other than the one
holding the worker's registration; the adopter lets that layer (cloud)
install a local satellite registration before the attach is retried locally.
…resh

A wire whose worker is registered but under a different epoch now returns
ErrWrongEpoch (not ErrAttachRejected); pool-full/closed stay ErrAttachRejected.
The attach adopter runs on unknown-worker OR wrong-epoch, so a satellite left
behind by a reconnected worker is refreshed by re-validating against the
registration holder instead of shadowing the new epoch until it is swept.
Order-independent fnv64a of the route set so a multi-node layer can tell
whether the nodes serving a deployment agree on the manifest (safe to route
without inspecting the path) or are mid rolling-deploy (fall back to a
path-aware resolve).
A multi-node layer can now replicate a node's route set and match request
paths against it locally, instead of a manifest digest. Drops the digest
helper added for that (superseded).
Shape-matches a request path against a set of route templates via canonical
typed-wildcard tokens and a left-to-right pruned walk: linear in path depth
(no 2^segments), type-aware (int/float/uuid/str/path), glob catch-alls, and a
PrefixIndex interface so the same walk runs over an exact map (local) or a
compact replicated backing (multi-node). Worker stays authoritative for the
exact convertor/method match.
- a path convertor anywhere in a template (non-terminal, or mixed with literal
  text in a segment) now canonicalizes to a terminal glob that spans slashes,
  instead of being dropped or narrowed to a single-segment str - the old
  behavior silently failed to match such routes (a false negative -> misroute).
- enforce MaxRouteDepth at ParseManifest (wires up RouteDepth), bounding the
  replicated filter's prefix count and the matcher's walk.
…-scoped attach

- worker selection uses power-of-two-choices over live in-flight streams
  (InflightStreams / SpareStreams) instead of weighted-random over a
  reported load; the conn pick stays least-loaded. In-flight is observed
  locally so it is correct for adopted wires, and the reported Load hook is
  dropped from the endpoint path.
- the front tags its own routing misses (X-Livekit-Endpoint-Miss) so a relay
  caller can distinguish them from a worker app's own 404/405 and retry past
  them across the remaining candidates.
- a data-wire attach is bound to the connecting grant's api key, so a leaked
  attach token cannot bind a conn to another project's worker.
- remove the dead scope-hook machinery (it only fed the removed bus resolve)
  and rename the request identity from "scope" to apiKey.
…st infra

- remove cmd/agent-endpoint-client: the Python SDK has landed, so the manual
  sidecar for non-SDK workers is no longer needed.
- move pkg/agent/endpoint/client to pkg/agent/endpoint/conformance (package
  conformance) so it reads as the test harness it is, not a product client
  SDK; only the acceptance suite drives it.
- reuse the 32KiB response-copy buffer and the response-head reader from
  sync.Pools; ~27% fewer bytes allocated per small request.
- reuse a per-conn marshal buffer in WriteFrame instead of allocating one per
  frame; ~19% fewer bytes on a 1MiB upload. Safe because stream.Write copies
  the payload and gorilla WriteMessage does not retain it.
- ReadFrame reads each frame into a reused per-conn buffer via NextReader
  instead of letting ReadMessage allocate one per frame; ~41% fewer bytes on a
  1MiB download. Safe: proto.Unmarshal copies the payload out and readLoop is
  the sole reader.
- the data wire's websocket read is bounded by its own max message size (a full
  frame + framing overhead), independent of the signalling message limit, so a
  peer cannot OOM the server with an oversized frame even when signalling limits
  are disabled. Drops the old coupling that clamped MaxFrameSize under the
  signalling limit.
…fers

Stream now implements io.ReaderFrom, so http.Request.Write's bufio.Writer
delegates the body to it and a large upload flows in MaxFrameSize frames instead
of ~4KiB ones - 16x fewer frames, marshals, scheduler cycles and websocket
messages. Large frame buffers (>= 16KiB) are drawn from a per-conn sync.Pool and
recycled by the scheduler after each write, so a big upload stops allocating a
buffer per frame; small/webhook bodies stay below the threshold and use a
right-sized make, so the average request is unaffected.

Measured on a 1MiB upload: -82% allocations, -66% latency, -17% bytes; a small
GET/POST is unchanged.
Replace the capsule mux / credit / attach-pool machinery with one WebTransport
(QUIC) session per worker: a control stream carries registration and status,
and each HTTP exchange rides its own QUIC stream (native mux, per-stream flow
control, half-close, and reset). Encode the HTTP method into the cross-node
route filter so candidate selection is method-aware. Keep the legacy WebSocket
control transport for backward compatibility.
Use endpoint.CurrentProtocol and a named SessionCloseOK instead of bare
literals, factor the repeated 503 and header-copy blocks into helpers, and drop
a few restating test comments and a redundant assertion. No behavior change.
@theomonnom
theomonnom marked this pull request as ready for review August 31, 2026 04:27
@theomonnom
theomonnom requested a review from a team as a code owner August 31, 2026 04:27

@devin-ai-integration devin-ai-integration Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Note

This report is out of date. Scroll down for Devin Review's latest report on this PR.

Devin Review found 6 potential issues.

3 flags not posted on this PR by your GitHub settings — view them in Devin Review. (Configure)

Devin Review

Comment thread pkg/service/agentservice.go Resolved
Comment thread pkg/service/agenthandler.go Outdated
return nil
}
reg := &endpoint.Registration{
WorkerID: w.ID,

@devin-ai-integration devin-ai-integration Bot Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Reconnects retain stale endpoint sessions

Each reconnect gets a new w.ID, so Register cannot supersede the prior session. Requests can select the stale session until teardown finishes.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment thread pkg/agent/endpoint/front.go Outdated
Comment on lines +245 to +246
case partial:
f.writeMiss(w, http.StatusMethodNotAllowed, MissMethodNotAllowed, "method not allowed")

@devin-ai-integration devin-ai-integration Bot Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Method errors omit allowed methods

A partial route match calls writeMiss without an Allow header. Clients receiving 405 cannot discover the endpoint's supported methods.

Learn more

In pkg/agent/endpoint/front.go, the partial-match branch emits HTTP 405 without the required Allow response header. Preserve or aggregate the methods for path-matching routes across eligible registrations, respecting public/private filtering, and set a deduplicated Allow header before writing the 405 response.

Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Comment thread pkg/agent/endpoint/front.go Outdated
Comment on lines +536 to +541
func copyResponseHeaders(dst http.Header, resp *http.Response) {
addHeaders(dst, resp.Header)
removeHopByHopHeaders(dst)
if resp.ContentLength >= 0 && dst.Get("Content-Length") == "" {
dst.Set("Content-Length", strconv.FormatInt(resp.ContentLength, 10))
}

@devin-ai-integration devin-ai-integration Bot Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 HTTP response trailers disappear

copyResponseHeaders removes the trailer declaration, and bridge never forwards trailer values. Proxied responses lose checksums and streaming metadata.

Learn more

In pkg/agent/endpoint/front.go, preserve end-to-end HTTP response trailers. Before WriteHeader, announce the trailer names from resp.Trailer instead of stripping their declaration as hop-by-hop metadata. After the response body reaches EOF and http.ReadResponse has populated the values, copy those values to the client ResponseWriter using Go's trailer forwarding conventions. Keep genuinely hop-by-hop headers filtered.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment thread pkg/service/server.go Resolved
Comment thread pkg/service/server.go Resolved
… 307

A slash mismatch (e.g. /hook/ for a route registered as /hook) is now rewritten
to the registered form and served directly, rather than 307-redirected. Webhook
clients often don't follow redirects, and a redirect from the final routing hop
resends the body and pays the whole routing path twice. Exact form is matched
first, so a route registered with a trailing slash is served as-is.
Route presence like a reverse proxy keyed on (project, agent_name, deployment):
any of a deployment's workers is a candidate and the worker's own router returns
the real status (a 404 for a path it doesn't serve during a rolling deploy is
returned, not re-relayed). This removes the whole per-node route-advertisement
path: the cuckoo route filter and matcher (routematch.go), the miss-tagging /
retry-past-miss machinery, and the route-depth cap that only existed to bound
the filter. Text routing is now the same shape as voice job dispatch.
devin-ai-integration[bot]

This comment was marked as resolved.

theomonnom and others added 4 commits September 3, 2026 00:54
…st the fallback flow)

Remove the write-only Registration.Endpoints field (matching goes through
Manifest; the multi-node layer no longer replicates the raw route set). Add
Front-level fallback tests (fires with the resolved identity, declined -> 404
with a local worker or 503 without), and fix two stale comments.
# Conflicts:
#	go.mod
#	go.sum
#	pkg/agent/worker.go
Replace the protobuf frame layer on exchange streams with a length-prefixed
StreamPreamble followed by opaque HTTP/1.1 bytes. QUIC already provides the
multiplexing and per-stream flow control, so the frame layer only re-encoded a
message both peers can already parse, and every SDK had to re-materialize HTTP
from it.

The front serializes a canonical request head from its own parsed
*http.Request and never forwards the client's bytes, which is what keeps
request smuggling out of the worker. Responses are read with
http.ReadResponse, so informational heads need no httptrace hook and the
conformance worker loses its HTTP reconstruction entirely.

Completion splits by outcome: a body ends by its own framing, a failure after
bytes have flowed travels in x-lk-completion / x-lk-error trailers, and a
failure before any byte resets the stream with an HttpStreamResetCode. REFUSED
stays distinct as the retry-safety signal, and the retry/idempotence rules are
unchanged.

The x-lk- prefix is reserved for this signalling: it is stripped from
client-supplied request headers so a caller cannot forge an outcome, and from
responses so it never reaches the end client. Exchange-stream targets are
split from the escaped path so a percent-encoded '?' or '/' cannot change
which resource the worker routes to.

Per-request state moves to attempt.go so the Front and attempt lifecycles stop
interleaving; the remaining files are grouped type-first with free helpers
last. Those moves are ordering only.
Picks up livekit/protocol 134fb913, which replaces the HTTP framing messages
with StreamPreamble and renumbers HttpStreamResetCode. The previous pin
predates AgentHttp entirely, so the endpoint packages only built through the
local go.work.

@devin-ai-integration devin-ai-integration Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Note

This report is out of date. Scroll down for Devin Review's latest report on this PR.

Devin Review found 6 new potential issues.

4 flags not posted on this PR by your GitHub settings — view them in Devin Review. (Configure)

Devin Review

Comment thread pkg/agent/endpoint/attempt.go Resolved
Comment thread pkg/agent/endpoint/front.go Resolved
Comment on lines +209 to +212
for i := 0; ; i++ {
if i > maxInformationalHeads {
return nil, errTooManyInformational
}

@devin-ai-integration devin-ai-integration Bot Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Ninth informational response passes limit

After eight informational responses, readResponse accepts a ninth because its guard uses i > maxInformationalHeads. The configured cap is exceeded.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment thread pkg/service/agentservice.go Resolved
Comment thread pkg/agent/endpoint/attempt.go Resolved
Comment thread pkg/service/agentwebtransport.go Resolved
The front gated non-public routes on a bool that was true for any valid token
in the project, so a roomJoin token minted for an end user reached every
non-public endpoint the project's agents expose.

Replace the resolver's (apiKey, authenticated) pair with an Access value and
give it the agent and deployment from the URL, so the scope rules stay with
the grant in protocol/auth and this package consumes only the verdict.
Credentialed now separates a caller with no credential from one whose
credential lacks the grant: the first is challenged with 401, the second gets
403 and no WWW-Authenticate, since a retry cannot succeed.

A denied request still reaches the fallback. Another node's worker may declare
the same path public, and that node is the authority.
paulwe and others added 5 commits September 15, 2026 00:31
handleConnection writes the register response from inside HandshakeAgentWorker
and installs the worker's routes after it returns, so a worker learns it is
registered a moment before the node can route to it. The conformance worker's
WaitRegistered unblocks on that response and startWorker returned straight
into the first request, which on a loaded runner arrived while the registry
was still empty and came back 503. TestAgentEndpointsStatusMapping saw that as
503 for the first few mapped statuses, TestAgentEndpointsHOL as an unexpected
EOF, reading 1024 bytes out of a short error body.

The stack keeps the registry it builds and startNamedWorker waits for the
worker's registration to appear in it, which is the condition the requests
actually depend on. TestAgentEndpointsRetrySafety builds its unreachable
worker by hand and waits the same way. The HOL test asserts its status before
reading the body, so a 503 there reports as a status mismatch rather than a
truncated read.

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Workers are keyed by deployment alongside agent name, namespace and job type.
The registered and last-deregistered lines named every part of that key except
the deployment.
Manifest matching runs a compiled regex per route over a linear scan, once per
candidate registration, on the serving path. At the 256-route cap that is up to
256 RE2 executions per replica per request.

The router compiles a manifest into a compressed trie instead. Starlette
selects the first route declared that matches, so the trie cannot resolve
static before wildcard the way net/http's does: every node carries the lowest
route index in its subtree, the walk tracks the lowest full match found and
prunes any subtree that cannot improve on it, and inserting in declaration
order leaves edges and leaves sorted by that index with no sort pass.

Params are not segment-aligned - starlette allows /f/{name}.{ext}, a {p:path}
anywhere, and a float whose fraction backtracks - so the walk must search. An
edge is single when nothing below it can start with a byte its own convertor
could have consumed, which is a property of the target node and so is settled
at build time; a single edge takes its greedy run and descends once. Templates
whose params are segment-aligned are entirely single and never search. What
remains is bounded by a step budget, and exhausting it returns ResultOverBudget
rather than a route the cut-short search cannot vouch for.

Templates parse without regexp. Scanning the grammar by hand keeps a brace that
opens nothing well-formed as an ordinary literal, which is what starlette's
finditer does. Anchoring is `\n?$` rather than `$`: python's '$' matches before
one trailing newline where Go's does not, and [^/] accepts a newline where .
refuses one, so the two convertors diverge in opposite directions on a decoded
%0A.

The regex implementation moves into the tests as an oracle, carrying its own
parser so it references the hand-rolled scanner as well as the trie.
FuzzMatchAgainstOracle generates a table and a request and asserts the two
agree on both the winning template and the result. Matching allocates nothing,
asserted by AllocsPerRun on hit, 405, miss and on the searching path.

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
ParseManifest builds a router.Router rather than a slice of compiled templates,
Manifest aliases it, and Route keeps the template and the public flag the front
reads. Declared methods become a mask at build time, so a method no route could
declare masks to 0 and matches nothing, as an undeclared one already did.

Three behavior changes ride along.

Templates anchor as `\n?$`. A manifest declaring private /files/{p:path} before
public /files/{p} routed GET /files/x%0A to the public route here and to the
private one on the worker, because the path convertor refuses a newline where
str accepts it. The access gate reads the public flag of the route the front
picked, so it opened on a route starlette would not have selected.

slashAlternatePaths derives the escaped form from the transform it applied
rather than from the result's suffix. A request path of // trimmed to /, the
caller saw a trailing slash on that result, took the append branch, and handed
the worker a request line of /// against a decoded path of /.

The decoded path is capped at MaxPathLength, answering 414 above it. Matching
runs before anything sizes the request head, so net/http's own limit was the
only bound on what the matcher was handed.

A table too ambiguous to decide now dispatches rather than 404s: the worker's
own router still knows, and the preamble carries no route for it to be told
about. Nothing here knows whether that route is public, so the request needs a
grant. Dispatch keys on the match set, since a candidate can now join it
without resolving a route.

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Router implements zapcore.ObjectMarshaler, so registration logs the table's
size and the templates whose shape forces the matcher to search under one key
rather than assembling fields at the call site. Which templates those are is
settled when the manifest is parsed, so it is worth reporting before any
request is served; what a single match cost belongs to that request instead.

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
devin-ai-integration[bot]

This comment was marked as resolved.

paulwe and others added 4 commits September 16, 2026 07:26
Canonical renders a template as its literals and convertor kinds, so two
templates the trie cannot tell apart share a key. Param names reach the trie
only as a kind, so /x/{a} and /x/{b} accept the same paths; anything keying
routes by the declared spelling splits them apart. Literals are length-prefixed
because a brace that opens no well-formed param is literal text: /x/{:str}
matches itself and must not collide with /x/{a}.

ambiguousTemplate becomes Template.Ambiguous. It reads only the template's own
elements, so it answers for a manifest that was validated but never compiled
into a table of its own.

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
A deployment owns its route table. A route is one template shape and one method
together with the workers that declared it; registration takes the union of the
table and the arriving worker's manifest, deregistration retracts the worker and
drops the routes nothing is left declaring. Manifest stops being a compiled
router and becomes the ordered list a worker declared, so a fleet holds one
table rather than one per replica, and a request resolves in a single walk.

A mixed fleet is the point. Matching each worker's own table in turn already
served heterogeneous methods, but the route the front reported was the first
candidate's while the worker it dispatched to was any of them, and partial and
denied were accumulated across workers whose manifests disagreed. Both become
properties of one table, so the status a request gets and the template the
worker is told are decided together.

Merge order is the lowest position a route holds in any declaring manifest, tied
by shape then method. A fleet declaring one manifest reproduces that manifest's
order, and the result reads off the current set of manifests, so nodes holding
the same fleet agree. This does not preserve any one worker's internal order: a
worker can be handed a request the merged table resolved to a public route while
its own table routes that path to a private one. Merging the declaration chains
in order would hold the property and is not done here;
TestRouteTableMergeOrderInversion carries the case.

Routes are keyed by shape, so /x/{a} and /x/{b} are one route and a renamed path
param does not halve the fleet serving it. Each worker keeps the spelling it
declared, and the preamble carries that, since it is re-serialized per attempt.

The tree holds routes by pointer and is rebuilt only when the route set or its
order moves, so a worker joining or leaving an existing route swaps nothing. A
supersede runs the removal and the addition as one transaction: an unchanged
manifest would otherwise empty every route, drop it, and build a new one under
the same key, leaving the published tree naming routes nothing can reach and no
change to the key set to show for it. A reconnect can also land on a different
agent name or deployment, so the retiring epoch is retracted from its own table.

Ambiguity is now a property of the merged tree, and one worker's template shape
can carry the whole deployment's matcher over its step budget, which leaves no
route decided and so no public flag to clear an ungranted request.

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
The registry was doing three jobs at once: fencing worker epochs by id,
listing a deployment's candidates, and holding its merged route table. The
last two are per-deployment state, so it keyed them on
(api key, agent name, deployment) and grew a tenancy concept that only an
embedder can actually define. Cloud has to lie to it, passing a project id
in a field named APIKey.

Split them. Scope is one deployment's serving state and stores no identity
at all; whoever embeds the package keys a map of scopes however its own
tenancy works, and hands the front a resolved one. Registry keeps only the
worker-id fence, which is genuinely node-wide: worker ids are server-issued,
so an epoch is superseded wherever it was scoped.

The front loses its registry, its SingleKeyFallback and FallbackRequest: the
resolver now returns the scope and a fallback already curried on the
deployment, plus an ok that carries the 401-vs-503 split the empty api key
used to encode. routeTable drops its key and takes the scope's logger, so
identity is curried in rather than stored.

pkg/service takes ownership of the "api key is the tenant" rule, which is
true there and nowhere else, and of releasing a scope once nothing holds it.
Behavior is unchanged, including serving public routes to an unauthenticated
caller when one configured key or one attached tenant makes the key
unambiguous.
ListenWebTransport returned a stop closure, so every caller had to park it
next to the server it belonged to. In cloud that meant a second field on the
node base, written at start and read at stop, for one listener.

WebTransportServer embeds webtransport.Server and owns the sockets and
accept loops, so Listen and Shutdown are methods and the shape matches
http.Server. Shutdown takes a context: it stops accepting, sends GOAWAY, and
closes whatever has not drained by the deadline, where the closure closed
everything at once with no deadline of its own. It is safe on a server that
never listened, which is what lets a holder key teardown off the field alone.

The embedded Close still releases sessions without releasing the sockets;
that is what the type comment warns about.

@devin-ai-integration devin-ai-integration Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Note

Newer findings are available below. Devin Review posted a newer report on this PR, in addition to the findings presented here.

Devin Review found 1 new potential issue.

7 flags not posted on this PR by your GitHub settings — view them in Devin Review. (Configure)

Devin Review

Comment on lines +204 to +211
slices.SortFunc(ordered, func(a, b *Route) int {
if c := cmp.Compare(a.ord, b.ord); c != 0 {
return c
}
if c := cmp.Compare(a.key.canonical, b.key.canonical); c != 0 {
return c
}
return cmp.Compare(a.key.method, b.key.method)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟥 Route merging bypasses private endpoint access

Overlapping worker manifests can make the merged table select a public route. It can then dispatch anonymous requests to a worker selecting a private route.

Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

staticcheck QF1001 flagged the negated disjunction in scanIdent, which was
failing the lint gate and so keeping the test job from running at all. The
positive helper reads better than the De Morgan form and lets the continue
condition drop its own '_' case.
init() handed the logger &config.DefaultConfig.Logging, so the leveler's
mutex lived inside the global that NewConfig yaml-marshals. Marshalling
reflectively copies the whole struct, mutex included, which raced the
component-level lookups pion makes from its own goroutines and failed
TestPreferMediaCodecForPublisher under -race.

The values are the same; only the storage is now test-local. The integration
helper aliased the same global and gets the same treatment.
The token comes from RawQuery so the body reaches a proxied agent endpoint
intact. That only holds as long as nobody reaches for FormValue, which is
the obvious way to read a param and the one that drains the body, so the
comment names it.
# Conflicts:
#	go.mod
#	go.sum
#	pkg/rtc/room_test.go
#	test/integration_helpers.go
An exchange stream already carries opaque HTTP/1.1, so a WebSocket is an
ordinary GET route: the front forwards an HTTP/1.1 Upgrade: websocket
handshake, the worker's HTTP stack decides, and on a 101 the front hijacks
the client connection and splices it onto the stream. No protocol change.

- Only HTTP/1.x GET with Connection: upgrade and Upgrade: websocket (and no
  body) is an upgrade; every other Upgrade token is still stripped. A 101 is
  accepted only for such a request and only with Upgrade: websocket;
  anything else stays a protocol error.
- A non-101 answer to an upgrade is an ordinary response; the stream then
  ends with a FIN rather than a reset.
- Retries are unchanged until the 101; after it the attempt is committed.
- Each worker takes at most MaxTunnelsPerWorker tunnels (default half its
  session's MaxStreams) so WebSockets cannot starve its HTTP routes; an
  upgrade no worker can take falls to the fallback, then 503.
- Drain: a tunnel outlives its worker starting to drain by
  TunnelDrainTimeout (default 30s), and Front.Drain closes tunnels once its
  context is done. Both close with a 1001 frame when the client-bound side
  is between frames, abruptly otherwise. The server drains tunnels while
  participants leave, since http.Server.Shutdown cannot see them.
- access_token is dropped from the target and a LiveKit bearer token from
  Authorization for every request: the worker gets identity from the
  preamble, and the token must not reach application code.
- Full duplex: enable it before the first flush, so an HTTP/1 client can
  keep streaming its body while the response streams back.

Config: agents.endpoints.max_tunnels, agents.endpoints.tunnel_drain_timeout.
The agent chain's CORS middleware writes Access-Control-* and Vary before
the front runs. A worker's head was added on top, duplicating
Access-Control-Allow-Origin, and the clear after a 1xx head dropped the
middleware's headers from the final response.

- A worker's Access-Control-* and Vary values replace the middleware's;
  other headers are still added (MergeWorkerHeaders).
- Headers set before the front ran are restored after each 1xx head.
- Preflights stay with the middleware; a plain OPTIONS still reaches a
  declared route. NewAgentEndpointCORS holds the agent chain's CORS
  middleware so other chains can share it.
A worker registering over WebSocket has no data plane, yet the handshake
negotiated endpoint settings, telling it its routes were live while every
request 503'd. Negotiate only when a WebTransport session exists, per the
endpoint_settings contract, and keep the worker registered for jobs.

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Devin Review found 1 new potential issue.

7 flags not posted on this PR by your GitHub settings — view them in Devin Review. (Configure)

Devin Review

Comment on lines +393 to +395
if k == "Vary" || strings.HasPrefix(k, "Access-Control-") {
// dst's slices may be shared by middleware and must not be written through
dst[k] = slices.Clone(vs)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Cross-origin responses lose Origin variance

When a worker sets Vary without CORS headers, MergeWorkerHeaders removes the middleware's Origin variance. Cached responses retain origin-specific Access-Control-Allow-Origin, so browsers reject legitimate requests from other origins.

Learn more

The agent endpoint middleware reflects the request Origin into Access-Control-Allow-Origin and adds Vary: Origin. When a worker supplies Vary but no Access-Control-Allow-Origin, this replacement leaves the reflected header in place while dropping Origin from Vary. A shared cache can then reuse that response for a different origin. The browser rejects the cached response because its allowed origin names the first caller.

Example: A worker responds with Vary: Accept-Encoding and no CORS headers. A request from https://one.example is cached with Access-Control-Allow-Origin: https://one.example but no Vary: Origin. The cache serves it to https://two.example, whose browser blocks the response.

Recommended fix: Preserve the middleware's Origin variance when its origin-dependent CORS headers survive the merge. Replace it only when the worker also overrides the corresponding CORS headers with a response that no longer depends on the middleware's reflected Origin.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

@paulwe
paulwe merged commit c264da5 into master Oct 6, 2026
3 checks passed
@paulwe
paulwe deleted the theo/agent-endpoints branch October 6, 2026 03:56
eleboucher pushed a commit to eleboucher/homelab that referenced this pull request Oct 7, 2026
…7 ➔ v1.13.8) (#2275)

This PR contains the following updates:

| Package | Update | Change |
|---|---|---|
| [docker.io/livekit/livekit-server](https://github.com/livekit/livekit) | patch | `v1.13.7` → `v1.13.8` |

---

### Release Notes

<details>
<summary>livekit/livekit (docker.io/livekit/livekit-server)</summary>

### [`v1.13.8`](https://github.com/livekit/livekit/releases/tag/v1.13.8)

[Compare Source](livekit/livekit@v1.13.7...v1.13.8)

##### Added

- agent: HTTP endpoints data plane ([#&#8203;4779](livekit/livekit#4779))
- use sender report pass through setting to forward abs-capture-time verbatim ([#&#8203;4812](livekit/livekit#4812))
- Add sdk lable to session start time and participant join ([#&#8203;4885](livekit/livekit#4885))
- Add a local participant method to get recently disconnected ([#&#8203;4911](livekit/livekit#4911))
- service: start room composite egress configured in a room preset ([#&#8203;4926](livekit/livekit#4926))

##### Changed

- Update github workflows ([#&#8203;4446](livekit/livekit#4446))
- Reduce descriptor marshal allocations on Go 1.26.4/linux-amd64 ([#&#8203;4681](livekit/livekit#4681))
- config: reject unknown send\_side\_bwe\_pacer, warn on unwired fallback ([#&#8203;4804](livekit/livekit#4804))
- Update github.com/livekit/protocol digest to [`a879e94`](livekit/livekit@a879e94) ([#&#8203;4864](livekit/livekit#4864))
- Update module github.com/gotesttools/gotestfmt/v2 to v2.5.0 ([#&#8203;4865](livekit/livekit#4865))
- Update module github.com/urfave/cli/v3 to v3.11.0 ([#&#8203;4867](livekit/livekit#4867))
- Update module golang.org/x/mod to v0.41.0 ([#&#8203;4868](livekit/livekit#4868))
- sfu: return VP8 munged header by value to avoid per-packet allocation ([#&#8203;4871](livekit/livekit#4871))
- sfu: patch pacer header extensions without per-packet allocation ([#&#8203;4872](livekit/livekit#4872))
- Update pion/sdp to get lesser SDP retention ([#&#8203;4873](livekit/livekit#4873))
- sfu: skip pacer allocation assertion under the race detector ([#&#8203;4874](livekit/livekit#4874))
- sfu: broadcast RTP to down tracks without per-packet allocations ([#&#8203;4875](livekit/livekit#4875))
- Track action versions and stop quarantining our own actions ([#&#8203;4877](livekit/livekit#4877))
- test: fix two data races in the test suites ([#&#8203;4878](livekit/livekit#4878))
- Bump go.opentelemetry.io/otel/sdk ([#&#8203;4879](livekit/livekit#4879))
- deps: update psrpc to v0.8.0 ([#&#8203;4882](livekit/livekit#4882))
- Update module github.com/moby/moby/client to v0.6.0 ([#&#8203;4883](livekit/livekit#4883))
- Update module golang.org/x/sync to v0.23.0 ([#&#8203;4884](livekit/livekit#4884))
- Propagate SIP\_TRUNK\_FAILURE ([#&#8203;4890](livekit/livekit#4890))
- ccutils: use millisecond resolution for probe interval backoff ([#&#8203;4891](livekit/livekit#4891))
- Increase receiver loadbalance threshold when batch io enabled ([#&#8203;4899](livekit/livekit#4899))
- rtc: parse each remote offer once per negotiation ([#&#8203;4904](livekit/livekit#4904))
- Bump protocol ([#&#8203;4909](livekit/livekit#4909))
- rtc: split EndSession out of MoveToRoom ([#&#8203;4917](livekit/livekit#4917))
- telemetry: drop the stats worker re-key path ([#&#8203;4918](livekit/livekit#4918))
- sfu: report forwarding latency as p90 instead of the mean ([#&#8203;4920](livekit/livekit#4920))
- rtc: accept ICE Completed in ICE-restart connect assertions ([#&#8203;4921](livekit/livekit#4921))
- rtc: measure data blob keys by their content, not their text form ([#&#8203;4923](livekit/livekit#4923))
- Remove deprecatred way of setting prometheus from the config file ([#&#8203;4928](livekit/livekit#4928))
- test: give mock participants a connection quality, close test rooms ([#&#8203;4933](livekit/livekit#4933))
- update warp dep ([#&#8203;4943](livekit/livekit#4943))

##### Fixed

- Do not add down tracks after receiver close ([#&#8203;4857](livekit/livekit#4857))
- Do not request media sections for transceivers that cannot send ([#&#8203;4892](livekit/livekit#4892))
- Deregister agent job when the server terminates it ([#&#8203;4893](livekit/livekit#4893))
- sfu: don't hold bindLock across the blank-frame flush in CloseWithFlush ([#&#8203;4895](livekit/livekit#4895))
- dynacast: re-send subscribed qualities after every publisher answer ([#&#8203;4907](livekit/livekit#4907))
- agent: release JobTerminate handler when job ends before registration ([#&#8203;4908](livekit/livekit#4908))
- Report disconnected for older disconnected participants. ([#&#8203;4910](livekit/livekit#4910))
- rtc: record a room's departure when the participant leaves it ([#&#8203;4913](livekit/livekit#4913))
- update deps to fix warp issue ([#&#8203;4916](livekit/livekit#4916))
- sfu: fix data stats active window bitrate and duration units ([#&#8203;4922](livekit/livekit#4922))
- fix: reject instead of drop for no dispatch rule ([#&#8203;4927](livekit/livekit#4927))
- fix: skip RTX/FEC when picking a fallback video codec ([#&#8203;4930](livekit/livekit#4930))
- fix: do not read invalid delta ([#&#8203;4935](livekit/livekit#4935))
- fix: use the fast debounce for the first negotiation ([#&#8203;4936](livekit/livekit#4936))
- fix: skip DTLS HelloVerifyRequest ([#&#8203;4937](livekit/livekit#4937))
- config: parse generated duration flags as durations ([#&#8203;4939](livekit/livekit#4939))
- fix: use the most common recent packet rate in connection quality ([#&#8203;4940](livekit/livekit#4940))
- fix: copy RED history packets instead of keeping pointers ([#&#8203;4941](livekit/livekit#4941))
- fix: keep one subscription when first subscribes race ([#&#8203;4944](livekit/livekit#4944))
- bump protocol to get unlock on no key fix ([#&#8203;4945](livekit/livekit#4945))
- fix: count leftover upstream loss after RTX repairs ([#&#8203;4946](livekit/livekit#4946))
- fix: switch VP8 temporal layer up only at a layer sync frame ([#&#8203;4947](livekit/livekit#4947))
- fix: reconcile everything when the reconcile queue overflows ([#&#8203;4948](livekit/livekit#4948))
- fix: enable H.264 publish for desktop Linux Firefox ([#&#8203;4949](livekit/livekit#4949))

</details>

---

### Configuration

📅 **Schedule**: (UTC)

- Branch creation
  - At any time (no schedule defined)
- Automerge
  - At any time (no schedule defined)

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about these updates again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Mend Renovate CLI](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0NC4xMzMuMCIsInVwZGF0ZWRJblZlciI6IjQ0LjEzMy4wIiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6W119-->

Reviewed-on: https://git.erwanleboucher.dev/eleboucher/homelab/pulls/2275
hbjydev pushed a commit to hbjydev/phoebe that referenced this pull request Oct 13, 2026
…7 → v1.13.9) (#854)

This PR contains the following updates:

| Package | Update | Change |
|---|---|---|
| [docker.io/livekit/livekit-server](https://github.com/livekit/livekit) | patch | `v1.13.7` → `v1.13.9` |

---

### Release Notes

<details>
<summary>livekit/livekit (docker.io/livekit/livekit-server)</summary>

### [`v1.13.9`](https://github.com/livekit/livekit/releases/tag/v1.13.9)

[Compare Source](livekit/livekit@v1.13.8...v1.13.9)

Please note that release v1.13.8 introduced a behaviour change that caused egress start failures explained in [#&#8203;4955](livekit/livekit#4955). This release restores the behaviour to what it was in v1.13.7 and before.

##### Changed

- bump protocol and psrpc deps ([#&#8203;4958](livekit/livekit#4958))
- sfu/buffer: parse the dependency descriptor without allocating ([#&#8203;4953](livekit/livekit#4953))
- sfu/buffer: stop allocating per ingested packet ([#&#8203;4951](livekit/livekit#4951))

##### Fixed

- v1 path: check for subscriber_allow_pause presence before using it ([#&#8203;4957](livekit/livekit#4957))
- Cap forward-jump loops in SelectorDecisionCache ([#&#8203;4952](livekit/livekit#4952))

### [`v1.13.8`](https://github.com/livekit/livekit/releases/tag/v1.13.8)

[Compare Source](livekit/livekit@v1.13.7...v1.13.8)

##### Added

- agent: HTTP endpoints data plane ([#&#8203;4779](livekit/livekit#4779))
- use sender report pass through setting to forward abs-capture-time verbatim ([#&#8203;4812](livekit/livekit#4812))
- Add sdk lable to session start time and participant join ([#&#8203;4885](livekit/livekit#4885))
- Add a local participant method to get recently disconnected ([#&#8203;4911](livekit/livekit#4911))
- service: start room composite egress configured in a room preset ([#&#8203;4926](livekit/livekit#4926))

##### Changed

- Update github workflows ([#&#8203;4446](livekit/livekit#4446))
- Reduce descriptor marshal allocations on Go 1.26.4/linux-amd64 ([#&#8203;4681](livekit/livekit#4681))
- config: reject unknown send_side_bwe_pacer, warn on unwired fallback ([#&#8203;4804](livekit/livekit#4804))
- Update github.com/livekit/protocol digest to [`a879e94`](livekit/livekit@a879e94) ([#&#8203;4864](livekit/livekit#4864))
- Update module github.com/gotesttools/gotestfmt/v2 to v2.5.0 ([#&#8203;4865](livekit/livekit#4865))
- Update module github.com/urfave/cli/v3 to v3.11.0 ([#&#8203;4867](livekit/livekit#4867))
- Update module golang.org/x/mod to v0.41.0 ([#&#8203;4868](livekit/livekit#4868))
- sfu: return VP8 munged header by value to avoid per-packet allocation ([#&#8203;4871](livekit/livekit#4871))
- sfu: patch pacer header extensions without per-packet allocation ([#&#8203;4872](livekit/livekit#4872))
- Update pion/sdp to get lesser SDP retention ([#&#8203;4873](livekit/livekit#4873))
- sfu: skip pacer allocation assertion under the race detector ([#&#8203;4874](livekit/livekit#4874))
- sfu: broadcast RTP to down tracks without per-packet allocations ([#&#8203;4875](livekit/livekit#4875))
- Track action versions and stop quarantining our own actions ([#&#8203;4877](livekit/livekit#4877))
- test: fix two data races in the test suites ([#&#8203;4878](livekit/livekit#4878))
- Bump go.opentelemetry.io/otel/sdk ([#&#8203;4879](livekit/livekit#4879))
- deps: update psrpc to v0.8.0 ([#&#8203;4882](livekit/livekit#4882))
- Update module github.com/moby/moby/client to v0.6.0 ([#&#8203;4883](livekit/livekit#4883))
- Update module golang.org/x/sync to v0.23.0 ([#&#8203;4884](livekit/livekit#4884))
- Propagate SIP_TRUNK_FAILURE ([#&#8203;4890](livekit/livekit#4890))
- ccutils: use millisecond resolution for probe interval backoff ([#&#8203;4891](livekit/livekit#4891))
- Increase receiver loadbalance threshold when batch io enabled ([#&#8203;4899](livekit/livekit#4899))
- rtc: parse each remote offer once per negotiation ([#&#8203;4904](livekit/livekit#4904))
- Bump protocol ([#&#8203;4909](livekit/livekit#4909))
- rtc: split EndSession out of MoveToRoom ([#&#8203;4917](livekit/livekit#4917))
- telemetry: drop the stats worker re-key path ([#&#8203;4918](livekit/livekit#4918))
- sfu: report forwarding latency as p90 instead of the mean ([#&#8203;4920](livekit/livekit#4920))
- rtc: accept ICE Completed in ICE-restart connect assertions ([#&#8203;4921](livekit/livekit#4921))
- rtc: measure data blob keys by their content, not their text form ([#&#8203;4923](livekit/livekit#4923))
- Remove deprecatred way of setting prometheus from the config file ([#&#8203;4928](livekit/livekit#4928))
- test: give mock participants a connection quality, close test rooms ([#&#8203;4933](livekit/livekit#4933))
- update warp dep ([#&#8203;4943](livekit/livekit#4943))

##### Fixed

- Do not add down tracks after receiver close ([#&#8203;4857](livekit/livekit#4857))
- Do not request media sections for transceivers that cannot send ([#&#8203;4892](livekit/livekit#4892))
- Deregister agent job when the server terminates it ([#&#8203;4893](livekit/livekit#4893))
- sfu: don't hold bindLock across the blank-frame flush in CloseWithFlush ([#&#8203;4895](livekit/livekit#4895))
- dynacast: re-send subscribed qualities after every publisher answer ([#&#8203;4907](livekit/livekit#4907))
- agent: release JobTerminate handler when job ends before registration ([#&#8203;4908](livekit/livekit#4908))
- Report disconnected for older disconnected participants. ([#&#8203;4910](livekit/livekit#4910))
- rtc: record a room's departure when the participant leaves it ([#&#8203;4913](livekit/livekit#4913))
- update deps to fix warp issue ([#&#8203;4916](livekit/livekit#4916))
- sfu: fix data stats active window bitrate and duration units ([#&#8203;4922](livekit/livekit#4922))
- fix: reject instead of drop for no dispatch rule ([#&#8203;4927](livekit/livekit#4927))
- fix: skip RTX/FEC when picking a fallback video codec ([#&#8203;4930](livekit/livekit#4930))
- fix: do not read invalid delta ([#&#8203;4935](livekit/livekit#4935))
- fix: use the fast debounce for the first negotiation ([#&#8203;4936](livekit/livekit#4936))
- fix: skip DTLS HelloVerifyRequest ([#&#8203;4937](livekit/livekit#4937))
- config: parse generated duration flags as durations ([#&#8203;4939](livekit/livekit#4939))
- fix: use the most common recent packet rate in connection quality ([#&#8203;4940](livekit/livekit#4940))
- fix: copy RED history packets instead of keeping pointers ([#&#8203;4941](livekit/livekit#4941))
- fix: keep one subscription when first subscribes race ([#&#8203;4944](livekit/livekit#4944))
- bump protocol to get unlock on no key fix ([#&#8203;4945](livekit/livekit#4945))
- fix: count leftover upstream loss after RTX repairs ([#&#8203;4946](livekit/livekit#4946))
- fix: switch VP8 temporal layer up only at a layer sync frame ([#&#8203;4947](livekit/livekit#4947))
- fix: reconcile everything when the reconcile queue overflows ([#&#8203;4948](livekit/livekit#4948))
- fix: enable H.264 publish for desktop Linux Firefox ([#&#8203;4949](livekit/livekit#4949))

</details>

---

### Configuration

📅 **Schedule**: (in timezone Europe/London)

- Branch creation
  - At any time (no schedule defined)
- Automerge
  - At any time (no schedule defined)

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about these updates again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Mend Renovate CLI](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0NC4xNTUuMSIsInVwZGF0ZWRJblZlciI6IjQ0LjE1NS4xIiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6WyJyZW5vdmF0ZS9jb250YWluZXIiLCJ0eXBlL3BhdGNoIl19-->

Reviewed-on: https://git.hayden.moe/hayden/phoebe/pulls/854
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.

2 participants