Skip to content

feat(daemon): converge the flagship agent onto one supervised path (steps 1-4a) - #3698

Merged
kovtcharov-amd merged 27 commits into
amd:mainfrom
kovtcharov:claude/daemon-convergence
Sep 24, 2026
Merged

kovtcharov-amd merged 27 commits into
amd:mainfrom
kovtcharov:claude/daemon-convergence

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Draft. Steps 1-4a are done. Step 4b — the transport flip itself — was attempted, measured, and reverted; what it actually costs is now written down.

Stacked on #3697. The diff against main includes the Slack commit. Review that first; this PR's commits are the four after feat(slack).

GAIA has two ways to run the flagship agent and was about to grow a third: the TUI spawns it as a stdio child, the daemon knows how to supervise it as an HTTP sidecar but never does, and the Slack bridge spawns a second stdio child. Converging them is subtraction — it deletes the reasons the other paths exist. Reasoning in docs/plans/daemon-convergence.mdx.

The headline: gated tools now work over the daemon

This is the piece the plan originally missed, and it is the safety-critical one. A gated tool could not run over the daemon at all: the agent's HTTP stream did not park on a confirmation, it emitted "this streaming surface cannot collect that yet" and cancelled the run, because there was nowhere for an answer to come from. On the Go side SSEClient implemented neither permission interface, so the chat view could only record intent.

For an agent whose gated set is shell, file writes and code execution, that is the difference between usable and refusing its most useful tools. Now: a tool_decision endpoint carrying confirm_id, a session-scoped bypass endpoint, the stdio transport's own PermissionState attached per turn so "always" grants and bypass survive the turn boundary, and both Go interfaces implemented. Proven with a live round trip over the real stream — the agent parks in confirm_tool_execution, the client answers, the run resumes.

Also fixed

gaia-agent --serve never worked from a pip install. The console script pointed past the transport dispatcher at stdio:main, so the one transport nobody could reach was the one the package documents. The dispatcher now lives in a light gaia_agent.entry that imports neither FastAPI nor the stdio graph until it has chosen — pointing it at server:main would have made the stdio wire import a web framework (an extras-only dependency) just to learn it was not selected.

Transport parity. Claude was refused over HTTP while stdio has always taken --use-claude; and switching model on a live session answered 409 "start a new session_id", which discards the conversation and every loaded skill. Both fixed, the model switch reusing stdio's own switch_model rather than growing a second implementation.

Why 4b is not here

Flipping catalog.go to TransportDaemon compiles and breaks two packages: internal/catalog (3 tests) and the entire tui/test e2e suite (9 tests). The blocker is --mock — a user-facing persistent flag, and the only test double the TUI has. SetMockBinary points "every subprocess agent" at a binary; a daemon agent has none.

The way through is known (tui/test/fakedaemon_test.go already serves the daemon control plane against an isolated GAIA_DAEMON_HOME; it needs /ensure, /version and a streaming /query), but that is test infrastructure plus new semantics for a documented flag, on the path every user hits at launch. It belongs on its own where it can be verified against a real daemon and sidecar rather than rushed. Written up as §4.4.

Test plan

  • python -m pytest hub/agents/gaia/python/tests/ -q — 337 pass
  • cd tui && go test ./... — all packages pass, e2e suite included
  • gaia-agent --serve --port 8149 then curl localhost:8149/health — this is what did not work before
  • Revert the console-script pointer; test_the_console_script_points_at_the_dispatcher fails. The pre-existing tests all called server.main directly, which is why they stayed green through the bug
  • test_a_gated_tool_runs_once_the_decision_arrives — the live confirmation round trip, the thing §3.4 is about

Pre-existing failures in this environment (verified identical on clean main in a separate worktree): test_full_tool_bundles, test_gaia_agent::test_manifest_tools_count, test_profilespec_characterization rows 12-14, test_structured_vlm_extraction, test_doc_examples_runnable — all missing optional extras or a tool-registry count drift, none in this diff.

No eval run: transport only, no prompt, tool, or agent-loop changes.

Evidence

Run on this branch, macOS (Apple Silicon).

gaia slack — the new CLI surface:

$ gaia slack status
Slack app installed on this machine: yes
GAIA configured for Slack:           no
Bridge running (backgrounded):       no

Slack is installed but not connected. Run `gaia slack setup`.

$ gaia slack start --allowed-users U024BE7LH        # no tokens stored yet
❌ Slack is not set up on this machine: no GAIA_SLACK_BOT_TOKEN and no GAIA_SLACK_APP_TOKEN. Run `gaia slack setup` to create the app and store its tokens, or export them directly. Docs: https://amd-gaia.ai/docs/guides/slack

$ GAIA_SLACK_BOT_TOKEN=xoxb-… GAIA_SLACK_APP_TOKEN=xapp-… gaia slack start --allowed-users U0AAAAAAA,U0BBBBBBB
❌ Slack adapter refused to start: more than one allowed user.

This bridge drives a single agent with a single conversation, so every allowed member would share one history — anyone could ask what the others asked or read — and one set of 'Always allow' approvals.
Pass exactly one Slack member ID:

  gaia slack start --allowed-users U024BE7LH

Docs: https://amd-gaia.ai/docs/guides/slack

$ gaia slack setup --print-url --no-browser
https://api.slack.com/apps?new_app=1&manifest_json=%7B%22display_information%22%3A%7B%22name%22%…

$ gaia slack decline --never && gaia slack status
Won't ask about Slack again. `gaia slack setup` still works.
Slack app installed on this machine: yes
GAIA configured for Slack:           no
Bridge running (backgrounded):       no

The two new agent routes, against a live gaia-agent --serve:

$ curl -s localhost:8149/version                 # 2.14 — main's 2.13 added GET /memory
{"apiVersion":"2.14","agentVersion":"0.2.0"}

$ curl -s -X POST .../query/<unknown-run>/tool_decision -d {"decision":"allow"}
{"detail":"No run '11111111-1111-4111-8111-111111111111' is in flight. It may have already finished or been cancelled; the decision was not delivered."}

$ curl -s -X POST .../query/<run>/tool_decision -d {"decision":"maybe"}   # fails closed
{"detail":[{"type":"value_error","loc":["body","decision"],"msg":"Value error, decision must be one of allow, deny, always, got 'maybe'","input":"maybe","ctx":{"error":{}}}]}

$ curl -s -X POST .../sessions/never-seen/bypass -d {"enabled":true}
{"detail":"No session 'never-seen' exists. Send a query on that session first; bypass applies to a conversation, not to the server."}

Not covered: no Slack workspace is connected here, so gaia slack start stops at
the token check above. The DM round trip — streamed reply, Allow/Deny buttons, a file
coming back — remains unverified against real Slack.

Until now the flagship agent only answered someone sitting at the machine
it runs on. Now you message GAIA from Slack on your phone and it answers
from your desktop — reading your files, searching your documents, and
uploading results back — and the TUI offers to connect it the first time
it notices Slack installed, rather than making you find the feature.

`gaia slack` runs its own long-lived process that owns its own
`gaia-agent` child over the same stdio transport the TUI uses. It is a
peer of the TUI, not a passenger: Slack works whether or not a terminal
is open, and a remote turn never lands in the conversation the local user
is looking at. The transport-agnostic half lives in `messaging/bridge.py`
so Signal (amd#693) is a renderer and a socket, not a second bridge.

Security is the part that decides whether this ships at all. Unlike the
Telegram adapter, which reaches a tool-less AgentSDK, this drives the real
agent — so the argument is not "the tools are absent" but "the dangerous
ones are gated and nothing here can ungate them":

- Shell, file writes and code execution already pause on
  TOOLS_REQUIRING_CONFIRMATION. Those pauses render as Block Kit buttons
  and the click rides the existing `gaia_control` channel, so a message
  can ask for a dangerous tool but never run one unattended.
- Bypass is structurally unreachable. The bridge builds no control message
  of its own; its only channel is decide(), which accepts three values.
- No allowlist, no start. DM-only, workspace-pinned, and the buttons check
  the allowlist too — a workspace admin reading the thread cannot approve a
  command on someone else's machine.
- Reads stay ungated. An allowlisted user can read what the agent can read.
  The setup confirmation and the guide say so plainly instead of implying
  otherwise; `--deny-gated-tools` makes the surface read-only outright.

Setup cannot be fully automatic — a Slack app can only be created by a
human at api.slack.com, and the manifest API needs a token obtained the
same way. So it is one click and two pastes: GAIA generates the manifest,
opens the pre-filled create-app URL, validates both tokens against
auth.test, and stores them in the OS keyring. The copy never claims
otherwise.

The offer is shown once and then only when something changed — a skip is
reconsidered exactly when Slack appears on a machine that lacked it, which
is the "I installed it later" case; `never` is honoured forever and
`/slack` always works.

Also fixes a packaging bug found on the way: `gaia.messaging` had no
__init__.py and was absent from setup.py's package list, so `gaia telegram`
ImportErrors on any installed wheel.

Tested: 165 new Python tests and 20 new Go tests. Two of them pin contracts
a fake cannot: the bridge's wire literals are fed through the real
`gaia_agent.stdio.apply_control`, and the adapter's Slack calls are
introspected against the installed slack_sdk — `files.upload` was retired
in favour of files_upload_v2, and a stub would have kept reporting success
straight through that. Full unit suite and the full Go suite pass.

Co-Authored-By: Claude Opus 5 <[email protected]>
@github-actions github-actions Bot added documentation Documentation changes dependencies Dependency updates mcp MCP integration changes cli CLI changes tests Test changes tui Go terminal UI (gaia-tui) labels Sep 12, 2026
Kalin Ovtcharov and others added 6 commits September 11, 2026 18:16
Until now the flagship agent only answered someone sitting at the machine
it runs on. Now you message GAIA from Slack on your phone and it answers
from your desktop — reading your files, searching your documents, and
uploading results back — and the TUI offers to connect it the first time
it notices Slack installed, rather than making you find the feature.

`gaia slack` runs its own long-lived process that owns its own
`gaia-agent` child over the same stdio transport the TUI uses. It is a
peer of the TUI, not a passenger: Slack works whether or not a terminal
is open, and a remote turn never lands in the conversation the local user
is looking at. The transport-agnostic half lives in `messaging/bridge.py`
so Signal (amd#693) is a renderer and a socket, not a second bridge.

Security is the part that decides whether this ships at all. Unlike the
Telegram adapter, which reaches a tool-less AgentSDK, this drives the real
agent — so the argument is not "the tools are absent" but "the dangerous
ones are gated and nothing here can ungate them":

- Shell, file writes and code execution already pause on
  TOOLS_REQUIRING_CONFIRMATION. Those pauses render as Block Kit buttons
  and the click rides the existing `gaia_control` channel, so a message
  can ask for a dangerous tool but never run one unattended.
- Bypass is structurally unreachable. The bridge builds no control message
  of its own; its only channel is decide(), which accepts three values.
- No allowlist, no start. DM-only, workspace-pinned, and the buttons check
  the allowlist too — a workspace admin reading the thread cannot approve a
  command on someone else's machine.
- Reads stay ungated. An allowlisted user can read what the agent can read.
  The setup confirmation and the guide say so plainly instead of implying
  otherwise; `--deny-gated-tools` makes the surface read-only outright.

Setup cannot be fully automatic — a Slack app can only be created by a
human at api.slack.com, and the manifest API needs a token obtained the
same way. So it is one click and two pastes: GAIA generates the manifest,
opens the pre-filled create-app URL, validates both tokens against
auth.test, and stores them in the OS keyring. The copy never claims
otherwise.

The offer is shown once and then only when something changed — a skip is
reconsidered exactly when Slack appears on a machine that lacked it, which
is the "I installed it later" case; `never` is honoured forever and
`/slack` always works.

Also fixes a packaging bug found on the way: `gaia.messaging` had no
__init__.py and was absent from setup.py's package list, so `gaia telegram`
ImportErrors on any installed wheel.

Tested: 165 new Python tests and 20 new Go tests. Two of them pin contracts
a fake cannot: the bridge's wire literals are fed through the real
`gaia_agent.stdio.apply_control`, and the adapter's Slack calls are
introspected against the installed slack_sdk — `files.upload` was retired
in favour of files_upload_v2, and a stub would have kept reporting success
straight through that. Full unit suite and the full Go suite pass.

Co-Authored-By: Claude Opus 5 <[email protected]>
The flagship agent documents two transports from one binary — HTTP for the
daemon and the Agent UI, stdio JSONL for a parent process that spawns it —
and `server.main()` is the dispatcher that chooses between them. The console
script pointed straight past it at `stdio:main`, so a pip-installed
`gaia-agent --serve` exited with "unrecognized arguments: --serve". The
frozen binary and the daemon's dev mode both reach the app by module path,
which is why the one transport nobody could reach was the one the package
itself documents.

The dispatcher moves to `gaia_agent.entry`, which imports neither FastAPI
nor the stdio graph until it has chosen. That indirection is the point:
`server` imports FastAPI at module scope and builds the ASGI app on import,
and FastAPI ships in the [ui]/[api] extras rather than the base install — so
pointing the script at `server:main` would have traded this bug for a worse
one, making the stdio wire import a web framework it never serves on a
machine that may not have it. `server.main` is re-exported from the new
module so the frozen binary's entry point keeps working: one implementation,
two names, rather than two dispatchers that can drift.

Every existing test in test_transport_dispatch.py called `server.main`
directly, which is exactly why they stayed green through this: importing the
dispatcher cannot see that nothing installed points at it. The new tests read
pyproject.toml, assert the dispatcher imports nothing heavy to make its
choice, and run the entry point in a fresh interpreter for each HTTP
selector. Reverting the one-line pointer makes them fail.

First step of the daemon convergence — see docs/plans/daemon-convergence.mdx
for the full sequence and the two defects that follow this one.

Co-Authored-By: Claude Opus 5 <[email protected]>
…ching over HTTP

Moving the TUI onto the daemon would have been a downgrade rather than a
move: two things the stdio transport has always done were unavailable over
HTTP, and both are visible to the user.

**Claude.** `/query` already accepted `provider`, but the allowed set was
`{"lemonade"}` — so `--use-claude`, which stdio takes at launch and `/model`
switches to live, had no HTTP equivalent. The TUI's own factory refuses the
daemon transport for exactly this reason. A Claude request now configures the
backend rather than just naming an id: `model` under `provider="claude"`
means a Claude model, so it is threaded as `claude_model`, not `model_id`
where it would point the local client at something Lemonade cannot serve.
Anything outside the widened set is still refused loudly.

**Switching model on a live session.** The HTTP path answered 409 and told
the caller to start a new `session_id`. That was honest but lossy — a new
session throws away the conversation and every loaded skill, which is what a
retained session exists to keep. It now switches in place, reusing the stdio
transport's own `switch_model` rather than growing a second implementation of
"move an agent onto a new client". That machinery is already all-or-nothing:
it builds the client before touching the agent and rolls back on any failure,
so a bad credential leaves the session on its previous model. The 409 stays
for a switch that genuinely fails, and now says what the session is still
running.

One bug worth naming because a test caught it rather than review: the two
backends record their model in different kwargs, and the registry read only
`model_id`. A Claude session therefore reported no model at all, so the very
request that created it looked like a model change and tried to switch an
agent built moments earlier with exactly what was asked for. The registry now
reads either spelling, and two tests pin that a fresh session is never
switched.

The test that asserted the old refusal is rewritten rather than deleted — it
now pins the new contract, including that the same agent survives the switch.

Steps 2 and 3 of the daemon convergence (docs/plans/daemon-convergence.mdx).
Note that §3.3 of that plan is corrected here too: the HTTP path was never
silently dropping the model, it was refusing it.

Co-Authored-By: Claude Opus 5 <[email protected]>
sys and route_console_logging_to_stderr moved to gaia_agent.entry with the
code that used them.

Co-Authored-By: Claude Opus 5 <[email protected]>
The daemon transport cannot deliver a tool approval at all: there is no HTTP
endpoint for a tool decision (/respond answers needs_input questions only),
and SSEClient implements neither of the permission interfaces the chat view
needs. Flipping the flagship onto the daemon today would leave every gated
tool hanging until it timed out and auto-denied, which for shell and file
writes means they stop working.

Recorded as §3.4 and step 4 is split: the endpoints and client interfaces
land before the transport flip, not after.

Co-Authored-By: Claude Opus 5 <[email protected]>
A gated tool could not run over the daemon at all. The agent's HTTP stream
did not park on a confirmation — it emitted "this streaming surface cannot
collect that yet" and cancelled the run — because there was nowhere for an
answer to come from. On the Go side, SSEClient implemented neither
permission interface, so the chat view could only record intent and told the
user "this agent connection cannot deliver a permission decision".

For the flagship, whose gated set is shell, file writes and code execution,
that is the difference between a usable agent and one that refuses its most
useful tools. This is the prerequisite the convergence plan originally
missed (§3.4).

What it takes:

* `POST /query/{run_id}/tool_decision` — the HTTP twin of the stdio control
  channel's tool_decision message, carrying confirm_id so a late answer
  cannot resolve whichever prompt replaced the one it was typed against, and
  the same three decisions the agent already parses. A decision for a prompt
  that is no longer pending is rejected rather than dropped: dropping it
  leaves the caller believing it approved something that never ran.
* `POST /sessions/{session_id}/bypass` — session-scoped, because bypass
  outliving a turn is the whole point of it. Only an existing session is
  accepted; creating one here would build an entire agent as a side effect
  of a settings toggle, and a typo'd id would silently "succeed".
* The session carries the stdio transport's own PermissionState, attached to
  each turn's handler and detached after. A fresh handler is built per turn,
  so without that both bypass and every "always" grant reset at the turn
  boundary — re-asking for a call the user already approved, which is the
  same defect as never having asked.
* The stream keeps draining on needs_confirmation when somebody is there to
  answer, exactly as it already does for needs_input. A one-shot still gets
  the refusal: parking a run on a prompt nobody will see reads as a hang.
* SSEClient implements ToolPermissionResponder and PermissionBypasser.

The decision words are not translated. PermissionDecision's values ARE the
wire words, a deliberate contract with the agent's DECISION_* constants, so
the Go side validates rather than maps — the agent fails closed on anything
it does not recognise, which would turn the approval a user just gave into a
silent denial.

Tested with a live round trip over the real stream: a scripted agent parks in
confirm_tool_execution, the client answers on /tool_decision, and the run
resumes and reports what it was told. Plus the one-shot still refusing, both
Go interfaces, and every decision reaching the agent verbatim.

Step 4a of docs/plans/daemon-convergence.mdx.

The transport flip itself (4b) was attempted and reverted, and the plan now
records what it actually costs rather than what it looked like: it breaks the
catalog and the whole end-to-end suite, because `--mock` — a user-facing flag
and the only test double the TUI has — points "every subprocess agent" at a
binary, and a daemon agent has none. That is a test-infrastructure change
plus new semantics for a documented flag, on the path every user hits at
launch, so it is sequenced on its own where it can be verified against a real
daemon and sidecar. See §4.4.

Co-Authored-By: Claude Opus 5 <[email protected]>
@kovtcharov
kovtcharov force-pushed the claude/daemon-convergence branch from 2893ed5 to 8c4fed2 Compare September 12, 2026 01:40
@kovtcharov kovtcharov changed the title feat(daemon): converge the flagship agent onto one supervised path (steps 1-3) feat(daemon): converge the flagship agent onto one supervised path (steps 1-4a) Sep 12, 2026
Kalin Ovtcharov and others added 8 commits September 11, 2026 18:51
… terminal

Setup was the odd one out. `/setup` streams `gaia init` in the transcript and
`/provider` (PR amd#3672) opens a native panel for cloud credentials, but
`/slack setup` suspended the whole UI with tea.ExecProcess and handed the
terminal to the CLI.

That is wrong for three reasons beyond inconsistency: a suspended TUI cannot
be drawn, cannot be driven by the control API — which exists so an assistant
can navigate the TUI while the user watches — and cannot be exercised by the
end-to-end harness. It also reads as the app crashing and coming back.

Setup now runs as a three-question flow on the same QuestionModel the agent's
own mid-run questions use, with `sensitive: true` so a pasted token is masked
rather than echoed into a scrollback the user may later screen-share. An
answer whose request id carries the flow's prefix is handled locally instead
of being posted to the agent — without that, a token would be sent to the LLM
as the answer to a question nobody asked.

The tokens reach Python through `gaia slack connect`, which reads them from
STDIN, one per line. Not argv: an argument is visible to every other process
on the machine through `ps` and lands in shell history. A Go test asserts
argv stays clean, which is the kind of thing that regresses silently.

The manifest is not rebuilt in Go. `gaia slack setup --print-url` hands over
the same URL the interactive flow uses, because the manifest — scopes, Socket
Mode, which events are subscribed — is a security surface, and two copies of
it would drift. Browser opening lives in the CLI too, where webbrowser
already was.

QuestionModel gains Sensitive() and Prompt(). The first exists so a host that
puts a secret behind this component can PROVE it is masked; the property is
worth an assertion rather than a comment.

Co-Authored-By: Claude Opus 5 <[email protected]>
`python -m gaia_agent.entry --help` produced nothing — the module had no
__main__ guard, so running it executed nothing at all. That is how the CLI
smoke test exercises an entry point without depending on PATH, and it looked
exactly like a binary that emits no output.

Co-Authored-By: Claude Opus 5 <[email protected]>
…-integration-f0237d

# Conflicts:
#	tui/internal/ui/components/helpoverlay.go
#	tui/internal/ui/components/helpoverlay_test.go
Three of the bridge's headline behaviours were broken, and the tests could
not see it because they fed the adapter event shapes the agent never emits.
Replies never streamed: the adapter read `text` from token events, and the
translator sends `delta`. Files never came back: it looked for a `file_path`
on tool results, which carry only a summary. And an approval prompt nobody
answered parked the bridge's only agent forever, since the agent disables its
own timeout — every later message just sat "Queued".

- Tokens stream from `delta`. An empty final keeps the text that streamed.
- A written file is uploaded using the path the write tool was CALLED with,
  once its result reports no failure. Read tools never trigger an upload.
- An approval prompt is denied after ten minutes, or at once if Slack refuses
  to post it. A click only answers a prompt that is still pending, so a double
  click or a late one cannot resolve a different prompt.
- A mid-run question is posted and the turn cancelled. The stdio wire cannot
  deliver an answer, and the conversation survives, so a reply continues it.
- Shared files are saved to ~/.gaia/slack/inbox under a sanitized name and the
  agent is told the path. Indexing them in the bridge put the document in an
  index the agent child never sees.
- The bridge serves exactly one member. It drives one agent with one
  conversation, so a second member would read the first's history and
  inherit their "Always allow" grants.

test_slack_event_contract.py drives the adapter with events from the real
SSEOutputHandler and CanonicalTranslator, and fails if the translator emits
a type the adapter neither handles nor deliberately ignores.

Also removes SLACK_HEALTH_PORT, which nothing served, adds the missing
`gaia slack` section to the CLI reference, and brings the guide and plan in
line with the shipped design.
`gaia slack status`, which the TUI runs at every launch, checked the bridge
with `os.kill(pid, 0)` — on Windows that is a console Ctrl+C, not a probe.
Liveness now goes through the daemon's psutil `pid_alive` and also confirms
the process is a Slack bridge, so a stale pid file naming an unrelated
process is neither reported as running nor sent SIGTERM by `stop`. psutil
joins the `slack` extra.

CI:
- Making `gaia.messaging` a real package let pylint reach telegram.py's two
  pre-existing unused `context` arguments; they are now `_context`.
- The Decline tests used a /bin/sh stub without the Windows skip.
- The palette title was never truncated, so at 20 columns it wrapped to two
  rows. Eight commands after merging /provider pushed the box one row past a
  12-row window.
…ence

# Conflicts:
#	tui/internal/ui/components/helpoverlay.go
#	tui/internal/ui/components/helpoverlay_test.go
…f0237d' into claude/daemon-convergence

# Conflicts:
#	docs/docs.json
#	docs/guides/slack.mdx
#	docs/plans/slack-tui-integration.mdx
#	setup.py
#	src/gaia/cli.py
#	src/gaia/messaging/bridge.py
#	src/gaia/messaging/slack/adapter.py
#	src/gaia/messaging/slack/cli.py
#	tests/unit/messaging/test_bridge.py
#	tests/unit/messaging/test_bridge_contract.py
#	tests/unit/messaging/test_slack_adapter.py
#	tests/unit/messaging/test_slack_cli.py
#	tests/unit/messaging/test_slack_tool_surface.py
#	tui/internal/gaiaslack/gaiaslack.go
#	tui/internal/gaiaslack/gaiaslack_test.go
#	tui/internal/ui/chat/model.go
#	tui/internal/ui/chat/slack.go
#	tui/internal/ui/chat/slack_test.go
The CLI reference section that arrived with the Slack fixes predates this
branch's non-interactive `gaia slack connect` and `setup --print-url`, so
neither appeared in it. Also gofmt-formats two files this branch edited.
@kovtcharov
kovtcharov marked this pull request as ready for review September 17, 2026 20:04
@github-actions

Copy link
Copy Markdown
Contributor

Request changes

This adds a Slack bridge that drives the real flagship agent, and fills the three daemon-transport gaps the plan names (the --serve entry point, the Claude provider, live model switching, and tool approval over HTTP). The Slack half is careful work — the security posture is written down as tests, not just prose. Two things should be fixed before merge, and both are small.

The agent's wire version wasn't bumped, so an older sidecar fails confusingly. Two new HTTP endpoints were added — one to answer a tool approval, one to toggle bypass — but the contract version the TUI negotiates on stayed where it was. The TUI now calls both unconditionally, so against an agent build that predates them the user gets "the run had already finished, so the decision arrived too late" when the real answer is "this agent is too old to be asked." Bump the version and gate the calls the way the session and questions capabilities already are.

The agent package's own docs now contradict the code. Its spec still tells integrators that changing the model on a live session is refused and that they must start a new session — which is exactly the behaviour this PR replaces with a real in-place switch — and its endpoint table doesn't list either new route. The changelog has no entry. Since the spec and the package publish together, shipping as-is puts self-contradicting docs in front of integrators; CLAUDE.md calls this out by name.

Smaller things, all with suggested fixes below: a stale comment and a user-facing error that still say the agent is local-inference-only right next to the set that now admits Claude; gaia slack setup --print-url --no-browser still opens a browser; and one docstring that disagrees with what --background actually does.

Real-world evidence

No evidence-bundle.md is present in the checked-out tree, and this run had no shell or network access, so I could not read the PR description to see what evidence it carries. I'm therefore not asserting evidence is missing — I simply can't see it. What I can say is that my verdict rests on static review alone: nothing here exercised gaia slack setup/start/status, the two new agent endpoints, or the TUI's /slack panel. If the description doesn't already carry the real gaia slack status --json output, a live POST .../tool_decision request+response, and a TUI screenshot of the setup panel, those are the artifacts worth attaching — this PR adds a CLI surface, an HTTP surface, and a TUI surface at once.

🔍 Technical details

🟡 Important

API_VERSION not bumped for two new endpoints (hub/agents/gaia/python/gaia_agent/server.py:57)

The constant's own comment says "Bumped when the wire surface changes… it must reflect real capability," and tui/internal/client/negotiate.go already gates needs_you (2.11) and session_id (2.12) on it. This PR adds POST /v1/gaia/query/{run_id}/tool_decision and POST /v1/gaia/sessions/{session_id}/bypass, plus a new accepted provider value, and leaves it at 2.12.

SSEClient.RespondToolPermission (tui/internal/client/sse.go:7336 in the diff) maps 404 to "the run had already finished, so the decision arrived too late" — which is what a user of a 2.12 sidecar will see, because the route doesn't exist. The hub publishes the agent package independently of the TUI, so this skew is reachable.

API_VERSION = "2.13"

…plus a toolDecisionContractMajor/Minor gate in negotiate.go alongside the existing two, and a supportsToolDecision check in RespondToolPermission/SetBypassPermissions so the failure names the real cause.

Bundled agent docs contradict the new behaviour (hub/agents/gaia/npm/SPEC.md:270, :319-323)

  • :319-323 still reads: "A /query supplying a model that differs from the one its session_id was built with also gets 409… start a new session_id to switch." server.py:631-655 now switches in place via _AgentSession.switch_model.
  • :270 endpoint table lists /cancel and /respond but neither new route.
  • hub/agents/gaia/npm/CHANGELOG.md has no entry for any of it.

CLAUDE.md's "A functional change must update EVERY doc that describes it" names this exact pattern (#1841): README / SPEC / SKILL / CHANGELOG publish together. Worth grepping 409, _ALLOWED_PROVIDERS, and stdio:main across the npm package before merge — the console-script change (pyproject.toml:36) may also be described there.

🟢 Minor

Stale comment and a self-contradicting 400 (hub/agents/gaia/python/gaia_agent/server.py:63, :577)

Line 63 survived the edit and now sits directly above a set that includes claude:

#: Inference backends ``/query`` accepts. ``claude`` sends the conversation to

And the refusal at :577 tells the caller the agent "runs local inference only" while listing ['claude', 'lemonade'] as allowed. The new test only asserts both names appear in the detail, so it passes with the contradiction intact:

                f"provider {request.provider!r} is not supported by the {AGENT_ID} "
                f"agent. Allowed: {sorted(_ALLOWED_PROVIDERS)}."

--no-browser is ignored when --print-url is passed (src/gaia/cli.py:4211 in the diff / gaia/messaging/slack/cli.py:main)

run_setup(print_url_only=True) takes the default open_browser=True, so gaia slack setup --print-url --no-browser still opens a browser. The unit test at tests/unit/messaging/test_slack_cli.py:6433 passes open_browser=False explicitly, so it can't catch the wiring.

        if getattr(args, "print_url", False):
            return run_setup(
                print_url_only=True,
                open_browser=not getattr(args, "no_browser", False),
            )

Docstring disagrees with --background (src/gaia/messaging/slack/cli.py, run_start)

"Blocks until interrupted unless background" — it always blocks; --background only writes the PID file, which is what the CLI help and docs/guides/slack.mdx both say.

    """Start the bridge. Blocks until interrupted; ``background`` only records a
    pid file so ``gaia slack stop`` can find this process."""

Strengths

  • tests/unit/messaging/test_slack_tool_surface.py argues the security posture structurally, not textually. Parsing the adapter's AST to prove it never builds a raw control dict — and reading GATED_TOOLS from base_agent.TOOLS_REQUIRING_CONFIRMATION rather than copying it — means a future tool added to the gate lands in the check automatically, and a reworded docstring can't defeat it. The _handle_event/_handle_interactive pairing test catches the exact trap Telegram's require_allowed exists for.
  • entry.py fixes gaia-agent --serve for the right reason and tests it the right way. Keeping the dispatcher free of FastAPI so the stdio wire doesn't pay for an extras-only dependency is the non-obvious constraint, and test_every_http_selector_is_recognised_by_the_installed_script runs a real subprocess — importing main, which is what every prior test did, is precisely what kept the bug alive.
  • bridge.py is a genuine transport-agnostic seam, not a Slack file with a general name. Turn serialization, the edit throttle, and the synthesized terminal event on child death are all platform-neutral, and the cross-process constants are pinned against the real gaia_agent.stdio definitions in test_bridge_contract.py rather than trusted.
  • The switch_model rename reuses stdio's snapshot/rollback machinery instead of writing a second switch, which is what keeps conversation_history and loaded_skills alive across a model change on the HTTP path.
  • Docs land with the code: docs/guides/slack.mdx, the CLI reference table, and docs/docs.json navigation are all present and accurate against the parser.

Kalin Ovtcharov added 2 commits September 17, 2026 13:24
Answering a permission prompt and toggling bypass are two new HTTP routes, but
the contract version stayed at 2.12 — so against an agent build that predates
them the TUI called both anyway and the 404 surfaced as "the run had already
finished, so the decision arrived too late". The real answer is that the agent
is too old to be asked, and the hub publishes the agent independently of the
TUI, so that skew is reachable.

2.13 now covers the two routes and the `claude` provider value, and the client
gates on it the way it already gates mid-run questions (2.6) and session_id
(2.12): it refuses before calling and names the contract that added the route.
The npm package's API_VERSION and the test that pins it to the sidecar's move
together.

Also from review:
- The provider refusal said the agent "runs local inference only" while listing
  claude as allowed, and a stale comment above the set said the same.
- `gaia slack setup --print-url --no-browser` still opened a browser. The
  existing test passes open_browser explicitly, so only main()'s wiring could
  catch it; the new test drives main().
- run_start's docstring claimed --background detaches. It records a pid file.
The agent package publishes its spec alongside the code, and the spec still told
integrators that changing the model on a live session is refused and that they
must start a new session — the behaviour this branch replaces with an in-place
switch. SKILL went further and said confirmation-gated tools can never run over
HTTP, so `write_file` and `run_shell_command` were documented as unreachable on
the very surface that can now approve them.

Updated together, as CLAUDE.md requires: the endpoint table gains both new
routes, SKILL §8 documents answering a prompt (and that a run which cannot
answer is still refused), the provider row admits claude, and the changelog
carries entries for all of it.
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions.

Note: Prior review status could not be verified (the gh CLI and WebFetch are both unavailable in this environment), so this is a full first-pass review.

This is a well-designed, security-conscious PR. The Slack adapter's two critical safety invariants — that bypass is unreachable from Slack, and that button-click authorization checks both _allowed() and _same_workspace() — are enforced in code and pinned by tests. The entry.py dispatcher cleanly solves the FastAPI-import layering problem. The v2.13 wire contract additions (/tool_decision, /sessions/{id}/bypass, Claude provider) are internally consistent, and all four hub docs (SPEC, SKILL, README, CHANGELOG) were updated together, which is the right pattern.

Two things worth fixing before merge:

🟡 A new comment in bridge.py names the old console-script target. Line 72 of src/gaia/messaging/bridge.py was written in this PR and says [project.scripts] gaia-agent = "gaia_agent.stdio:main". That was accurate before this PR, but pyproject.toml was changed to gaia_agent.entry:main as part of this same change. The comment ships stale on day one.

🟡 No real-world CLI evidence in the PR. The rubric asks for a gaia slack start invocation and its output when a new CLI subcommand ships, so reviewers can see the golden path works on real hardware. If the description already links this elsewhere, the flag is moot — but if it is absent, a short terminal session output would close the gap.

One nit (does not count toward the 🟡 budget):

🟢 _ask_confirmation (adapter.py lines 716–721) stamps confirm_id onto every element in every block using block.get("elements", []). This works because only actions-type blocks have elements, but the intent would be clearer filtering on block.get("type") == "actions".

🔍 Technical details

Stale comment:
src/gaia/messaging/bridge.py:72 — change "gaia_agent.stdio:main" → "gaia_agent.entry:main" to match what pyproject.toml now installs.

Real-world evidence:
Per the review rubric, new CLI surfaces need the real gaia <subcommand> output in the PR description (or a linked comment). For gaia slack start --allowed-users <id>, that would be the terminal output confirming the bridge started, connected, and responded to a test message. If CI evidence already lives in a linked comment, this is already satisfied.

_ask_confirmation nit:

# Current (all blocks, all elements)
for block in blocks:
    for element in block.get("elements", []):
        element["value"] = confirm_id

# Clearer intent
for block in blocks:
    if block.get("type") == "actions":
        for element in block.get("elements", []):
            element["value"] = confirm_id

Functional either way; the type filter just makes the assumption explicit.

Things that look correct (no action needed):

  • entry.py / server.py circular-import concern: server.py imports entry.main at module scope, but entry.py imports server.serve_http lazily inside a function branch — no cycle.
  • session_registry.switch_model: self.model_id = target only executes when _switch() succeeds, so a failed switch leaves model_id unchanged (correct).
  • PermissionState.attach/detach correctly transfers bypass and "always" grants across turn boundaries.
  • Both _handle_event and _handle_interactive check _allowed() and _same_workspace() — the test test_both_message_and_button_paths_check_the_allowlist pins this.
  • Bypass is absent from bridge.py's control vocabulary — test_bridge.py pins its absence.

… branch

bridge.py's note on which console script the agent wheel installs still named
`gaia_agent.stdio:main` — accurate until this same branch repointed it at
`gaia_agent.entry:main`, so the comment would have shipped stale on day one.

Also filters the confirmation blocks on `type == "actions"` before stamping the
confirm_id. Only actions blocks carry elements, so this changes nothing today;
it states the assumption instead of relying on it.
Main independently claimed contract 2.13 for `GET /memory` (amd#3978) while this
branch claimed 2.13 for `/tool_decision`, `/sessions/{id}/bypass` and the
`claude` provider. Main's 2.13 is already released, so an agent built from it
has /memory but not these routes — gating them on 2.13 would send the TUI to a
route the agent lacks, the exact failure the version gate exists to prevent.

This branch's additions therefore move to 2.14; main's memory route stays at
2.13. The npm package, its docs, the TUI gate and the tests follow, and the
"older agent" tests now use a 2.13 agent, which is the realistic skew. The npm
version test takes main's form, deriving the expected value from server.py.
@github-actions

Copy link
Copy Markdown
Contributor

🟡 The Slack bot token can be sent to a non-Slack URL.

_download() fetches the file URL from the Slack event payload and passes the bot token as an Authorization header. Two gaps: the URL's domain is never validated against files.slack.com (or any Slack-owned domain), and requests.get() follows redirects by default — so if Slack's CDN were to redirect to an external host, the bearer token would be forwarded there.

In practice the url_private_download field comes from Slack's backend and is always Slack-hosted, so the attack requires a compromised Slack response. But it's a defence-in-depth gap that's cheap to close.

Suggested fix:

🔍 Technical details

src/gaia/messaging/slack/adapter.py:554

_SLACK_FILE_DOMAINS = ("files.slack.com", "files-pri.slack.com", "cdn.slack-edge.com")

def _download(self, url: str, name: str, file_id: str = "") -> Path:
    from urllib.parse import urlparse
    parsed = urlparse(url)
    if parsed.scheme != "https" or not any(
        parsed.netloc == d or parsed.netloc.endswith(f".{d}") for d in _SLACK_FILE_DOMAINS
    ):
        raise ValueError(
            f"Slack gave a file URL outside the expected domains ({url!r}); "
            "refusing to send the bot token to it."
        )
    ...
    response = requests.get(
        url,
        headers={"Authorization": f"Bearer {self.bot_token}"},
        timeout=60,
        stream=True,
        allow_redirects=False,   # ← add this
    )

The domain list matches Slack's documented CDN hostnames. allow_redirects=False ensures a redirect never carries the token off-domain even before the domain check runs.

Kalin Ovtcharov and others added 5 commits September 17, 2026 20:38
A shared file is downloaded with the bot token as a bearer header, from a URL
taken from the event payload. Nothing checked that URL was Slack's, and requests
follows redirects by default, so a URL or a redirect pointing elsewhere would
have carried the token with it. Slack always sends its own file URLs, so this
needs a compromised response to matter — but it is cheap to close.

The URL must now be https on a slack.com or slack-edge.com host, compared on the
parsed hostname so userinfo and ports are stripped first, and a redirect is
refused rather than followed. Tests cover a foreign host, plain http, a
lookalike suffix, a URL that is really a request to another host after the
`@`, and a redirect — and assert no request is made at all in the refused cases.
Main's side of the negotiate.go conflict explained that `email` reports a
numerically HIGHER contract (2.14) than the memory route needs and serves no
such route, so it gates /memory by WHICH agent as well as by version. The same
is true of this branch's routes: email also reports 2.14 and serves neither
/tool_decision nor /bypass. A version-only gate would have sent both to it and
turned a 404 into "the run already finished".

So the gate is now contract >= 2.14 on the gaia agent, mirroring
memoryAgentID. The refusal names the right fix for each case: email has no such
route, while an older gaia build should be updated.

It also closes a regression this branch introduced. The chat view decided a
prompt was answerable live when the client's Go type implemented
ToolPermissionResponder, and SSEClient now does for every daemon agent,
email included. The view offered Allow/Deny as live and then failed on click,
where it used to say the decision was only recorded. SSEClient now reports the
negotiated answer through LivePermissionReporter, and the view and /bypass
consult it. A transport that does not report, like the stdio child, keeps
today's behaviour.

Main also added a test that the help panel's Commands block is exactly two
lines. The /slack row that the earlier merge put on a third line now sits on
the first.
Main added `run_python` to the confirmation-gated set, taking it from seven
tools to eight. SKILL §8 keeps this branch's framing — a gated tool can be
answered over HTTP when the caller can answer — with main's updated list and
count; main's "refused, not prompted" wording is what this branch replaces.

The changelog keeps both sides' Added entries. It also fixes a placement
error from this branch: its Changed entries had been inserted in the middle of
the Added list, filing every later Added entry under Changed. They now lead
the release's existing Changed list.
The coding skill started requiring run_python in amd#3994, but the starter-skill
check only knew the inline tools that existed before it, so it failed on main
and on every branch merged from it.
The refusal tests all pass against a guard that rejects everything, so
nothing caught an over-tightened match. Swapping hostname for netloc in
_is_slack_file_url left the whole suite green while silently dropping any
URL carrying an explicit port.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Closed — the domain check and the redirect refusal were already in, pushed a couple of minutes after this review landed. I verified both against head and pushed one test that was missing.

Worth flagging that the suggested fix as written would not have been enough. Setting allow_redirects=False alone makes requests hand back the 302 itself, and raise_for_status() does not treat 3xx as an error — so the redirect's HTML body would have been written out and returned as the user's file, silently. The shipped version rejects a 3xx response explicitly, which is the part that actually matters.

The one thing I did change: every test for this guard was a refusal test, so they all passed against a guard that rejects everything. I confirmed that by swapping hostname for netloc in the check — the whole suite stayed green, even though that quietly drops any URL carrying an explicit port. Added the accept-side test, which fails on that swap.

tests/unit/messaging/ — 207 passed, 1 skipped. Lint clean.

🔍 Technical details

Fix landed in 9ac570ed7 "fix(slack): only ever send the bot token to Slack's own hosts". Verified on head, now 3189c6a34.

_is_slack_file_url (src/gaia/messaging/slack/adapter.py:149) matches on parsed.hostname, not netloc, so userinfo and a port are stripped before comparison — https://[email protected]/x.pdf is judged as evil.example. Allowed domains are ("slack.com", "slack-edge.com") plus subdomains, rather than the narrower explicit list in the suggestion; Slack serves files from several subdomains and pinning three of them would refuse legitimate downloads.

_download then refuses a redirect rather than following it:

allow_redirects=False,
...
if response.is_redirect or 300 <= response.status_code < 400:
    raise ValueError(...)
response.raise_for_status()

Confirmed empirically that raise_for_status() is a no-op on a 302, which is why the explicit check is load-bearing rather than belt-and-braces.

Mutation checks run against head:

Mutation Result
Remove the 3xx guard (suggestion as written) test_a_redirected_download_is_refused_and_nothing_is_saved fails ✅
hostname → netloc Suite stayed green ❌ — the gap this commit closes
hostname → netloc, with the new test Fails on the :443 case ✅

The existing refusal cases already cover the @ userinfo trick, a bare http:// scheme, and the files.slack.com.evil.example suffix trick — those are good and unchanged.

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

This PR swallows #3697 whole — merge #3697 first, or it closes as an empty no-op. @kovtcharov-amd that ordering is the only human decision left here; the PR itself is green and every review finding is already fixed on head.

Nothing pushed to this branch — it needed no changes.

🔍 Technical details

Stack evidence. git log --oneline origin/main..pr/3698 includes #3697's commits 55e011de1, 8ff8801f8, feffd62c9, e7d1b3529, plus the explicit merge e3f170b72 Merge remote-tracking branch 'fork/claude/gaia-slack-tui-integration-f0237d' into claude/daemon-convergence and a duplicate-titled 1d4443f8d.

Retargeting onto #3697 is impossible, not merely undesirable. A PR base must exist in the base repo; gh api repos/amd/gaia/branches/claude/daemon-convergence and .../claude/gaia-slack-tui-integration-f0237d both 404 — the branches exist only on the kovtcharov fork. Merge order is the only available expression of the dependency.

Review findings verified fixed on head:

  • hub/agents/gaia/python/gaia_agent/server.py:62 — API_VERSION = "2.14" (the bot asked for 2.13; 2.14 supersedes it)
  • Docs and the bot-token fix landed in a commit timestamped 03:38 UTC — the last bot comment is 03:36 UTC, i.e. it predates the fix by two minutes and was never re-run.

Not merged with main (28 behind) deliberately: the PR is MERGEABLE/CLEAN and fully green, and its bc6fae453 is byte-identical to main's 39c860b74, so it auto-resolves. Churning a green PR to re-run CI under a spend-capped judge buys nothing.

kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Sep 22, 2026
…cleanly

Both branches reflowed the block to two lines, but placed /slack
differently. Same wording here means no conflict when the stack lands.
Kalin Ovtcharov added 2 commits September 23, 2026 11:40
main's skill-capture work and this branch's HTTP tool approval both describe
the confirmation gate, so the docs had to be reconciled: a gated tool is no
longer refused over /query, and capture_skill makes it nine of them.
The matrix refuses to render until every exposed REST verb carries an eval
annotation, so tool_decision and bypass took the whole Test Gaia Agent job
down the moment main's matrix check merged in. Both are contract-tested
only, like the other query routes.
@github-actions github-actions Bot added the sidecar Agent sidecar contract / harness label Sep 23, 2026
amd#3697 landed on main as a squash, so every Slack file collided with its own
earlier self. This branch carries the later version of each — the native TUI
setup panel rather than the terminal hand-off, `gaia slack connect`, and the
bot-token host guard — so the resolution keeps it.
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 24, 2026
Merged via the queue into amd:main with commit 224df15 Sep 24, 2026
65 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli CLI changes dependencies Dependency updates documentation Documentation changes mcp MCP integration changes sidecar Agent sidecar contract / harness tests Test changes tui Go terminal UI (gaia-tui)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants