Skip to content

feat: add AG-UI protocol server (serve ag-ui) - #5067

Open
deka wants to merge 14 commits into
docker:mainfrom
la-fabrique:feat/ag-ui-serve
Open

deka wants to merge 14 commits into
docker:mainfrom
la-fabrique:feat/ag-ui-serve

Conversation

@deka

@deka deka commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Closes #5066

Summary

Adds a first, deliberately small level of AG-UI support: docker agent serve ag-ui <agent-file>|<registry-ref> implements the server side of the protocol. POST /ag-ui takes a RunAgentInput and streams the run back as AG-UI events over SSE, so any AG-UI client SDK can drive a Docker Agent agent.

Step 1 is a plain chat: user text in; streamed assistant text, reasoning and server-side tool activity out. Human-in-the-loop, frontend tools, shared state and attachments are left to follow-up issues, as scoped in #5066.

What changed

  • cmd/root/agui.go: the serve ag-ui command, with the flag conventions of serve a2a (--agent, --listen (default 127.0.0.1:8084), --session-db, --safety, --auth-token, --cors-origin, --insecure-no-auth, runtime flags). A non-loopback listener requires --auth-token or --insecure-no-auth.
  • pkg/agui (new):
    • translator.go: a state machine that turns runtime events into AG-UI events. The runtime is unchanged.
    • input.go: RunAgentInput decoding and validation at the boundary.
    • server.go: endpoint, session mapping, per-thread run lock, SSE streaming, shutdown.
  • Event types and SSE encoding come from the Go SDK of ag-ui-protocol/ag-ui (sdks/community/go), so the wire format follows the specification. The SDK has no tagged release yet, so go.mod pins a pseudo-version.
  • pkg/httpsec: OriginMatcher.Match, which checks literals and patterns together.
  • Docs: docs/features/cli/index.md (command and flags), new guide docs/features/ag-ui/index.md, nav entry, and a note in the HTTP 413 troubleshooting section.

Behaviour

Session mapping

  • threadId is the session ID (origin ag-ui); an unknown threadId creates the session. A threadId that matches a session of another origin is rejected with 409 and that session is left untouched (same rule as A2A context IDs).
  • The server-side session is the source of truth. Only the user messages that end messages are appended; the rest of the client history (system, assistant, tool) is ignored.
  • A user message keeps its AG-UI id, so a message the thread already holds is not appended twice. A request with no new user message gets 400, unless the thread still ends on a user message (its last run failed before storing any output): resending the same messages then retries it.
  • One run at a time per thread: a second run gets 409. Closing the connection cancels the run and releases the thread.

Event mapping (as specified in the issue)

Runtime event AG-UI event
StreamStarted (root session) RUN_STARTED
StreamStopped (root session), normal stop RUN_FINISHED
StreamStopped (root session), any other stop RUN_ERROR (with code)
Error (root session) message and code of the RUN_ERROR if the run then stops; CUSTOM docker-agent.error before RUN_FINISHED if the run recovered
AgentChoice TEXT_MESSAGE_START / CONTENT / END, boundaries from the message ID
AgentChoiceReasoning REASONING_START / REASONING_MESSAGE_START / CONTENT / END / REASONING_END
PartialToolCall TOOL_CALL_START / TOOL_CALL_ARGS
ToolCall / ToolCallResponse TOOL_CALL_END / TOOL_CALL_RESULT
AgentSwitching STEP_STARTED / STEP_FINISHED (stepName = agent name)
TokenUsage, Warning, SessionTitle, ModelFallback CUSTOM (docker-agent.<type>)

The translator keeps the stream well formed for strict clients: RUN_STARTED always comes first, every started message, tool call and step is ended before RUN_FINISHED or RUN_ERROR, and nothing follows a terminal event. It also covers providers that do not stream tool calls, retracted tool calls (ToolCallsRetracted), unnamed tool calls, and text that resumes after a tool call.

Only the stop event ends the stream, because not every runtime error ends a run (a failed compaction reports one and the loop goes on). RUN_FINISHED is sent for a normal stop only. A run that was cut short ends with RUN_ERROR, whose code is canceled, the runtime error code, the stop reason (max_iterations, budget_exceeded, hook_blocked, loop_detected) or run_failed. A stream that closes without a stop event is reported as RUN_ERROR too.

Input validation

RunAgentInput is validated before any session change: invalid input gets 400 with {"error": "..."}, creates nothing, and a valid retry on the same threadId still works. A non-empty tools, state or resume is rejected with a clear error rather than ignored; non-text user content is rejected too. Bodies above 8 MiB get 413.

  • threadId starts with a letter or digit and contains only letters, digits, ., _ and -. It becomes the session ID, which names the tool-result directory the limit_large_tool_results hook removes at session end: .. resolved to the temp directory itself.
  • Message ids are bounded (256 bytes) and must be distinct among the trailing user messages. The content of the history that is discarded is not validated.

Security defaults

Same as serve a2a: restricted tool safety unless --safety says otherwise, bearer auth through httpsec.BearerAuth, CORS off unless --cors-origin is set (allowed headers: Authorization, Content-Type, Accept). The session is non-interactive: a tool call the policy does not allow is denied, and an elicitation is declined, because nobody can answer over AG-UI yet.

Two checks protect the default unauthenticated loopback listener from web pages the user visits:

  • Content-Type must be application/json (415 otherwise), so a cross-origin browser request needs a CORS preflight.
  • Without --auth-token, a loopback listener only accepts a loopback Host (httpsec.LoopbackHost, as in serve api), which stops DNS rebinding.

--cors-origin now honours literal origins when the value mixes literals and ~ patterns: echo ignores AllowOrigins once AllowOriginFunc is set, so the function uses the new httpsec.OriginMatcher.Match.

Shutdown

The server rejects new runs with 503, closes the connections, cancels the runs in progress (also when Serve fails on its own) and waits up to 10 seconds for them. A run that ignores its cancellation is abandoned so it cannot block the shutdown. Nothing is resumed at startup: the thread keeps what was stored and accepts a new run. The guide documents this.

Tests

  • Exact AG-UI event sequence on the wire (HTTP + SSE against a mock model) for: text only, reasoning, a tool call, an agent switch (transfer_task), an error, and a client disconnect (run canceled, thread released, next run accepted).
  • Session mapping on the SQLite store: server-side history wins over a forged client history, resent messages are not duplicated, retry after a failed run and after a run cut off before any answer, thread resumed after a restart using IDs created before it, collision with a session of another origin.
  • Validation table with raw JSON on the wire (null message, mistyped fields, tools / state / resume, non-text content...), then a check that nothing was stored and a valid retry works.
  • Concurrent run on a thread (409), a sibling thread not blocked, oversized body, auth and CORS preflight, shutdown waiting for in-flight runs, shutdown not blocked by a run that ignores its cancellation, the production entry point Run.
  • Security regressions: a threadId such as .. is rejected and a sentinel file in a confined temp directory survives; a text/plain or form POST gets 415 and a foreign Host gets 403 with no model call and no session; a token-protected server accepts any Host; literal, pattern and mixed --cors-origin values.
  • Tool safety: under restricted, strict and balanced the tool is not executed, a denial result is streamed and the run finishes; a thread created under autonomous follows the server's policy after a restart as restricted.
  • Translator unit tests for edge cases (message boundaries, tool call variants, sub-session events, terminal events for every stop reason, an error the run recovers from, unnamed tool calls, CUSTOM).
  • go test -race ./pkg/agui/ ./pkg/httpsec/ passes. Key behaviours were checked by disabling them and watching the matching test fail (thread lock, request cancellation, shutdown wait, origin collision, dedup, auth, body limit, elicitation decline, threadId pattern, content-type and Host checks, CORS matching, safety policy, resume ceiling, stop-reason mapping...).

Interoperability

  • In the test suite: TestInterop_SDKClientConsumesStream drives the server with the AG-UI Go SDK client (pkg/client/sse), decodes every frame with the SDK decoder and runs events.ValidateSequence on the result.
  • Manual check, not in the repository: the TypeScript client @ag-ui/client 1.0.5 (HttpAgent.runAgent, which applies the protocol's own event verification) consumed a multi-agent run with reasoning and a tool call, and rebuilt the expected messages (assistant tool call, tool result, reasoning, assistant text).

Validation

  • task build: OK
  • task test (go test ./... with .env.test): OK
  • golangci-lint run, go run ./lint ., go mod tidy --diff: no finding in the files of this PR. My local golangci-lint reports errcheck on channel receives in files this PR does not touch (cmd/root/backend_auth_test.go, pkg/sqliteutil/sqlite_test.go, pkg/tools/lifecycle/supervisor_test.go); they are pre-existing and left alone.

Known gaps, not fixed here

  • serve a2a and serve chat build their CORS configuration the same way, so they still drop literal origins when --cors-origin mixes literals and patterns. The fix is to use OriginMatcher.Match there too. The three corsMiddlewareConfig copies cannot move to pkg/httpsec, which must not depend on echo (TestPackageDoesNotDependOnEcho).
  • serve a2a has no Host check on an unauthenticated loopback listener.
  • largeToolResultDir trusts the session ID; this PR validates the ID at the AG-UI boundary and leaves the hook unchanged.

Notes for reviewers

  • The endpoint path is /ag-ui and the default port 8084 (next to 8082 for A2A and 8083 for chat). Both are easy to change if you prefer other values.
  • The SDK's SSE writer adds an id: line built from the event type and timestamp to each frame. It is valid SSE and both clients ignore it.
  • Out of scope, as listed in the issue: interrupts (HITL), frontend tools, shared state, attachments, a Docker Agent AG-UI client.

@aheritier aheritier added area/api For features/issues/fixes related to the usage of the cagent API area/core Core agent runtime, session management area/docs Documentation changes area/sessions For features/issues/fixes related to session lifecycle (resume, persistence, export) kind/feat PR adds a new feature (maps to feat:). Use on PRs only. labels Nov 28, 2026
@deka
deka marked this pull request as ready for review November 30, 2026 09:05
@deka
deka requested a review from a team as a code owner November 30, 2026 09:05
@rumpl

rumpl commented Nov 30, 2026

Copy link
Copy Markdown
Member

Just a heads up, this is a big PR, we're gonna need some time to review and grok it

@deka

deka commented Nov 30, 2026

Copy link
Copy Markdown
Contributor Author

Just a heads up, this is a big PR, we're gonna need some time to review and grok it

Yes, maybe after merging the new A2A features?
Regards

@rumpl

rumpl commented Dec 1, 2026

Copy link
Copy Markdown
Member

@deka Could you please tell me how I can test this? How can I get a UI that listens to docker-agent's ag-ui stream

@aheritier aheritier left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Six blocking issues inline: prompt policy, request validation, thread isolation, two stream outcomes, and CLI completion.

Comment thread pkg/agui/server.go Resolved
Comment thread pkg/agui/input.go Resolved
Comment thread pkg/agui/input.go Resolved
Comment thread pkg/agui/translator.go Resolved
Comment thread pkg/agui/translator.go Resolved
Comment thread cmd/root/serve.go Resolved
@deka
deka force-pushed the feat/ag-ui-serve branch from ea43569 to 4ecb1ca Compare December 1, 2026 10:13
deka added a commit to la-fabrique/docker-agent that referenced this pull request Dec 1, 2026
Addresses review comment docker#5067 (comment).

Signed-off-by: deka <dimitri.rayer@gmail.com>
deka added a commit to la-fabrique/docker-agent that referenced this pull request Dec 1, 2026
Decoder.More returned false on a stray closing bracket and on read errors, so a malformed body started a run and a chunked body past the size limit lost its 413.

Addresses review comment docker#5067 (comment).

Signed-off-by: deka <dimitri.rayer@gmail.com>
deka added a commit to la-fabrique/docker-agent that referenced this pull request Dec 1, 2026
The runtime ends an answer truncated by the model's token limit as a normal turn, with FinishReason=length. The stream now ends with RUN_ERROR (code length) instead of RUN_FINISHED.

Addresses review comment docker#5067 (comment).

Signed-off-by: deka <dimitri.rayer@gmail.com>
deka added a commit to la-fabrique/docker-agent that referenced this pull request Dec 1, 2026
TOOL_CALL_END only closes the argument stream: clients report a started call without a TOOL_CALL_RESULT as pending when the run succeeds. A call retracted by a provider fallback now gets a result saying it was not executed, and RUN_FINISHED is never sent with an unanswered call.

Addresses review comment docker#5067 (comment).

Signed-off-by: deka <dimitri.rayer@gmail.com>
deka added a commit to la-fabrique/docker-agent that referenced this pull request Dec 1, 2026
The session ID names the directory of large tool results, which the session-end hook removes. On a case-insensitive filesystem two threads whose IDs differ only by case shared it, while the store and the run lock told them apart. The session ID is now ag-ui-<sha256(threadId)>; events keep the wire threadId.

Addresses review comment docker#5067 (comment).

Signed-off-by: deka <dimitri.rayer@gmail.com>
deka added a commit to la-fabrique/docker-agent that referenced this pull request Dec 1, 2026
A retry skipped user_prompt_submit, so a prompt a hook had blocked reached the model, and only the last of several new user messages was checked. The new user messages now make one prompt, and a retry submits the unanswered prompt again: the runtime announces, stores and checks it like any other. Deduplication only decides which messages are new.

Addresses review comment docker#5067 (comment).

Signed-off-by: deka <dimitri.rayer@gmail.com>
@deka

deka commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @aheritier 🙏 Addressed in 7aba9c2..c42c866, details in the threads.

@aheritier
aheritier marked this pull request as draft December 1, 2026 11:03
@aheritier

Copy link
Copy Markdown
Collaborator

Please move this PR back to ready for review once the requested changes are addressed.

@deka

deka commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

@rumpl I added a demo page for that in 17bf357: examples/ag-ui/README.md. It's a single HTML file using the official @ag-ui/client, with the chat on one side and the raw AG-UI events on the other. The README covers building, the agent config, the two commands to run, and what to try.

@deka
deka marked this pull request as ready for review December 1, 2026 11:34
@deka
deka requested a review from aheritier December 1, 2026 11:34
deka added a commit to la-fabrique/docker-agent that referenced this pull request Dec 1, 2026
Addresses review comment docker#5067 (comment).

Signed-off-by: deka <dimitri.rayer@gmail.com>
deka added a commit to la-fabrique/docker-agent that referenced this pull request Dec 1, 2026
Decoder.More returned false on a stray closing bracket and on read errors, so a malformed body started a run and a chunked body past the size limit lost its 413.

Addresses review comment docker#5067 (comment).

Signed-off-by: deka <dimitri.rayer@gmail.com>
deka added a commit to la-fabrique/docker-agent that referenced this pull request Dec 1, 2026
The runtime ends an answer truncated by the model's token limit as a normal turn, with FinishReason=length. The stream now ends with RUN_ERROR (code length) instead of RUN_FINISHED.

Addresses review comment docker#5067 (comment).

Signed-off-by: deka <dimitri.rayer@gmail.com>
deka added a commit to la-fabrique/docker-agent that referenced this pull request Dec 1, 2026
TOOL_CALL_END only closes the argument stream: clients report a started call without a TOOL_CALL_RESULT as pending when the run succeeds. A call retracted by a provider fallback now gets a result saying it was not executed, and RUN_FINISHED is never sent with an unanswered call.

Addresses review comment docker#5067 (comment).

Signed-off-by: deka <dimitri.rayer@gmail.com>
deka added a commit to la-fabrique/docker-agent that referenced this pull request Dec 1, 2026
The session ID names the directory of large tool results, which the session-end hook removes. On a case-insensitive filesystem two threads whose IDs differ only by case shared it, while the store and the run lock told them apart. The session ID is now ag-ui-<sha256(threadId)>; events keep the wire threadId.

Addresses review comment docker#5067 (comment).

Signed-off-by: deka <dimitri.rayer@gmail.com>
deka added a commit to la-fabrique/docker-agent that referenced this pull request Dec 1, 2026
A retry skipped user_prompt_submit, so a prompt a hook had blocked reached the model, and only the last of several new user messages was checked. The new user messages now make one prompt, and a retry submits the unanswered prompt again: the runtime announces, stores and checks it like any other. Deduplication only decides which messages are new.

Addresses review comment docker#5067 (comment).

Signed-off-by: deka <dimitri.rayer@gmail.com>
@deka
deka force-pushed the feat/ag-ui-serve branch from 074476a to acdde79 Compare December 1, 2026 13:23

@aheritier aheritier left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Four blocking issues: rejected prompts can reach the model on a later turn, batched messages can be replayed, repeated tool calls lose their results, and provider refusals are reported as success.

Comment thread pkg/agui/server.go Resolved
Comment thread pkg/agui/server.go Resolved
Comment thread pkg/agui/translator.go Resolved
Comment thread pkg/agui/translator.go Resolved
@aheritier
aheritier marked this pull request as draft December 1, 2026 16:31
deka added a commit to la-fabrique/docker-agent that referenced this pull request Dec 1, 2026
Addresses review comment docker#5067 (comment).

Signed-off-by: deka <dimitri.rayer@gmail.com>
deka added a commit to la-fabrique/docker-agent that referenced this pull request Dec 1, 2026
Addresses review comment docker#5067 (comment).

Signed-off-by: deka <dimitri.rayer@gmail.com>
deka added a commit to la-fabrique/docker-agent that referenced this pull request Dec 1, 2026
Addresses review comment docker#5067 (comment).

Signed-off-by: deka <dimitri.rayer@gmail.com>
deka added a commit to la-fabrique/docker-agent that referenced this pull request Dec 1, 2026
Addresses review comment docker#5067 (comment).

Signed-off-by: deka <dimitri.rayer@gmail.com>
@deka

deka commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @aheritier 🙏 Addressed in 73581ec..869df41, details in the threads.

@deka
deka marked this pull request as ready for review December 1, 2026 17:23
@deka
deka requested a review from aheritier December 1, 2026 17:35
@trungutt

trungutt commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Thanks @deka, looks great now. Two things left:

  1. CI fails to build. Your fix(a2a): allow literal CORS origins alongside patterns #5088 added OriginMatcher.Match to main, and this PR adds it again (method OriginMatcher.Match already declared). Please update the PR on top of latest main (merge/rebase whatever you want) and drop the PR's Match and TestOriginMatcher_Match.

  2. The runtime is never closed. Background agents ignore the request's cancellation and only Close() stops them, so they keep running after RUN_FINISHED (reproduced on 869df41). Please close the runtime once stream returns, but in the background: Close() waits for the background agents' cleanup, which would otherwise hold the response. Shutdown should still wait for it. fix(a2a): close the runtime when a run ends #5082 does this for serve a2a, with a test you can adapt.

deka added 14 commits December 1, 2026 19:32
Add `docker agent serve ag-ui`, the server side of the AG-UI protocol:
POST /ag-ui takes a RunAgentInput and streams the run back as AG-UI
events over SSE, so any AG-UI client SDK can drive an agent.

- pkg/agui translates runtime events to AG-UI events (run, text,
  reasoning, tool call, step and custom events) with the Go SDK of
  ag-ui-protocol/ag-ui; the runtime is unchanged
- threadId maps to the session ID; the server-side session is the
  source of truth and only the trailing user messages are appended
- one run at a time per thread; a client disconnect cancels the run
- RunAgentInput is validated before any session change; non-empty
  tools, state or resume are rejected rather than ignored
- same auth, CORS and tool safety defaults as serve a2a

Human-in-the-loop, frontend tools, shared state and attachments are
left to follow-up issues.

Closes docker#5066

Signed-off-by: deka <dimitri.rayer@gmail.com>
Input:
- restrict threadId to letters, digits, '.', '_' and '-': it becomes the
  session ID, which names the tool-result directory removed at session end
  (".." resolved to the temp dir itself)
- bound message ids, reject duplicate ids among the trailing user messages,
  and stop validating the history that is discarded

Cross-site requests:
- require Content-Type: application/json (415), so a browser needs a CORS
  preflight
- check the Host header on a loopback listener without a token
- honour literal origins when --cors-origin mixes literals and patterns

Run outcome:
- only the stop event ends the stream: an error the run recovered from is
  sent as CUSTOM docker-agent.error before RUN_FINISHED
- a run cut short (max_iterations, budget_exceeded, hook_blocked,
  loop_detected) or closed without a stop event ends with RUN_ERROR
- close open messages, tool calls and steps before RUN_ERROR
- name unnamed tool calls, and log an invalid event instead of treating it
  as a client disconnect

Shutdown cancels the runs even when Serve fails on its own; the drain stays
bounded and is now documented, along with the response codes.

Signed-off-by: deka <dimitri.rayer@gmail.com>
Addresses review comment docker#5067 (comment).

Signed-off-by: deka <dimitri.rayer@gmail.com>
Decoder.More returned false on a stray closing bracket and on read errors, so a malformed body started a run and a chunked body past the size limit lost its 413.

Addresses review comment docker#5067 (comment).

Signed-off-by: deka <dimitri.rayer@gmail.com>
The runtime ends an answer truncated by the model's token limit as a normal turn, with FinishReason=length. The stream now ends with RUN_ERROR (code length) instead of RUN_FINISHED.

Addresses review comment docker#5067 (comment).

Signed-off-by: deka <dimitri.rayer@gmail.com>
TOOL_CALL_END only closes the argument stream: clients report a started call without a TOOL_CALL_RESULT as pending when the run succeeds. A call retracted by a provider fallback now gets a result saying it was not executed, and RUN_FINISHED is never sent with an unanswered call.

Addresses review comment docker#5067 (comment).

Signed-off-by: deka <dimitri.rayer@gmail.com>
The session ID names the directory of large tool results, which the session-end hook removes. On a case-insensitive filesystem two threads whose IDs differ only by case shared it, while the store and the run lock told them apart. The session ID is now ag-ui-<sha256(threadId)>; events keep the wire threadId.

Addresses review comment docker#5067 (comment).

Signed-off-by: deka <dimitri.rayer@gmail.com>
A retry skipped user_prompt_submit, so a prompt a hook had blocked reached the model, and only the last of several new user messages was checked. The new user messages now make one prompt, and a retry submits the unanswered prompt again: the runtime announces, stores and checks it like any other. Deduplication only decides which messages are new.

Addresses review comment docker#5067 (comment).

Signed-off-by: deka <dimitri.rayer@gmail.com>
A one-file page using the official @ag-ui/client, showing the chat and the raw AG-UI events, with a README to build, prepare the agent and run it.

Signed-off-by: deka <dimitri.rayer@gmail.com>
8000 serves the demo page and 8084 the AG-UI server. requireLocalPort keeps the same ports on the host, so the page origin matches --cors-origin.

Signed-off-by: deka <dimitri.rayer@gmail.com>
Addresses review comment docker#5067 (comment).

Signed-off-by: deka <dimitri.rayer@gmail.com>
Addresses review comment docker#5067 (comment).

Signed-off-by: deka <dimitri.rayer@gmail.com>
Addresses review comment docker#5067 (comment).

Signed-off-by: deka <dimitri.rayer@gmail.com>
Addresses review comment docker#5067 (comment).

Signed-off-by: deka <dimitri.rayer@gmail.com>
@deka
deka force-pushed the feat/ag-ui-serve branch from 869df41 to b91787b Compare December 1, 2026 19:48

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/api For features/issues/fixes related to the usage of the cagent API area/core Core agent runtime, session management area/docs Documentation changes area/sessions For features/issues/fixes related to session lifecycle (resume, persistence, export) kind/feat PR adds a new feature (maps to feat:). Use on PRs only.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: AG-UI protocol support, step 1 (serve ag-ui streaming chat)

4 participants