Skip to content

feat: add chat plugins backed by a chatd fork node - #2

Merged
ibetitsmike merged 15 commits into
mainfrom
mike/chat-plugins
Nov 9, 2026
Merged

ibetitsmike merged 15 commits into
mainfrom
mike/chat-plugins

Conversation

@ibetitsmike

@ibetitsmike ibetitsmike commented Nov 8, 2026 •

Copy link
Copy Markdown
Owner

Xum opened this PR for Mike.

Ports chat plugins from the coder/coder branch mike/chat-plugins (tip 76d1a1ca8b6). Sandboxed Wasm plugins (wazero, one coder plugin-host child process per plugin) bridge Coder Agents chats to external services such as Signal. An owner uploads a plugin per organization and grants it capabilities, users link an external identity with a link code, chat events of linked users go to the plugin, and the plugin's webhook posts into chats. A database lease picks the replica that runs a plugin, and other replicas forward webhooks to it. The feature is behind the plugins experiment.

The branch is rebased onto main at 7e37c9bb5f, after #25 added coderd/database/forkdb and the chat_subagents node. The first 12 commits are the source commits, cherry-picked unchanged. The 13th fixes golangci-lint findings that chatdmig files on fork main already had (unhandled writes, a uint conversion, a test timeout constant, a control flag and an import shadowing), so the full lint run reports 0 issues. The 14th moves the database layer to the fork's layout from chatdmig/README.md: the plugin tables become a chatd fork node, and their queries join forkdb next to chat_subagents. Upstream's generated database code is identical to main. The 15th fixes a source test: the sandbox tests started their 60 second deadline before building the test plugin, and a cold wasip1 build on the CI runner used it up.

Fork decisions

  • chatd node, not 000640. nodes/01a1bc7b-…_plugins.up.sql replaces the numbered migration, its down file and its fixture, so upstream's next 000640 cannot collide. It adds six values to the core enum public.api_key_scope and creates plugins, plugin_user_links, plugin_link_codes and plugin_chat_bindings in chatd, with foreign keys to organizations, files, dbcrypt_keys, users and chats. dump.sql, models.go, queries.sql.go, querier.go, the constraint files, dbmock, querymetrics.go, dbauthz.go, dbgen.go, modelmethods.go and dbcrypt.go are back to main.
  • forkdb. The 25 plugin queries go in forkdb/queries/plugins.sql. sqlc.yaml lists the plugins node before chat_subagents, in graph order, which TestSQLCSchemaOrder checks. forkdb.From, forkdb.Wrapper and forkdb.InTx from feat: add forkdb for fork-only queries and the chat_subagents node #25 do not change. The four transactions of the source (create and update a plugin, issue a link code, complete a link) use InTx, and TestInTx now checks a commit and a rollback.
  • Authorization. dbauthz/fork_forkdb.go makes the same check as the source branch for each plugin query. TestForkQuerier gets the source TestPlugins cases, so it still fails for a fork query without a case.
  • dbcrypt and metrics. enterprise/dbcrypt/fork_forkdb.go now encrypts plugins.config on the same six queries as the source, instead of passing every fork query through. TestPlugins in enterprise/dbcrypt checks the round trip. dbmetrics/fork_forkdb.go measures each plugin query under its own name.
  • API key scopes. With upstream's dump.sql, sqlc no longer emits the plugin scopes. forkdb.APIKeyScopeValues lists the six values, and forkdb.ValidAPIKeyScope accepts upstream's and the fork's, so apikey.Generate and the token error message use it. The OAuth2 grant path keeps Valid(), since these scopes are not external and no app can register them. scripts/check-scopes also reads the ALTER TYPE api_key_scope ADD VALUE lines of the fork nodes. TestAPIKeyScopeValues checks that both lists together equal the enum in a migrated database. rbac, codersdk and the generated scope files did not change.
  • Dropped GetPluginChatMessagesAfter. It returned chat_messages rows, so forkdb would have needed its own copy of the ChatMessage model. Delivery now pages with upstream's GetChatMessagesByChatIDAscPaginated (same visibility and deletion filter) and keeps only assistant messages in Go. The cursor moves to the last message of the page, so user messages are skipped once.
  • Equivalence tests. TestUpgradeMatchesFresh gets a subtest per fork node that migrates a database without the node, upgrades it, and compares it with a fresh one. TestForkNodesOnlyAddToChatd fails if a fork node creates or changes anything outside chatd other than adding enum values.
  • fork-ci. graph runs check-scopes. chat-tests adds plugin to the ./coderd and ./enterprise/coderd filter, and TestExpPlugins of ./cli.

Apart from the source commits, upstream files change in a few lines: one call each in coderd/apikey/apikey.go, coderd/apikey.go and scripts/check-scopes/main.go, and the plugin block that the source added to coderd/coderd.go. The rest is in fork files: the fork_forkdb*.go file next to each wrapper, coderd/database/forkdb, the node and scripts/check-scopes/fork.go.

Validation

Local runs on a35c726759. Go suites ran in a coder-gen:local container (Go 1.26.10, Postgres 15).

  • chatdmig check and go test ./coderd/database/migrations/chatdmig/... with a database: pass. The without …_plugins subtest of TestUpgradeMatchesFresh is the upgrade from the fork main schema, and it also runs in the schema job.
  • go test ./coderd/x/plugins/..., also with -race: pass.
  • -run '(?i)plugin' ./coderd ./enterprise/coderd and -run TestExpPlugins ./cli: pass.
  • ./coderd/database/forkdb/..., ./coderd/database/dbauthz/, ./coderd/database/dbmetrics/, ./enterprise/dbcrypt/..., ./coderd/rbac/..., ./coderd/apikey/...: pass.
  • go run ./scripts/check-scopes, go run ./scripts/intxcheck on the changed packages, go build ./...: pass.
  • golangci-lint with the full config and with .golangci.new-code.yaml --new-from-merge-base=origin/main on the changed packages: 0 issues outside testdata, which golangci-lint run does not lint.
  • forkdb/generate.sh leaves no diff.
  • site/: tsc, biome and vitest (22 files, 440 tests): pass.

Open issues

  • coder server dbcrypt rotate, decrypt and delete do not handle plugins.config, as in the source branch. A delete can fail on the config_key_id foreign key while a plugin still uses the key.

ibetitsmike added a commit that referenced this pull request Nov 9, 2026
InTx had no test on this branch: PR #2's TestInTx needs plugin queries.
TestInTx checks that the fork queries run in the transaction of the
upstream queries and roll back with it.
ibetitsmike added a commit that referenced this pull request Nov 9, 2026
* feat(coderd/database): add forkdb for fork-only sqlc queries

Add package forkdb, which runs fork-only queries generated by sqlc on the
connection or transaction of a database.Store and behind the dbauthz,
dbmetrics and dbcrypt wrappers. Add the first fork node, chat_subagents,
with one query, since sqlc refuses to generate with zero queries. Add a
fork-ci job that fails when forkdb generation drifts.

* style(coderd/database/dbauthz): end fork_forkdb_test.go with a newline

* style(coderd/database/migrations/chatdmig): drop the extra blank line in the chat_subagents node

* refactor(coderd/database/dbauthz): drop a redundant method check in TestForkQuerier

* test(coderd/database/forkdb): cover forkdb.InTx

InTx had no test on this branch: PR #2's TestInTx needs plugin queries.
TestInTx checks that the fork queries run in the transaction of the
upstream queries and roll back with it.
Add the storage and authorization foundation for chat plugins behind the
new "plugins" experiment:

- Migration 000640 adds plugins, plugin chat bindings, link codes, and
  leases tables, plus plugin:* and coder:chats.converse API key scopes.
- queries/plugins.sql with generated querier, dbauthz, dbmetrics, dbmock,
  dbgen, and dbcrypt support for encrypted plugin config.
- rbac.ResourcePlugin, excluded from member and org-admin defaults, and
  the internal coder:chats.converse composite scope.
- codersdk.ExperimentPlugins and regenerated API docs and TS types.
Adds the coder.plugins.v1 protobuf ABI shared by coderd and Wasm plugins,
and a guest SDK for Go plugins built with GOOS=wasip1 GOARCH=wasm
-buildmode=c-shared. The SDK exports coder_alloc, coder_manifest,
coder_on_tick, coder_on_event and coder_on_http, and talks to the host
through the coder.call and coder.result imports.
Adds coderd/x/plugins/sandbox, which runs one plugin module in wazero
with memory, time, input, output and log limits and without filesystem,
environment, argument or network access, and coderd/x/plugins/pluginhost,
which serves the sandbox over dRPC on stdio from a hidden `coder
plugin-host` subcommand. coderd starts the child with a fixed minimal
environment and drives it through pluginhost.Client. plugintest builds
plugins for tests, and the sandbox test plugin exercises the whole ABI.
Report failed kills of the plugin host, forward log sink write errors,
join cleanup errors in sandbox.New, and keep proto3 strings from plugins
valid UTF-8 so encoding a result cannot crash the guest. Logf falls back
to stderr when the host rejects the line.
Adds the codersdk types and ExperimentalClient methods for installing
plugins, reading their manifests, and linking external accounts such as
a Signal number to a Coder user. The TypeScript types are regenerated.
Run installed plugins and expose the experimental plugin API behind the
"plugins" experiment:

- coderd/x/plugins: a Manager that leases plugins per replica and runs
  each one in its own `coder plugin-host` process, host calls that check
  the approved grants (chat capabilities, HTTP origins, config keys)
  before they act, chat event delivery to linked users' chats, ticks,
  and webhook forwarding.
- Host calls act for the linked user through a short-lived
  coder:chats.converse token, so a plugin reaches only the chats API of
  users who linked an account.
- coderd/plugins.go: owner-only install, inspect, list, update, and
  delete; link codes and links for users; a public webhook route the
  plugin authenticates itself.
- UpdatePluginRequest.Config is now a pointer so an empty map clears all
  config values.
- Regenerated API docs and TypeScript types.
Add `coder exp plugins` with install (prints the requested grants and
asks before it grants them), list, enable, disable, config, and remove.
Add an example plugin that bridges Coder chats to Signal through a
signal-cli-rest-api server. Users link with a code, Signal messages go
to their chats, and agent replies come back to Signal.
convertPlugin returns an error when the stored manifest or grants do not
decode, and the handlers answer with an internal server error. A failed
write of the webhook response is logged.
The sandbox compilation cache frees an entry when the last module that
uses it closes. Under the race detector, one compile of a Go module takes
approximately 20 seconds, so TestPlugins ran out of time. BuildWasm now
keeps one sandbox module open for each built package, and later compiles
of the same bytes in the test binary are cache hits.
Add /settings/linked-accounts, shown in the user settings sidebar when
the plugins experiment is on. Each linkable plugin lists the linked
external accounts with an Unlink action, and a button makes a one-time
link code that the user sends to the bot as /link CODE. While a code
waits, the page checks the list every 3 seconds and hides the code when
a new account links or the code expires.
Only the replica that holds a plugin's lease could answer its webhook.
Behind a load balancer, the other replicas replied 503, so a sender that
does not retry lost the message.

A replica that does not run the plugin now forwards the webhook to the
lease holder at its relay address, the way chat stream parts reach the
replica that owns a chat. The forwarded request keeps its method, path,
query, body and end-to-end headers. A relay header stops a second hop,
and coderd removes it before the plugin sees the request. If the holder
can't be reached, the sender still gets 503 with Retry-After.

A replica that shuts down now publishes the lease release, so another
replica takes over at once instead of on its next 10-second check.
golangci-lint reported unhandled errors, an integer conversion, a magic test timeout, a control flag and an import shadowing in chatdmig files that fork main already had.
The plugin tables become the chatd fork node plugins instead of the
upstream numbered migration 000640, so upstream's next migration cannot
collide with it. Their queries move to a new sqlc package,
coderd/database/forkdb, and upstream's generated database code is back
to main.

forkdb.From returns the fork queries through the dbauthz, dbmetrics and
dbcrypt wrappers of a database.Store, and forkdb.InTx runs both query
sets in one transaction. The dbauthz fork querier makes the same checks
as the source branch. forkdb.ValidAPIKeyScope accepts the plugin scopes
that sqlc no longer emits, and check-scopes reads them from the fork
nodes. The chatdmig equivalence tests now upgrade a database without
each fork node and check that fork nodes only add to chatd.
…deadline starts

newModule created its 60 second context before plugintest.TestPlugin, so a cold wasip1 build on a busy CI runner used up the deadline and every sandbox.New failed with context deadline exceeded. The other callers already build first.
@ibetitsmike
ibetitsmike marked this pull request as ready for review November 9, 2026 02:19
@ibetitsmike
ibetitsmike merged commit 8c183ed into main Nov 9, 2026
9 checks passed
@ibetitsmike
ibetitsmike deleted the mike/chat-plugins branch November 9, 2026 02:19
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-09T02:36:53.071555Z a35c726 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a35c726759

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coderd/plugins.go Resolved
Comment thread coderd/plugins.go Resolved
Comment thread coderd/x/plugins/delivery.go Resolved
Comment thread coderd/x/plugins/manager.go Resolved
ibetitsmike added a commit that referenced this pull request Nov 9, 2026
#2 added ExperimentPlugins to ExperimentsKnown without an entry in
TestExperimentDisplayNames, which left go test ./codersdk/ red on main.
ibetitsmike added a commit that referenced this pull request Nov 9, 2026
* feat: add fork hooks for chat tools, chat routes and experiments

Fork features need to stay out of the hot upstream files so an upstream
sync does not merge into fork logic. Add the three hooks those features
will use, empty, so each hot file carries exactly one fork line:

- codersdk.ForkExperiments joins ExperimentsKnown in an init, so a
  fork-<feature> experiment is accepted by the CLI flag, the deployment
  config and the experiment evaluator without editing deployment.go.
- Server.appendForkTools runs after appendRootChatTools in
  buildTurnEnvironment, and gates on Server.experiments like the
  upstream chatd tools, so the turn tool list stays the upstream list
  while no fork experiment is on.
- API.registerForkChatRoutes mounts /api/v2/chats/fork behind the API
  key middleware. It has no route yet, so fork paths answer 404 instead
  of reaching the /chats wildcard and turning into a 400 from the UUID
  parsing of {chat}. The mount is accepted beside the /chats mount, in
  either order, which the chat route and swagger walk tests confirm.

* test(coderd/x/chatd): check appendForkTools with every fork experiment off

The W0a acceptance asks for a test that the hook returns the tool list
unchanged while no fork experiment is on, with and without the upstream
experiments.

* test(codersdk): pin the display name of the plugins experiment

#2 added ExperimentPlugins to ExperimentsKnown without an entry in
TestExperimentDisplayNames, which left go test ./codersdk/ red on main.

* test(codersdk): let fork experiments skip the upstream display name test

Fork experiments come last in ExperimentsKnown, so TestExperimentDisplayNames
checks only the upstream entries and a new fork experiment does not have to
edit that upstream test. TestForkExperiments checks the order.

* docs(coderd/x/chatd): leave architecture TODOs for the fork route and tool hooks

* fix(coderd): authenticate the fork chat mount before its 404
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant