Merge branch 'feat/gateway-service': Phase 1 Gateway Service extraction

Stands up archie-gateway as its own binary serving ChatContract over gRPC
and makes it the daemon's only transport for webui chat (Q3 part 5's
atomic flip -- the in-process serving path is deleted, not deprecated).

- contract seams + protobuf toolchain (Phase 0)
- single taskactions.Service across webui, daemon NATS responder and the
  standalone gateway's client
- services.gateway.target is the only config surface left; mode is gone
  now that remote is the only transport
- task dev launches archie-gateway alongside archied + Vite

Verified end-to-end against live infra: real GitHub token (zero repos
configured, so no repo was polled or touched) and the real
@heyarchie_home_bot Telegram bot, both processes booted together against
shared NATS/store, chat and /status round-tripped successfully.

# Conflicts:
#	go.sum
This commit is contained in:
sam committed 2026-09-06 02:26:19 +10:00
commit 5bd553d8ed
52 files changed
+4483 -739

No files matched your search

+11
View File
@@ -50,6 +50,15 @@ jobs:
- name: Install gofumpt
run: go install mvdan.cc/gofumpt@latest
- name: Install protobuf tools
run: bash tools/proto.sh install
- name: Ensure contract baseline ref
run: |
if ! git show-ref --verify --quiet refs/heads/main; then
git branch main origin/main
fi
- name: Install ripgrep
run: sudo apt-get update && sudo apt-get install -y --no-install-recommends ripgrep
@@ -57,6 +66,8 @@ jobs:
run: |
gofumpt -w .
go fix ./...
bash tools/proto.sh lint
bash tools/proto.sh check
go vet ./...
go build ./...
go test ./... -count=1
+40 -9
View File
@@ -15,6 +15,26 @@ tasks:
- gofumpt -w .
- go fix ./...
proto:install:
desc: Install the pinned Buf and protobuf Go generators
cmds:
- bash tools/proto.sh install
proto:generate:
desc: Generate and format committed grpc-go service contracts
cmds:
- bash tools/proto.sh generate
proto:lint:
desc: Lint protobuf contracts and check compatibility with main
cmds:
- bash tools/proto.sh lint
proto:check:
desc: Regenerate contracts and reject uncommitted generated differences
cmds:
- bash tools/proto.sh check
vet:
desc: Run go vet
cmds:
@@ -69,25 +89,32 @@ tasks:
- npm test
dev:
desc: "Develop: archied live-reload + Vite HMR together. Open http://localhost:5173"
desc: "Develop: archied live-reload + archie-gateway + Vite HMR together. Open http://localhost:5173"
summary: |
Runs both halves of the dev loop in one terminal:
Runs the dev loop in one terminal:
* air rebuilds and restarts archied on Go changes
* vite serves the dashboard with hot reload on :5173,
proxying /api and /events through to archied on :8484
* air rebuilds and restarts archied on Go changes
* archie-gateway serves ChatContract on 127.0.0.1:8585 (archied
dials it for chat; it does not embed a gateway)
* vite serves the dashboard with hot reload on :5173,
proxying /api and /events through to archied on :8484
Open http://localhost:5173 -- not :8484. The Vite server is the one with
hot reload; :8484 serves the last built dist/ and will look stale.
Ctrl-C stops both.
deps: [dev:daemon, dev:ui]
Ctrl-C stops all three.
deps: [dev:daemon, dev:gateway, dev:ui]
dev:daemon:
desc: archied only, live-reloading via air (prefer `task dev`)
cmds:
- air
dev:gateway:
desc: archie-gateway only, no live-reload (prefer `task dev`)
cmds:
- go run ./cmd/archie-gateway
dev:ui:
desc: Vite dev server only, expects archied already running (prefer `task dev`)
dir: ui
@@ -115,7 +142,7 @@ tasks:
- go run ./cmd/archied -config-overlay ~/.config/archie/mobile.toml
build:
desc: Build archied and archie-agent binaries
desc: Build archie services and agent binaries
# Version stamping used to live only in Dockerfile.archied, so any build
# from source -- including a host deployment -- reported "dev" for
# both components and /version was useless there. Derive the same
@@ -133,9 +160,11 @@ tasks:
- go.sum
generates:
- "{{.BIN_DIR}}/archied"
- "{{.BIN_DIR}}/archie-gateway"
- "{{.BIN_DIR}}/archie-agent"
cmds:
- go build -ldflags "-X github.com/samcharles93/archie-core/internal/app/archied.gatewayVersion={{.GATEWAY_VERSION}} -X github.com/samcharles93/archie-core/internal/app/archied.runtimeVersion={{.RUNTIME_VERSION}} -X github.com/samcharles93/archie-core/internal/installtype.buildType=binary" -o {{.BIN_DIR}}/archied ./cmd/archied
- go build -ldflags "-X github.com/samcharles93/archie-core/internal/app/archied.gatewayVersion={{.GATEWAY_VERSION}} -X github.com/samcharles93/archie-core/internal/installtype.buildType=binary" -o {{.BIN_DIR}}/archie-gateway ./cmd/archie-gateway
- go build -ldflags "-X github.com/samcharles93/archie-core/internal/app/agentworker.version={{.RUNTIME_VERSION}} -X github.com/samcharles93/archie-core/internal/installtype.buildType=binary" -o {{.BIN_DIR}}/archie-agent ./cmd/archie-agent
test:
@@ -144,10 +173,12 @@ tasks:
- go test ./... -count=1
check:
desc: "Full quality gate: fmt, go fix, vet, lint, build, test, ui tests (matches [[repos.gate]] in config.toml)"
desc: "Full quality gate: fmt, go fix, proto, vet, lint, build, test, ui tests"
cmds:
- task: fmt
- go fix ./...
- task: proto:lint
- task: proto:check
- task: vet
- task: lint
- task: build
+36
View File
@@ -0,0 +1,36 @@
// Command archie-gateway hosts the Gateway Service's gRPC contract.
package main
import (
"context"
"flag"
"fmt"
"os"
"os/signal"
"path/filepath"
"syscall"
"github.com/samcharles93/archie-core/internal/app/archied"
)
func main() { os.Exit(run()) }
func run() int {
base, err := os.UserConfigDir()
if err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
}
var options archied.GatewayOptions
flag.StringVar(&options.Config, "config", filepath.Join(base, "archie", "config.toml"), "configuration file or directory")
flag.StringVar(&options.Overlay, "config-overlay", "", "configuration overlay file or directory")
flag.StringVar(&options.Listen, "listen", "127.0.0.1:8585", "gateway gRPC listen address")
flag.Parse()
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
if err := archied.RunGateway(ctx, options); err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
}
return 0
}
+6 -1
View File
@@ -33,7 +33,12 @@ cp deployments/single-forge-github.toml ~/.config/archie/config.toml
Edit API keys in `~/.config/archie/env` or directly in `config.toml`, then launch Archie Core:
```bash
archied
archie-gateway -config ~/.config/archie/config.toml -listen 127.0.0.1:8585 &
archied -config ~/.config/archie/config.toml
# or via systemd:
systemctl --user start archied
```
The templates use the extracted Gateway Service by default. Start
`archie-gateway` before `archied`; it owns the conversation SQLite file and
serves the `ChatContract` gRPC API on the configured target.
+3
View File
@@ -17,6 +17,9 @@ diff_cap_lines = 0
work_dir = "~/.local/share/archie/work"
db_path = "~/.local/share/archie/archie.db"
[services.gateway]
target = "127.0.0.1:8585"
[forge]
type = "gitea"
host = "https://git.example.com"
+3
View File
@@ -7,6 +7,9 @@
work_dir = "~/.local/share/archie/work"
db_path = "~/.local/share/archie/archie.db"
[services.gateway]
target = "127.0.0.1:8585"
poll_interval = "60s"
# Standalone execution: Forge polling is disabled
@@ -8,6 +8,9 @@
work_dir = "~/.local/share/archie/work"
db_path = "~/.local/share/archie/archie.db"
[services.gateway]
target = "127.0.0.1:8585"
poll_interval = "60s"
[models]
+5
View File
@@ -13,6 +13,11 @@ bot_user = "archie-bot"
bot_email = "archie-bot@users.noreply.github.com"
diff_cap_lines = 400
# The Gateway Service owns conversational state and serves ChatContract over
# gRPC. Run archie-gateway alongside archied with this address.
[services.gateway]
target = "127.0.0.1:8585"
[forge]
type = "github"
host = "https://github.com"
+20 -2
View File
@@ -4,7 +4,7 @@ This runbook describes how to manage `archied` as a background user service on L
---
## 1. Unit File (`~/.config/systemd/user/archied.service`)
## 1. Unit Files (`~/.config/systemd/user/archied.service` and `archie-gateway.service`)
Create the systemd user service file at `~/.config/systemd/user/archied.service`:
@@ -25,6 +25,24 @@ RestartSec=5s
WantedBy=default.target
```
Create the Gateway Service unit beside it:
```ini
[Unit]
Description=Archie Gateway Service
After=network.target
[Service]
Type=simple
ExecStart=%h/.local/bin/archie-gateway -config %h/.config/archie/config.toml -listen 127.0.0.1:8585
EnvironmentFile=-%h/.config/archie/env
Restart=on-failure
RestartSec=5s
[Install]
WantedBy=default.target
```
---
## 2. Enabling User Linger (`loginctl`)
@@ -52,7 +70,7 @@ systemctl --user daemon-reload
Enable and start the service immediately:
```bash
systemctl --user enable --now archied
systemctl --user enable --now archie-gateway archied
```
Check service status:
+3 -1
View File
@@ -53,10 +53,10 @@ require (
golang.org/x/exp v0.0.0-20260824195058-e88cd73687aa // indirect
golang.org/x/sync v0.22.0 // indirect
golang.org/x/sys v0.47.0 // indirect
golang.org/x/text v0.41.0 // indirect
golang.org/x/time v0.15.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20260904194346-d0f1323225a4 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260904194346-d0f1323225a4 // indirect
google.golang.org/protobuf v1.36.12 // indirect
modernc.org/libc v1.75.7 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.12.1 // indirect
@@ -80,6 +80,8 @@ require (
github.com/traefik/yaegi v0.16.1
golang.org/x/net v0.58.0
golang.org/x/term v0.45.0
google.golang.org/grpc v1.83.2
google.golang.org/protobuf v1.36.12
gopkg.in/yaml.v3 v3.0.1
modernc.org/sqlite v1.58.0
)
+6 -34
View File
@@ -1,21 +1,17 @@
cel.dev/cel-go v0.32.0 h1:irvpFKr5EuGPyxeME03ERh0rii1TX+BDAnB9eL3IvNk=
cel.dev/cel-go v0.32.0/go.mod h1:DnVip7tpJSsgZymwfT+m1tnEVy3ivAjSMXPx12YrMkU=
cel.dev/expr v0.25.1 h1:1KrZg61W6TWSxuNZ37Xy49ps13NUovb66QLprthtwi4=
cel.dev/expr v0.25.1/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4=
cel.dev/expr v0.25.3 h1:A2jO8jwOugrrovveCWfj0KEZOfqiLgAcwjpHPhzIGw0=
cel.dev/expr v0.25.3/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4=
code.gitea.io/sdk/gitea v0.25.1 h1:yywxWwoV+SdjHtbC6unBiXojWdZOtoHuGhEazEXeWuE=
code.gitea.io/sdk/gitea v0.25.1/go.mod h1:uDFWYBU8dgZsgOHwe6C/6olxvf8FHguNB3wW1i83fgg=
github.com/42wim/httpsig v1.2.4 h1:mI5bH0nm4xn7K18fo1K3okNDRq8CCJ0KbBYWyA6r8lU=
github.com/42wim/httpsig v1.2.4/go.mod h1:yKsYfSyTBEohkPik224QPFylmzEBtda/kjyIAJjh3ps=
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
github.com/ProtonMail/go-crypto v1.4.1 h1:9RfcZHqEQUvP8RzecWEUafnZVtEvrBVL9BiF67IQOfM=
github.com/ProtonMail/go-crypto v1.4.1/go.mod h1:e1OaTyu5SYVrO9gKOEhTc+5UcXtTUa+P3uLudwcgPqo=
github.com/a-h/templ v0.3.1020/go.mod h1:A2DlK61v+K+NRoGnhmYbNYVmtYHcFO5/AisMvBdDxTM=
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8=
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be/go.mod h1:ySMOLuWl6zY27l47sB3qLNK6tF2fkHG55UZxx8oIVo4=
github.com/antithesishq/antithesis-sdk-go v0.8.0 h1:bVV5ZAuwaREn4klRSJusYaA+A7NXq8Qi9C/knCaQ2N4=
@@ -24,7 +20,6 @@ github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYW
github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw=
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio=
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs=
github.com/bwesterb/go-ristretto v1.2.4/go.mod h1:fUIoIZaG73pV5biE2Blr2xEzDoMj7NFEuV9ekS419A0=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/cloudflare/circl v1.6.5 h1:O64F26HEqNhznd/hrC5KZXVKYuKM2rx4deZDTc4ihQA=
@@ -33,8 +28,6 @@ github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG
github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M=
github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE=
github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk=
github.com/containerd/typeurl/v2 v2.2.0/go.mod h1:8XOOxnyatxSWuG8OfsZXVnAF4iZfedjS/8UHSPJnX4g=
github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davidmz/go-pageant v1.0.2 h1:bPblRCh5jGU+Uptpz6LgMZGD5hJoOt7otgT454WvHn0=
@@ -68,11 +61,10 @@ github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/go-quicktest/qt v1.101.0/go.mod h1:14Bz/f7NwaXPtdYEgzsx46kqSxVwTbzVZsDC26tQJow=
github.com/go-telegram/bot v1.25.0 h1:C072msZtr+GjJiQsX/UJLirz+jzSNZVWkckxWufR7Ww=
github.com/go-telegram/bot v1.25.0/go.mod h1:i2TRs7fXWIeaceF3z7KzsMt/he0TwkVC680mvdTFYeM=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/codesearch v1.3.0-rc.1 h1:vSFGuF5wS3sjimuLzqPG+PGjWQ9VvEtPFbxdZD7YuuQ=
github.com/google/codesearch v1.3.0-rc.1/go.mod h1:hKdpx7wOsvk2WLT/D6NLPxFeLT8jKCehZu21JpA2rIY=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
@@ -84,7 +76,6 @@ github.com/google/go-querystring v1.2.0 h1:yhqkPbu2/OH+V9BfpCVPZkNmUXhb2gBxJArfh
github.com/google/go-querystring v1.2.0/go.mod h1:8IFJqpSRITyJ8QhQ13bmbeMBDfmeEJZD5A0egEOmkqU=
github.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=
github.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=
github.com/google/go-tpm-tools v0.3.13-0.20230620182252-4639ecce2aba/go.mod h1:EFYHy8/1y2KfgTAsx7Luu7NGhoxtuVHnNo8jE7FikKc=
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo=
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
@@ -112,15 +103,10 @@ github.com/minio/highwayhash v1.0.4 h1:asJizugGgchQod2ja9NJlGOWq4s7KsAWr5XUc9Clg
github.com/minio/highwayhash v1.0.4/go.mod h1:GGYsuwP/fPD6Y9hMiXuapVvlIUEhFhMTh0rxU3ik1LQ=
github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=
github.com/moby/moby/api v1.55.0 h1:2/sexvQyqIWS8pRSCFddBfpW2qE7vR7FCL+vN8pxwMc=
github.com/moby/moby/api v1.55.0/go.mod h1:+RQ6wluLwtYaTd1WnPLykIDPekkuyD/ROWQClE83pzs=
github.com/moby/moby/api v1.56.0 h1:GQzua3NA599ASSIICx0iFgiJeO9YkdDARvQsm23ZZuQ=
github.com/moby/moby/api v1.56.0/go.mod h1:sZ+THbVWkjOmBPPfbnzdD/G1LuIexWhqlSHHPTDQ1Uk=
github.com/moby/moby/client v0.5.1 h1:tYNaJno4c0HXz12y5BiqEDy0rVTYkWzI26lGvnTMiJw=
github.com/moby/moby/client v0.5.1/go.mod h1:odLstlZ6uSnfvAgVxMpvgmb8SUdd+siH2T0GBuxVAlM=
github.com/moby/moby/client v0.6.0 h1:AJjEB21QPbXSXjDsZorFBoDZPhMrfbpaPLgSMAW9Bgs=
github.com/moby/moby/client v0.6.0/go.mod h1:OCo00wNRyA3m4lmJ228W3JbyCN4ZNNYjpOXiJydBdcQ=
github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc=
github.com/nats-io/jwt/v2 v2.8.2 h1:XXRgB60MSTnqsRwejQurVDs/hcv2dkt+86GjI+I/bMc=
github.com/nats-io/jwt/v2 v2.8.2/go.mod h1:Ag/56sq9OblL4JgdYufDd16Egb17Kr/8WwwuO/forVc=
github.com/nats-io/nats-server/v2 v2.14.6 h1:dHjEHa49lUTxIb5jrsk5kz/AmOyOQ4T9ti8djcBumDQ=
@@ -146,13 +132,10 @@ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/russross/blackfriday v1.6.0/go.mod h1:ti0ldHuxg49ri4ksnFxlkCfN+hvslNlmVHqNRXXJNAY=
github.com/samcharles93/ai-sdk v0.1.32 h1:rfBpWUOADuRTaq2kyCnMjdhtlFfaqUbsyL5DbIluqmA=
github.com/samcharles93/ai-sdk v0.1.32/go.mod h1:u4zrQ9/Q58L5mNEut4bNQ1ks+RCKq71LN5EDz2N/0Zk=
github.com/santhosh-tekuri/jsonschema/v5 v5.3.1/go.mod h1:uToXkOrWAZ6/Oc07xWQrPOhJotwFIyu2bBVN41fcDUY=
github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw=
github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
@@ -180,12 +163,8 @@ golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPh
golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8=
golang.org/x/crypto v0.56.0 h1:GUh5Ii4J5jtcseSMiRqr1jXCNHoxjeV9Fmekc2oLy6Y=
golang.org/x/crypto v0.56.0/go.mod h1:OMW5y6CY9l38uPLmxU6l6pwcXp1obtLo3e6gT7gQR2I=
golang.org/x/exp v0.0.0-20240823005443-9b4947da3948 h1:kx6Ds3MlpiUHKj7syVnbp57++8WpuKPcR5yjLBjvLEA=
golang.org/x/exp v0.0.0-20240823005443-9b4947da3948/go.mod h1:akd2r19cwCdwSwWeIdzYQGa/EZZyqcOdwWiwj5L5eKQ=
golang.org/x/exp v0.0.0-20260824195058-e88cd73687aa h1:QSyA8ishJCyT21kER9KwNt0b7BM3iRK4x9QXhjN5Fdk=
golang.org/x/exp v0.0.0-20260824195058-e88cd73687aa/go.mod h1:zeBbvyFKDaLwa7CH/zI8KXt7gTl14SF7sO08Pl5jBCM=
golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk=
golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=
golang.org/x/mod v0.39.0 h1:UF5zwQdCRRUpHfyPwr7d4UrGiVeldIsogtzWVnczL74=
golang.org/x/mod v0.39.0/go.mod h1:bvIbwjQ0HUFFf5AKukeeYQG4ZBUG9yxQbR9aEweIwYY=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
@@ -211,23 +190,16 @@ golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE=
golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=
golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI=
golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo=
golang.org/x/tools/go/expect v0.1.1-deprecated/go.mod h1:eihoPOH+FgIqa3FpoTwguz/bVUSGBlGQU67vpBeOrBY=
golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated/go.mod h1:RVAQXBGNv1ib0J382/DPCRS/BPnsGebyM1Gj5VSDpG8=
google.golang.org/genproto/googleapis/api v0.0.0-20240826202546-f6391c0de4c7 h1:YcyjlL1PRr2Q17/I0dPk2JmYS5CDXfcdb2Z3YRioEbw=
google.golang.org/genproto/googleapis/api v0.0.0-20240826202546-f6391c0de4c7/go.mod h1:OCdP9MfskevB/rbYvHTsXTtKC+3bHWajPdoKgjcYkfo=
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
google.golang.org/genproto/googleapis/api v0.0.0-20260904194346-d0f1323225a4 h1:NCe/UiklGd/9xjT+ROBVhJ1kf6TRQaFedsR+z7u1gvo=
google.golang.org/genproto/googleapis/api v0.0.0-20260904194346-d0f1323225a4/go.mod h1:fJ2lYaWjqNknJyQBOCd0fA3HnEElJqGplH71a2txi+g=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240903143218-8af14fe29dc1 h1:pPJltXNxVzT4pK9yD8vR9X75DaWYYmLGMsEvBfFQZzQ=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240903143218-8af14fe29dc1/go.mod h1:UqMtugtsSgubUsoxbuAoiCXvqvErP7Gf0so0mK9tHxU=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260904194346-d0f1323225a4 h1:5t+ZydAFj5kGVLrgCvLmpmCf9ylGRd64hpEronfRaws=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260904194346-d0f1323225a4/go.mod h1:DjtHYE8FKJLivXcBEjGwndXfIC23G0VpXiXKqG179uA=
google.golang.org/grpc v1.83.1/go.mod h1:kDyl6SKsiHKt0uylY5gtn5cEjkrIOhQOGDgIc4JGwzQ=
google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU=
google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8=
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+39 -87
View File
@@ -23,7 +23,6 @@ import (
"github.com/samcharles93/ai-sdk/runtime"
"github.com/samcharles93/archie-core/internal/agentexec"
channelruntime "github.com/samcharles93/archie-core/internal/channels"
"github.com/samcharles93/archie-core/internal/channels/email"
"github.com/samcharles93/archie-core/internal/channels/webhook"
@@ -48,6 +47,7 @@ import (
"github.com/samcharles93/archie-core/internal/infrastructure/modelcatalog"
"github.com/samcharles93/archie-core/internal/infrastructure/sessioncurator"
"github.com/samcharles93/archie-core/internal/infrastructure/skillcurator"
"github.com/samcharles93/archie-core/internal/infrastructure/taskactions"
"github.com/samcharles93/archie-core/internal/logging"
"github.com/samcharles93/archie-core/internal/memory"
"github.com/samcharles93/archie-core/internal/plugin"
@@ -128,7 +128,6 @@ type boot struct {
chatController *gateway.StoreTaskController
defaultChatIdentity string
updateService *releaseupdate.Service
webRouter *gateway.Router
startGateways []func()
capabilityHost *plugin.Host
@@ -273,6 +272,12 @@ func (b *boot) openStores(ctx context.Context) error {
log.Error("close store", "err", err)
}
})
// The conversation store is Gateway-owned data, but Phase 1 keeps the
// daemon's own Telegram/email routers and the session-memory curator
// reading the same SQLite file directly (Messaging extraction is
// Phase 4). Both processes opening the same file is the accepted
// Phase 1 shape; remote consumers of the conversation store arrive
// when a process that cannot open the file needs it.
chatSessionStore, err := makeTelegramSessionStore(cfg) //nolint:contextcheck // the session store opener takes no context by design; its schema init must complete at boot regardless of cancellation
if err != nil {
log.Error("open conversation store", "path", conversationDBPath(cfg.DBPath), "err", err)
@@ -481,92 +486,23 @@ func (b *boot) setupContainers(ctx context.Context) func() {
// setupLLMAndChat wires the runtime, tool registry, model management,
// personas and the dashboard's chat service.
func (b *boot) setupLLMAndChat(ctx context.Context) {
cfg, log := b.cfg, b.log
func (b *boot) setupLLMAndChat() error {
cfg := b.cfg
// ── LLM runtime ──────────────────────────────────────────────────
// Created before gateways so the LLMResponder can be wired into the
// Telegram router for non-command message processing.
providers := executionProviders(cfg)
b.llm = agentexec.NewRuntime(providers)
b.toolReg = tools.NewRegistry()
chatModels := newChatModelManager(cfg.Models, cfg.Chat.Models, b.catalogModels)
chatModels.ApplyModelCatalog(b.catalog)
b.chatModels = chatModels
// Telegram/email keep their own in-process routers rather than going
// through ChatContract: their streaming responder is a callback, and
// ChatContract's wire-safe interface can't carry one.
b.setupChatRuntime(cfg)
// ── Persona registry ─────────────────────────────────────────────
b.personas = gateway.NewPersonaRegistry(gateway.DefaultPersonas())
profiles, defaultChatIdentity := chatTaskProfiles(cfg)
var chatTasks gateway.TaskCreator
if len(profiles) > 0 {
chatTasks = gateway.NewStoreTaskCreatorForProfiles(
chatTaskWriterAdapter{enqueue: b.st.EnqueueChatTask},
profiles,
)
contract, cleanup, err := composeChatContract(cfg.Services.Gateway)
if err != nil {
return err
}
b.chatTasks = chatTasks
b.defaultChatIdentity = defaultChatIdentity
chatController := gateway.NewStoreTaskController(chatTaskControllerAdapter{
taskByID: b.st.TaskByID,
requeue: b.st.Requeue,
transition: b.st.Transition,
})
b.chatController = chatController
b.updateService = makeUpdateService(telegramSetup{Cfg: config.NewHolder(cfg)})
b.addCleanup(cleanup)
b.web.Chat = &webui.ChatService{Contract: contract, Updates: b.updateService}
b.web.WorkRequests = b.chatTasks
// The dashboard is another gateway, not a second chat implementation. It
// shares the router, session history, model selection, personas and LLM
// responder with Telegram while using a stable browser channel id.
b.webRouter = gateway.NewRouter(b.st, nil, "web")
b.webRouter.Version = fmt.Sprintf("Archie\nGateway: %s\nRuntime: %s", gatewayVersion, runtimeVersion)
if cfg.Chat.Telegram.Token != (secret.SecretRef{}) || cfg.Chat.Telegram.TokenEnv != "" {
b.webRouter.Restart = func(context.Context) error {
if b.restartTelegram == nil {
return fmt.Errorf("telegram gateway is not ready")
}
return b.restartTelegram()
}
}
b.webRouter.Models = b.chatModels
if b.updateService != nil {
b.webRouter.Updates = b.updateService
}
b.webRouter.Personas = b.personas
b.webRouter.InitSessions(b.chatSessionStore)
configureTaskCommands(b.webRouter, b.chatTasks, b.chatController, chatTaskListerAdapter{tasks: b.st.Tasks}, b.defaultChatIdentity)
webSetup := telegramSetup{
Cfg: config.NewHolder(cfg), St: b.st, LLM: b.llm, ChatModels: b.chatModels, ToolReg: b.toolReg,
Personas: b.personas, ChatTasks: b.chatTasks, ChatController: b.chatController,
ChatTaskLister: chatTaskListerAdapter{tasks: b.st.Tasks},
ChatTaskLogs: chatTaskLogReaderAdapter{
tasks: b.st.TaskByID,
taskLogs: b.taskLogs,
},
ChatTaskActor: chatTaskActorAdapter{
tasks: b.st.TaskByID,
handler: b.web.Handler(),
token: func() string { return b.web.Token },
},
DefaultChatIdentity: b.defaultChatIdentity, SessionStore: b.chatSessionStore,
Bus: b.bus, Log: log, Secrets: b.secrets,
}
b.webRouter.LLM, b.webRouter.LLMStream = makeChatLLMResponder(ctx, "web", webSetup, b.chatSessionStore, b.webRouter)
b.webRouter.Titles = newChatTitleGenerator(webSetup)
b.webRouter.Log = log
b.web.Chat = &webui.ChatService{
Router: b.webRouter, Sessions: b.chatSessionStore,
Turns: gateway.NewTurns(log),
Models: b.chatModels, Personas: b.personas,
}
if b.updateService != nil {
b.web.Chat.Updates = b.updateService
}
// Operator readiness probes: wired once the chat surface exists so the
// gateway probe can read the real session store and model manager.
b.setupReadinessProbes()
return nil
}
// setupGateways assembles the Telegram, email and webhook gateways. It
@@ -586,9 +522,12 @@ func (b *boot) setupGateways(ctx context.Context, cfgPath, overlayPath string) b
taskLogs: b.taskLogs,
},
ChatTaskActor: chatTaskActorAdapter{
tasks: b.st.TaskByID,
handler: b.web.Handler(),
token: func() string { return b.web.Token },
contract: func() gateway.ChatContract {
if b.web != nil && b.web.Chat != nil {
return b.web.Chat.Contract
}
return nil
}(),
},
DefaultChatIdentity: b.defaultChatIdentity, SessionStore: b.chatSessionStore, Updates: b.updateService,
Secrets: b.secrets,
@@ -888,6 +827,17 @@ func (b *boot) registerNATSRPC() error {
return err
}
b.addCleanup(unsubscribeAgentEvents)
// The standalone Gateway forwards operator task actions to the daemon
// over NATS. The daemon owns execution cancellation, retry policy,
// forge closure and event persistence; the responder applies the same
// taskactions.Service the dashboard uses.
unsubscribeTaskActions, err := taskactions.Register(coreConn, b.taskActions(), log)
if err != nil {
log.Error("gateway task action register failed", "err", err)
return err
}
b.addCleanup(unsubscribeTaskActions)
return nil
}
@@ -914,7 +864,9 @@ func (b *boot) setupMemory() error {
b.memManager = memManager
// The dashboard is built before memory exists, so it is wired in here
// rather than at construction.
b.web.Memory = memManager
if b.web != nil {
b.web.Memory = memManager
}
if err := memManager.Initialize("daemon"); err != nil {
log.Warn("memory manager initialize", "err", err)
+30
View File
@@ -0,0 +1,30 @@
package archied
import (
"fmt"
"strings"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/gateway"
"github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc"
)
// composeChatContract dials the standalone archie-gateway, the sole owner of
// ChatContract.
func composeChatContract(settings config.ServiceConnection, options ...grpc.DialOption) (gateway.ChatContract, func(), error) {
if strings.TrimSpace(settings.Target) == "" {
return nil, nil, fmt.Errorf("services.gateway.target is required")
}
// Deployments that put the Gateway on a separate trust boundary supply
// their own transport credentials through options; the default must be
// usable without manufacturing a certificate in the config loader.
opts := append([]grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}, options...)
conn, err := grpc.NewClient(settings.Target, opts...)
if err != nil {
return nil, nil, fmt.Errorf("create gateway client: %w", err)
}
return gatewayrpc.NewClient(conn), func() { _ = conn.Close() }, nil
}
+96
View File
@@ -0,0 +1,96 @@
package archied
import (
"context"
"net"
"testing"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"google.golang.org/grpc/test/bufconn"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/gateway"
"github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc"
)
func TestComposeChatContractRejectsInvalidSettings(t *testing.T) {
for _, tt := range []struct {
name string
settings config.ServiceConnection
}{
{name: "missing target", settings: config.ServiceConnection{}},
{name: "blank target", settings: config.ServiceConnection{Target: " \t\n"}},
} {
t.Run(tt.name, func(t *testing.T) {
chat, cleanup, err := composeChatContract(tt.settings)
if cleanup != nil {
t.Cleanup(cleanup)
}
if err == nil {
t.Fatal("invalid settings were accepted")
}
if chat != nil || cleanup != nil {
t.Fatal("invalid settings published an adapter or cleanup")
}
})
}
}
func TestComposeChatContractRemoteAndCleanup(t *testing.T) {
listener := bufconn.Listen(1024 * 1024)
server := grpc.NewServer()
gatewayrpc.RegisterServer(server, compositionChat{snapshot: gateway.ChatSnapshot{ActiveModel: "remote-model"}})
serveDone := make(chan error, 1)
go func() { serveDone <- server.Serve(listener) }()
t.Cleanup(func() {
server.Stop()
_ = listener.Close()
if err := <-serveDone; err != nil {
t.Errorf("serve chat: %v", err)
}
})
chat, cleanup, err := composeChatContract(
config.ServiceConnection{Target: "passthrough:///chat"},
grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) {
return listener.DialContext(ctx)
}),
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
if err != nil {
t.Fatal(err)
}
if cleanup == nil {
t.Fatal("remote composition returned no cleanup")
}
t.Cleanup(cleanup)
if _, ok := chat.(*gatewayrpc.Client); !ok {
t.Fatalf("remote composition returned %T", chat)
}
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
defer cancel()
snapshot, err := chat.Snapshot(ctx)
if err != nil {
t.Fatal(err)
}
if snapshot.ActiveModel != "remote-model" {
t.Fatalf("Snapshot used wrong adapter: ActiveModel = %q", snapshot.ActiveModel)
}
cleanup()
if _, err := chat.Snapshot(ctx); status.Code(err) != codes.Canceled {
t.Fatalf("Snapshot after cleanup: code = %v, want Canceled; error = %v", status.Code(err), err)
}
}
type compositionChat struct {
gateway.ChatContract
snapshot gateway.ChatSnapshot
}
func (c compositionChat) Snapshot(context.Context) (gateway.ChatSnapshot, error) {
return c.snapshot, nil
}
+112
View File
@@ -0,0 +1,112 @@
package archied
import (
"context"
"fmt"
"net"
"os"
"time"
natsio "github.com/nats-io/nats.go"
"google.golang.org/grpc"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/gateway"
"github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc"
"github.com/samcharles93/archie-core/internal/infrastructure/taskactions"
"github.com/samcharles93/archie-core/internal/plugin"
)
// GatewayOptions contains process inputs for the standalone Gateway.
type GatewayOptions struct {
Config string
Overlay string
Listen string
}
// RunGateway owns conversation persistence, model runtime and tool-provider
// lifecycles. Task-store adapters continue to access the existing task database
// until the State Store Service extraction; no task data is relocated.
func RunGateway(ctx context.Context, options GatewayOptions) error {
b := newBootstrap()
defer b.cleanup()
if err := b.loadConfig(ctx, options.Config, options.Overlay, false); err != nil {
return err
}
b.log = b.log.With("component", "gateway")
if err := b.openStores(ctx); err != nil {
return err
}
b.loadCatalog(ctx, options.Config)
if b.cfg.NATS.URL == "" {
return fmt.Errorf("archie-gateway requires nats.url pointing to the daemon's shared NATS server")
}
token, err := configuredNATSToken(b.cfg.NATS, os.Getenv)
if err != nil {
return err
}
nc, err := natsio.Connect(b.cfg.NATS.URL, natsio.Token(token))
if err != nil {
return fmt.Errorf("connect gateway task actions: %w", err)
}
b.addCleanup(nc.Close)
contract, err := b.startGatewayRuntime(ctx, taskactions.Client{Conn: nc, Timeout: 30 * time.Second})
if err != nil {
return err
}
host, _, err := net.SplitHostPort(options.Listen)
if err != nil || !net.ParseIP(host).IsLoopback() {
return fmt.Errorf("gateway listen address must use a loopback IP; use a secured tunnel for remote access")
}
listener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", options.Listen)
if err != nil {
return fmt.Errorf("listen for gateway: %w", err)
}
defer listener.Close()
b.log.Info("archie-gateway running", "addr", listener.Addr().String())
return serveGateway(ctx, listener, contract)
}
func (b *boot) startGatewayRuntime(ctx context.Context, actor gateway.ChatTaskActor) (gateway.ChatContract, error) {
b.bus = events.NewBus()
b.addCleanup(b.bus.Close)
b.capabilityHost = plugin.NewHost()
contract := b.setupGatewayChat(ctx, actor)
// Memory is opened with its own long-lived context inside (matching the
// daemon path via setupMemoryAll): shutdown of the file-backed provider
// outlives the boot context by design, so the legacy manager wires itself
// with a background context rather than the gateway's boot ctx.
if err := b.setupMemory(); err != nil { //nolint:contextcheck // setupMemory owns its lifecycle contexts, matching the daemon's setupMemoryAll
return nil, err
}
if err := b.registerTools(); err != nil {
return nil, err
}
b.registerStandaloneTools()
b.addCleanup(shutdownCapabilityHost(b.capabilityHost, b.log))
if err := b.capabilityHost.Start(ctx); err != nil {
return nil, fmt.Errorf("start gateway tool providers: %w", err)
}
for _, skipped := range b.providerRegistry.Skipped() {
b.log.Warn("gateway tool provider unavailable", "provider", skipped.ID, "err", skipped.Err)
}
return contract, nil
}
func serveGateway(ctx context.Context, listener net.Listener, contract gateway.ChatContract) error {
server := grpc.NewServer()
gatewayrpc.RegisterServer(server, contract)
serveErr := make(chan error, 1)
go func() { serveErr <- server.Serve(listener) }()
select {
case <-ctx.Done():
// A client can keep a streaming RPC open indefinitely. Allow draining,
// then force cancellation before closing the session store and tools.
timer := time.AfterFunc(10*time.Second, server.Stop)
server.GracefulStop()
timer.Stop()
return nil
case err := <-serveErr:
return err
}
}
+77
View File
@@ -0,0 +1,77 @@
package archied
import (
"context"
"fmt"
"github.com/samcharles93/archie-core/internal/agentexec"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/gateway"
"github.com/samcharles93/archie-core/internal/tools"
)
// setupChatRuntime wires the model runtime, tool registry, persona registry,
// chat task creator/controller, default chat identity and the release-update
// service. Both the daemon (its own Telegram/email routers) and the standalone
// Gateway (the web router) build through this one constructor so the two
// processes cannot diverge.
func (b *boot) setupChatRuntime(cfg config.Config) {
// ── LLM runtime ──────────────────────────────────────────────────
// Created before gateways so the LLMResponder can be wired into the
// Telegram router for non-command message processing.
providers := executionProviders(cfg)
b.llm = agentexec.NewRuntime(providers)
b.toolReg = tools.NewRegistry()
chatModels := newChatModelManager(cfg.Models, cfg.Chat.Models, b.catalogModels)
chatModels.ApplyModelCatalog(b.catalog)
b.chatModels = chatModels
// ── Persona registry ─────────────────────────────────────────────
b.personas = gateway.NewPersonaRegistry(gateway.DefaultPersonas())
profiles, defaultChatIdentity := chatTaskProfiles(cfg)
var chatTasks gateway.TaskCreator
if len(profiles) > 0 {
chatTasks = gateway.NewStoreTaskCreatorForProfiles(
chatTaskWriterAdapter{enqueue: b.st.EnqueueChatTask},
profiles,
)
}
b.chatTasks = chatTasks
b.defaultChatIdentity = defaultChatIdentity
b.chatController = gateway.NewStoreTaskController(chatTaskControllerAdapter{
taskByID: b.st.TaskByID,
requeue: b.st.Requeue,
transition: b.st.Transition,
})
b.updateService = makeUpdateService(telegramSetup{Cfg: config.NewHolder(cfg)})
}
// setupGatewayChat is the sole production constructor of the local contract.
// Frontends use its gRPC representation; only this service owns the router.
func (b *boot) setupGatewayChat(ctx context.Context, actor gateway.ChatTaskActor) gateway.ChatContract {
b.setupChatRuntime(b.cfg)
cfg := b.cfg
router := gateway.NewRouter(b.st, nil, "web")
router.Version = fmt.Sprintf("Archie\nGateway: %s\nRuntime: %s", gatewayVersion, runtimeVersion)
router.Models = b.chatModels
router.Personas = b.personas
router.Updates = b.updateService
router.InitSessions(b.chatSessionStore)
configureTaskCommands(router, b.chatTasks, b.chatController, chatTaskListerAdapter{tasks: b.st.Tasks}, b.defaultChatIdentity)
setup := telegramSetup{
Cfg: config.NewHolder(cfg), St: b.st, LLM: b.llm, ChatModels: b.chatModels, ToolReg: b.toolReg,
Personas: b.personas, ChatTasks: b.chatTasks, ChatController: b.chatController,
ChatTaskLister: chatTaskListerAdapter{tasks: b.st.Tasks},
ChatTaskLogs: chatTaskLogReaderAdapter{tasks: b.st.TaskByID, taskLogs: b.taskLogs},
ChatTaskActor: actor, DefaultChatIdentity: b.defaultChatIdentity, SessionStore: b.chatSessionStore,
Bus: b.bus, Log: b.log, Secrets: b.secrets,
}
router.LLM, router.LLMStream = makeChatLLMResponder(ctx, "web", setup, b.chatSessionStore, router)
router.Titles = newChatTitleGenerator(setup)
router.Log = b.log
return &gateway.LocalChatAdapter{
Router: router, Sessions: b.chatSessionStore, Turns: gateway.NewTurns(b.log),
Models: b.chatModels, Personas: b.personas, TaskActor: actor,
}
}
+9 -64
View File
@@ -5,7 +5,6 @@
package archied
import (
"bytes"
"context"
"crypto/sha256"
"encoding/json"
@@ -13,8 +12,6 @@ import (
"fmt"
"log/slog"
"net"
"net/http"
"net/http/httptest"
"os"
"os/signal"
"path/filepath"
@@ -353,7 +350,7 @@ func parseArgs() (runArgs, bool) {
return args, false
}
func Run() int {
func Run() int { //nolint:cyclop // the composition root's setup sequence is deliberately flat and sequential
args, exit := parseArgs()
if exit {
return 0
@@ -392,7 +389,9 @@ func Run() int {
return 1
}
b.setupLLMAndChat(ctx)
if err := b.setupLLMAndChat(); err != nil {
return 1
}
if !b.setupGateways(ctx, args.cfgPath, args.overlayPath) {
return 1
}
@@ -660,72 +659,18 @@ func (a chatTaskLogReaderAdapter) ReadChatTaskLogs(
}, nil
}
// chatTaskActorAdapter executes operator actions on a task via the same
// action path the dashboard uses, ensuring chat and webui cannot diverge.
// It enforces identity scoping so an identity cannot mutate another
// identity's tasks.
// chatTaskActorAdapter sends messaging actions through the Gateway boundary.
type chatTaskActorAdapter struct {
tasks func(context.Context, int64) (*store.Task, error)
handler http.Handler
token func() string
contract gateway.ChatContract
}
func (a chatTaskActorAdapter) ApplyChatTaskAction(
ctx context.Context, identity string, taskID int64, action taskstate.Action,
) (gateway.TaskActionResult, error) {
if a.tasks == nil || a.handler == nil {
return gateway.TaskActionResult{}, fmt.Errorf("task actions are not configured")
if a.contract == nil {
return gateway.TaskActionResult{}, gateway.ErrChatCapabilityUnavailable
}
task, err := a.tasks(ctx, taskID)
if err != nil {
return gateway.TaskActionResult{}, err
}
if task == nil {
return gateway.TaskActionResult{}, fmt.Errorf("task %d not found", taskID)
}
// Match the filter chatTaskListerAdapter and chatTaskLogReaderAdapter apply:
// a model bound to one identity must not mutate another identity's tasks,
// and tasks with no identity (forge-sourced) are not actionable through a
// chat tool at all — they belong to the daemon, not a particular identity.
if task.Identity != identity {
return gateway.TaskActionResult{}, fmt.Errorf("task %d belongs to %q, not %q", taskID, task.Identity, identity)
}
if err := taskstate.CheckAction(task.Status, action); err != nil {
return gateway.TaskActionResult{}, err
}
body, err := json.Marshal(map[string]any{"action": string(action)})
if err != nil {
return gateway.TaskActionResult{}, fmt.Errorf("marshal action request: %w", err)
}
req := httptest.NewRequestWithContext(
ctx, http.MethodPost,
fmt.Sprintf("/api/tasks/%d/action", taskID),
bytes.NewReader(body),
)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Archie-CSRF", "1")
if a.token != nil {
if tok := a.token(); tok != "" {
req.Header.Set("Authorization", "Bearer "+tok)
}
}
rec := httptest.NewRecorder()
a.handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
errMsg := strings.TrimSpace(rec.Body.String())
if errMsg == "" {
errMsg = fmt.Sprintf("HTTP %d", rec.Code)
}
return gateway.TaskActionResult{}, fmt.Errorf("action %s on task %d failed: %s", action, taskID, errMsg)
}
return gateway.TaskActionResult{
TaskID: taskID,
Action: string(action),
Message: fmt.Sprintf("Applied %s to task %d.", action, taskID),
}, nil
return a.contract.ApplyTaskAction(ctx, identity, taskID, action)
}
func chatTaskProfiles(cfg config.Config) ([]gateway.TaskProfile, string) {
+3 -3
View File
@@ -61,14 +61,14 @@ func channelStates(m *channelruntime.Manager) []readiness.ChannelState {
// sessionCount returns the number of gateway sessions. An unwired chat
// surface returns 0 rather than reporting a false failure.
func sessionCount(ctx context.Context, chat *webui.ChatService) int {
if chat == nil || chat.Sessions == nil {
if chat == nil || chat.Contract == nil {
return 0
}
sessions, err := chat.Sessions.List(ctx)
snapshot, err := chat.Contract.Snapshot(ctx)
if err != nil {
return 0
}
return len(sessions)
return len(snapshot.Sessions)
}
// diskProbePath resolves the filesystem the readiness disk probe inspects:
+5 -2
View File
@@ -97,8 +97,11 @@ func TestSetupReadinessProbes_WiresEverySubsystem(t *testing.T) {
Cfg: config.NewHolder(cfg),
Channels: channelruntime.NewManager([]channelruntime.Descriptor{{ID: "telegram", Name: "Telegram", Configured: true}}),
Chat: &webui.ChatService{
Sessions: gateway.NewSessionStoreMemory(),
Models: newChatModelManager(map[string]string{"chat": "openai/gpt-4o"}, nil),
Contract: &gateway.LocalChatAdapter{
Router: &gateway.Router{},
Sessions: gateway.NewSessionStoreMemory(),
Models: newChatModelManager(map[string]string{"chat": "openai/gpt-4o"}, nil),
},
},
},
chatModels: newChatModelManager(map[string]string{"chat": "openai/gpt-4o"}, nil),
@@ -2,16 +2,47 @@ package archied
import (
"context"
"fmt"
"log/slog"
"path/filepath"
"strings"
"testing"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/gateway"
"github.com/samcharles93/archie-core/internal/store"
"github.com/samcharles93/archie-core/internal/taskstate"
"github.com/samcharles93/archie-core/internal/webui"
)
// testTaskActor formats taskactions.Service's result the same way the real
// NATS actor (infrastructure/taskactions.Client) does, so this test exercises
// the shared service through the same chatTaskActorAdapter → LocalChatAdapter
// → ChatTaskActor chain production traffic uses.
type testTaskActor struct{ b *boot }
func (a testTaskActor) ApplyChatTaskAction(
ctx context.Context, identity string, taskID int64, action taskstate.Action,
) (gateway.TaskActionResult, error) {
if err := a.b.taskActions().Apply(ctx, &identity, taskID, action); err != nil {
return gateway.TaskActionResult{}, err
}
return gateway.TaskActionResult{
TaskID: taskID,
Action: string(action),
Message: fmt.Sprintf("Applied %s to task %d.", action, taskID),
}, nil
}
func newChatTaskActorForTest(t *testing.T, st store.TaskStore, cfg config.Config) chatTaskActorAdapter {
t.Helper()
b := &boot{
st: st,
cfg: cfg,
log: slog.Default(),
}
return chatTaskActorAdapter{contract: &gateway.LocalChatAdapter{TaskActor: testTaskActor{b}}}
}
func TestChatTaskActorAdapterCrossIdentityRefused(t *testing.T) {
ctx := context.Background()
st, err := store.Open(ctx, filepath.Join(t.TempDir(), "tasks.db"))
@@ -28,12 +59,7 @@ func TestChatTaskActorAdapterCrossIdentityRefused(t *testing.T) {
t.Fatal(err)
}
srv := &webui.Server{Store: st, Cfg: config.NewHolder(config.Config{})}
adapter := chatTaskActorAdapter{
tasks: st.TaskByID,
handler: srv.Handler(),
token: func() string { return srv.Token },
}
adapter := newChatTaskActorForTest(t, st, config.Config{})
tests := []struct {
name string
@@ -88,12 +114,7 @@ func TestChatTaskActorAdapterRefusesDisallowedStateAction(t *testing.T) {
}
t.Cleanup(func() { _ = st.Close() })
srv := &webui.Server{Store: st, Cfg: config.NewHolder(config.Config{})}
adapter := chatTaskActorAdapter{
tasks: st.TaskByID,
handler: srv.Handler(),
token: func() string { return srv.Token },
}
adapter := newChatTaskActorForTest(t, st, config.Config{})
tests := []struct {
name string
@@ -170,12 +191,7 @@ func TestChatTaskActorAdapterTaskNotFound(t *testing.T) {
}
t.Cleanup(func() { _ = st.Close() })
srv := &webui.Server{Store: st, Cfg: config.NewHolder(config.Config{})}
adapter := chatTaskActorAdapter{
tasks: st.TaskByID,
handler: srv.Handler(),
token: func() string { return srv.Token },
}
adapter := newChatTaskActorForTest(t, st, config.Config{})
_, err = adapter.ApplyChatTaskAction(ctx, "archie", 999999, taskstate.ActionAbandon)
if err == nil {
@@ -247,12 +263,7 @@ func TestChatTaskActorAdapterAppliesActionsToStore(t *testing.T) {
}
t.Cleanup(func() { _ = st.Close() })
srv := &webui.Server{Store: st, Cfg: config.NewHolder(config.Config{MaxRetries: 3})}
adapter := chatTaskActorAdapter{
tasks: st.TaskByID,
handler: srv.Handler(),
token: func() string { return srv.Token },
}
adapter := newChatTaskActorForTest(t, st, config.Config{MaxRetries: 3})
task, err := st.EnqueueChatTask(ctx, "acme", "widget", "actionable task", "", "", "archie")
if err != nil {
@@ -295,46 +306,12 @@ func TestChatTaskActorAdapterAppliesActionsToStore(t *testing.T) {
}
}
func TestChatTaskActorAdapterWithTokenAuth(t *testing.T) {
func TestChatTaskActorAdapterNilContract(t *testing.T) {
ctx := context.Background()
st, err := store.Open(ctx, filepath.Join(t.TempDir(), "tasks.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = st.Close() })
adapter := chatTaskActorAdapter{contract: nil}
srv := &webui.Server{
Store: st,
Cfg: config.NewHolder(config.Config{MaxRetries: 3}),
Token: "secret-token-12345",
}
adapter := chatTaskActorAdapter{
tasks: st.TaskByID,
handler: srv.Handler(),
token: func() string { return srv.Token },
}
task, err := st.EnqueueChatTask(ctx, "acme", "widget", "auth task", "", "", "archie")
if err != nil {
t.Fatal(err)
}
if err := st.Transition(ctx, task.ID, store.StatusQueued, store.StatusParked, "park"); err != nil {
t.Fatal(err)
}
result, err := adapter.ApplyChatTaskAction(ctx, "archie", task.ID, taskstate.ActionAbandon)
if err != nil {
t.Fatalf("ApplyChatTaskAction with token auth failed: %v", err)
}
if result.TaskID != task.ID {
t.Errorf("result.TaskID = %d, want %d", result.TaskID, task.ID)
}
current, err := st.TaskByID(ctx, task.ID)
if err != nil || current == nil {
t.Fatalf("TaskByID = (%+v, %v)", current, err)
}
if current.Status != store.StatusClosedWontDo {
t.Errorf("status = %q, want %q", current.Status, store.StatusClosedWontDo)
_, err := adapter.ApplyChatTaskAction(ctx, "archie", 1, taskstate.ActionAbandon)
if err == nil {
t.Fatal("expected error for nil contract, got nil")
}
}
+54
View File
@@ -0,0 +1,54 @@
package archied
import (
"context"
"fmt"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/taskactions"
"github.com/samcharles93/archie-core/internal/events"
taskactionstore "github.com/samcharles93/archie-core/internal/infrastructure/taskactions"
)
// taskActions assembles the daemon-owned operator action service. The daemon
// retains execution cancellation, retry policy, forge closure and event
// ownership; the dashboard's webui service and the NATS responder both build
// through the same constructor so the surfaces cannot diverge.
func (b *boot) taskActions() taskactions.Service {
return taskactionstore.NewService(
taskactionstore.Store{TaskStore: b.st},
taskactionstore.MaxRetries(config.NewHolder(b.cfg)),
b.cancelTask,
b.closeIssue,
b.removeTaskLogs,
b.publishEvent,
b.log.Warn,
)
}
func (b *boot) cancelTask(id int64) bool {
if b.d == nil {
return false
}
return b.d.CancelTask(id)
}
func (b *boot) closeIssue(ctx context.Context, owner, repo string, number int, comment string) error {
if b.forgeClient == nil {
return fmt.Errorf("forge is not configured")
}
return b.forgeClient.CloseIssue(ctx, owner, repo, number, comment)
}
func (b *boot) removeTaskLogs(id int64) error {
if b.taskLogs == nil {
return nil
}
return b.taskLogs.Remove(id)
}
func (b *boot) publishEvent(e events.Event) {
if b.bus != nil {
b.bus.Publish(e)
}
}
+2 -1
View File
@@ -426,7 +426,8 @@ type ToolsConfig struct {
// Config is the daemon configuration.
type Config struct {
WorkDir string `toml:"work_dir" yaml:"work_dir"`
Services Services `toml:"services" yaml:"services"`
WorkDir string `toml:"work_dir" yaml:"work_dir"`
// SkillsDir is an optional path to a shared skills directory
// containing .agents/skills/*/SKILL.md files. When set, the
// daemon builds its workflow registry from the skill catalog
+12
View File
@@ -0,0 +1,12 @@
package config
// Services selects contract adapters at application composition time.
type Services struct {
Gateway ServiceConnection `toml:"gateway" yaml:"gateway"`
}
// ServiceConnection is the archie-gateway process's gRPC address. It does not
// register services or start listeners. Changes require a daemon restart.
type ServiceConnection struct {
Target string `toml:"target" yaml:"target"`
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,429 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.6.2
// - protoc (unknown)
// source: gateway/v1/chat.proto
package gatewayv1
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.64.0 or later.
const _ = grpc.SupportPackageIsVersion9
const (
ChatService_Snapshot_FullMethodName = "/gateway.v1.ChatService/Snapshot"
ChatService_GetSession_FullMethodName = "/gateway.v1.ChatService/GetSession"
ChatService_RecentMessages_FullMethodName = "/gateway.v1.ChatService/RecentMessages"
ChatService_RecentTurns_FullMethodName = "/gateway.v1.ChatService/RecentTurns"
ChatService_Route_FullMethodName = "/gateway.v1.ChatService/Route"
ChatService_Stream_FullMethodName = "/gateway.v1.ChatService/Stream"
ChatService_Cancel_FullMethodName = "/gateway.v1.ChatService/Cancel"
ChatService_SetPersona_FullMethodName = "/gateway.v1.ChatService/SetPersona"
ChatService_ApplyTaskAction_FullMethodName = "/gateway.v1.ChatService/ApplyTaskAction"
)
// ChatServiceClient is the client API for ChatService service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type ChatServiceClient interface {
Snapshot(ctx context.Context, in *SnapshotRequest, opts ...grpc.CallOption) (*SnapshotResponse, error)
GetSession(ctx context.Context, in *GetSessionRequest, opts ...grpc.CallOption) (*GetSessionResponse, error)
RecentMessages(ctx context.Context, in *RecentMessagesRequest, opts ...grpc.CallOption) (*RecentMessagesResponse, error)
RecentTurns(ctx context.Context, in *RecentTurnsRequest, opts ...grpc.CallOption) (*RecentTurnsResponse, error)
Route(ctx context.Context, in *RouteRequest, opts ...grpc.CallOption) (*RouteResponse, error)
Stream(ctx context.Context, in *StreamRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[StreamResponse], error)
Cancel(ctx context.Context, in *CancelRequest, opts ...grpc.CallOption) (*CancelResponse, error)
SetPersona(ctx context.Context, in *SetPersonaRequest, opts ...grpc.CallOption) (*SetPersonaResponse, error)
ApplyTaskAction(ctx context.Context, in *ApplyTaskActionRequest, opts ...grpc.CallOption) (*ApplyTaskActionResponse, error)
}
type chatServiceClient struct {
cc grpc.ClientConnInterface
}
func NewChatServiceClient(cc grpc.ClientConnInterface) ChatServiceClient {
return &chatServiceClient{cc}
}
func (c *chatServiceClient) Snapshot(ctx context.Context, in *SnapshotRequest, opts ...grpc.CallOption) (*SnapshotResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(SnapshotResponse)
err := c.cc.Invoke(ctx, ChatService_Snapshot_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *chatServiceClient) GetSession(ctx context.Context, in *GetSessionRequest, opts ...grpc.CallOption) (*GetSessionResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(GetSessionResponse)
err := c.cc.Invoke(ctx, ChatService_GetSession_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *chatServiceClient) RecentMessages(ctx context.Context, in *RecentMessagesRequest, opts ...grpc.CallOption) (*RecentMessagesResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(RecentMessagesResponse)
err := c.cc.Invoke(ctx, ChatService_RecentMessages_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *chatServiceClient) RecentTurns(ctx context.Context, in *RecentTurnsRequest, opts ...grpc.CallOption) (*RecentTurnsResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(RecentTurnsResponse)
err := c.cc.Invoke(ctx, ChatService_RecentTurns_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *chatServiceClient) Route(ctx context.Context, in *RouteRequest, opts ...grpc.CallOption) (*RouteResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(RouteResponse)
err := c.cc.Invoke(ctx, ChatService_Route_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *chatServiceClient) Stream(ctx context.Context, in *StreamRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[StreamResponse], error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
stream, err := c.cc.NewStream(ctx, &ChatService_ServiceDesc.Streams[0], ChatService_Stream_FullMethodName, cOpts...)
if err != nil {
return nil, err
}
x := &grpc.GenericClientStream[StreamRequest, StreamResponse]{ClientStream: stream}
if err := x.ClientStream.SendMsg(in); err != nil {
return nil, err
}
if err := x.ClientStream.CloseSend(); err != nil {
return nil, err
}
return x, nil
}
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
type ChatService_StreamClient = grpc.ServerStreamingClient[StreamResponse]
func (c *chatServiceClient) Cancel(ctx context.Context, in *CancelRequest, opts ...grpc.CallOption) (*CancelResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(CancelResponse)
err := c.cc.Invoke(ctx, ChatService_Cancel_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *chatServiceClient) SetPersona(ctx context.Context, in *SetPersonaRequest, opts ...grpc.CallOption) (*SetPersonaResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(SetPersonaResponse)
err := c.cc.Invoke(ctx, ChatService_SetPersona_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *chatServiceClient) ApplyTaskAction(ctx context.Context, in *ApplyTaskActionRequest, opts ...grpc.CallOption) (*ApplyTaskActionResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(ApplyTaskActionResponse)
err := c.cc.Invoke(ctx, ChatService_ApplyTaskAction_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
// ChatServiceServer is the server API for ChatService service.
// All implementations must embed UnimplementedChatServiceServer
// for forward compatibility.
type ChatServiceServer interface {
Snapshot(context.Context, *SnapshotRequest) (*SnapshotResponse, error)
GetSession(context.Context, *GetSessionRequest) (*GetSessionResponse, error)
RecentMessages(context.Context, *RecentMessagesRequest) (*RecentMessagesResponse, error)
RecentTurns(context.Context, *RecentTurnsRequest) (*RecentTurnsResponse, error)
Route(context.Context, *RouteRequest) (*RouteResponse, error)
Stream(*StreamRequest, grpc.ServerStreamingServer[StreamResponse]) error
Cancel(context.Context, *CancelRequest) (*CancelResponse, error)
SetPersona(context.Context, *SetPersonaRequest) (*SetPersonaResponse, error)
ApplyTaskAction(context.Context, *ApplyTaskActionRequest) (*ApplyTaskActionResponse, error)
mustEmbedUnimplementedChatServiceServer()
}
// UnimplementedChatServiceServer must be embedded to have
// forward compatible implementations.
//
// NOTE: this should be embedded by value instead of pointer to avoid a nil
// pointer dereference when methods are called.
type UnimplementedChatServiceServer struct{}
func (UnimplementedChatServiceServer) Snapshot(context.Context, *SnapshotRequest) (*SnapshotResponse, error) {
return nil, status.Error(codes.Unimplemented, "method Snapshot not implemented")
}
func (UnimplementedChatServiceServer) GetSession(context.Context, *GetSessionRequest) (*GetSessionResponse, error) {
return nil, status.Error(codes.Unimplemented, "method GetSession not implemented")
}
func (UnimplementedChatServiceServer) RecentMessages(context.Context, *RecentMessagesRequest) (*RecentMessagesResponse, error) {
return nil, status.Error(codes.Unimplemented, "method RecentMessages not implemented")
}
func (UnimplementedChatServiceServer) RecentTurns(context.Context, *RecentTurnsRequest) (*RecentTurnsResponse, error) {
return nil, status.Error(codes.Unimplemented, "method RecentTurns not implemented")
}
func (UnimplementedChatServiceServer) Route(context.Context, *RouteRequest) (*RouteResponse, error) {
return nil, status.Error(codes.Unimplemented, "method Route not implemented")
}
func (UnimplementedChatServiceServer) Stream(*StreamRequest, grpc.ServerStreamingServer[StreamResponse]) error {
return status.Error(codes.Unimplemented, "method Stream not implemented")
}
func (UnimplementedChatServiceServer) Cancel(context.Context, *CancelRequest) (*CancelResponse, error) {
return nil, status.Error(codes.Unimplemented, "method Cancel not implemented")
}
func (UnimplementedChatServiceServer) SetPersona(context.Context, *SetPersonaRequest) (*SetPersonaResponse, error) {
return nil, status.Error(codes.Unimplemented, "method SetPersona not implemented")
}
func (UnimplementedChatServiceServer) ApplyTaskAction(context.Context, *ApplyTaskActionRequest) (*ApplyTaskActionResponse, error) {
return nil, status.Error(codes.Unimplemented, "method ApplyTaskAction not implemented")
}
func (UnimplementedChatServiceServer) mustEmbedUnimplementedChatServiceServer() {}
func (UnimplementedChatServiceServer) testEmbeddedByValue() {}
// UnsafeChatServiceServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to ChatServiceServer will
// result in compilation errors.
type UnsafeChatServiceServer interface {
mustEmbedUnimplementedChatServiceServer()
}
func RegisterChatServiceServer(s grpc.ServiceRegistrar, srv ChatServiceServer) {
// If the following call panics, it indicates UnimplementedChatServiceServer was
// embedded by pointer and is nil. This will cause panics if an
// unimplemented method is ever invoked, so we test this at initialization
// time to prevent it from happening at runtime later due to I/O.
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
t.testEmbeddedByValue()
}
s.RegisterService(&ChatService_ServiceDesc, srv)
}
func _ChatService_Snapshot_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SnapshotRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ChatServiceServer).Snapshot(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: ChatService_Snapshot_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ChatServiceServer).Snapshot(ctx, req.(*SnapshotRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ChatService_GetSession_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetSessionRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ChatServiceServer).GetSession(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: ChatService_GetSession_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ChatServiceServer).GetSession(ctx, req.(*GetSessionRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ChatService_RecentMessages_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RecentMessagesRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ChatServiceServer).RecentMessages(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: ChatService_RecentMessages_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ChatServiceServer).RecentMessages(ctx, req.(*RecentMessagesRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ChatService_RecentTurns_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RecentTurnsRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ChatServiceServer).RecentTurns(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: ChatService_RecentTurns_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ChatServiceServer).RecentTurns(ctx, req.(*RecentTurnsRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ChatService_Route_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RouteRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ChatServiceServer).Route(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: ChatService_Route_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ChatServiceServer).Route(ctx, req.(*RouteRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ChatService_Stream_Handler(srv interface{}, stream grpc.ServerStream) error {
m := new(StreamRequest)
if err := stream.RecvMsg(m); err != nil {
return err
}
return srv.(ChatServiceServer).Stream(m, &grpc.GenericServerStream[StreamRequest, StreamResponse]{ServerStream: stream})
}
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
type ChatService_StreamServer = grpc.ServerStreamingServer[StreamResponse]
func _ChatService_Cancel_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(CancelRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ChatServiceServer).Cancel(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: ChatService_Cancel_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ChatServiceServer).Cancel(ctx, req.(*CancelRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ChatService_SetPersona_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SetPersonaRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ChatServiceServer).SetPersona(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: ChatService_SetPersona_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ChatServiceServer).SetPersona(ctx, req.(*SetPersonaRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ChatService_ApplyTaskAction_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ApplyTaskActionRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ChatServiceServer).ApplyTaskAction(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: ChatService_ApplyTaskAction_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ChatServiceServer).ApplyTaskAction(ctx, req.(*ApplyTaskActionRequest))
}
return interceptor(ctx, in, info, handler)
}
// ChatService_ServiceDesc is the grpc.ServiceDesc for ChatService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var ChatService_ServiceDesc = grpc.ServiceDesc{
ServiceName: "gateway.v1.ChatService",
HandlerType: (*ChatServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Snapshot",
Handler: _ChatService_Snapshot_Handler,
},
{
MethodName: "GetSession",
Handler: _ChatService_GetSession_Handler,
},
{
MethodName: "RecentMessages",
Handler: _ChatService_RecentMessages_Handler,
},
{
MethodName: "RecentTurns",
Handler: _ChatService_RecentTurns_Handler,
},
{
MethodName: "Route",
Handler: _ChatService_Route_Handler,
},
{
MethodName: "Cancel",
Handler: _ChatService_Cancel_Handler,
},
{
MethodName: "SetPersona",
Handler: _ChatService_SetPersona_Handler,
},
{
MethodName: "ApplyTaskAction",
Handler: _ChatService_ApplyTaskAction_Handler,
},
},
Streams: []grpc.StreamDesc{
{
StreamName: "Stream",
Handler: _ChatService_Stream_Handler,
ServerStreams: true,
},
},
Metadata: "gateway/v1/chat.proto",
}
+201
View File
@@ -0,0 +1,201 @@
// Package taskactions owns operator task mutations shared by chat and dashboard.
package taskactions
import (
"context"
"errors"
"fmt"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/taskstate"
)
var (
ErrNotFound = errors.New("task not found")
ErrConflict = errors.New("task action conflict")
ErrUnavailable = errors.New("runtime task control is unavailable")
)
// Task is the state needed to authorize and apply an operator action.
type Task struct {
ID int64
Owner, Repo, Identity, Status, Stage, ParkReason string
IssueNumber, RetryCount int
ForgeBacked bool
}
type Store interface {
TaskByID(context.Context, int64) (*Task, error)
Transition(context.Context, int64, string, string, string) error
Requeue(context.Context, int64, string, string) error
RetryTask(context.Context, int64, string, string) error
ArchiveTask(context.Context, int64, string, events.Event) (int64, error)
InsertEvent(context.Context, events.Event) (int64, error)
}
// Service runs in the daemon, which owns execution cancellation and events.
type Service struct {
Store Store
MaxRetries func(*Task) int
CancelTask func(int64) bool
CloseIssue func(context.Context, string, string, int, string) error
RemoveLogs func(int64) error
Publish func(events.Event)
Warn func(string, ...any)
}
// Apply scopes chat requests to an identity. A nil identity denotes an
// authenticated dashboard operator, who may act across identities.
func (s Service) Apply(ctx context.Context, identity *string, id int64, action taskstate.Action) error {
task, err := s.Store.TaskByID(ctx, id)
if err != nil {
return err
}
if task == nil {
return fmt.Errorf("task %d: %w", id, ErrNotFound)
}
if identity != nil && task.Identity != *identity {
return fmt.Errorf("task %d belongs to %q, not %q", id, task.Identity, *identity)
}
if err := taskstate.CheckAction(task.Status, action); err != nil {
return fmt.Errorf("%w: %w", ErrConflict, err)
}
mutation, err := s.apply(ctx, task, identity, action)
if err != nil {
return err
}
if mutation.verb != "" && task.ForgeBacked {
s.closeRejectedIssue(ctx, task, identity, mutation.verb)
}
s.emit(ctx, mutation.event)
return nil
}
type outcome struct {
event events.Event
verb string
}
// apply performs the store mutation for one action and returns the event to
// record alongside it. Errors from the store are returned unwrapped: the
// caller maps them to a response, and the rules-level errors (ErrConflict)
// were already checked above.
func (s Service) apply(ctx context.Context, task *Task, identity *string, action taskstate.Action) (outcome, error) {
source := "the dashboard"
if identity != nil {
source = "chat"
}
o := outcome{event: events.Event{TaskID: task.ID, Repo: task.Owner + "/" + task.Repo, Issue: task.IssueNumber}}
switch action {
case taskstate.ActionApprove:
err := s.Store.Requeue(ctx, task.ID, "waiting_human", "implement")
o.event.Kind, o.event.Detail = events.KindHumanApproved, "approved via "+source
return o, err
case taskstate.ActionRetry:
return s.applyRetry(ctx, task, source, o)
case taskstate.ActionStop:
return s.applyStop(ctx, task, source, o)
case taskstate.ActionReject:
o.event.Kind, o.event.Detail, o.verb = events.KindHumanRejected, "rejected via "+source, "rejected"
if task.Status == "running" && s.CancelTask != nil {
s.CancelTask(task.ID)
}
return o, s.Store.Transition(ctx, task.ID, task.Status, "closed_wont_do", "declined from "+source)
case taskstate.ActionCancel, taskstate.ActionAbandon:
return s.applyCancelOrAbandon(ctx, task, action, source, o)
case taskstate.ActionArchive:
return s.applyArchive(ctx, task, source, o)
default:
return o, fmt.Errorf("unsupported task action %q", action)
}
}
func (s Service) applyRetry(ctx context.Context, task *Task, source string, o outcome) (outcome, error) {
limit := 0
if s.MaxRetries != nil {
limit = s.MaxRetries(task)
}
if limit > 0 && task.RetryCount >= limit {
reason := fmt.Sprintf("max retries reached (%d/%d)", task.RetryCount, limit)
if err := s.Store.Transition(ctx, task.ID, "parked", "dead", reason); err != nil {
s.warn("transition to dead failed", "task", task.ID, "err", err)
} else {
o.event.Kind, o.event.Detail = events.KindTaskDead, reason
s.emit(ctx, o.event)
}
return o, fmt.Errorf("%w: %s", ErrConflict, reason)
}
err := s.Store.RetryTask(ctx, task.ID, "parked", "")
o.event.Kind, o.event.Detail = events.KindTaskRetried, "retried via "+source
o.event.Data = map[string]any{"retry_count": task.RetryCount + 1, "previous_stage": task.Stage, "previous_reason": task.ParkReason}
return o, err
}
func (s Service) applyStop(ctx context.Context, task *Task, source string, o outcome) (outcome, error) {
if s.CancelTask == nil {
return o, ErrUnavailable
}
o.event.Kind, o.event.Detail = events.KindTaskStopped, "stopped via "+source+"; recoverable work remains parked"
if !s.CancelTask(task.ID) {
o.event.Detail = "no active execution was found; recoverable work was parked via " + source
}
return o, s.Store.Transition(ctx, task.ID, "running", "parked", o.event.Detail)
}
func (s Service) applyCancelOrAbandon(ctx context.Context, task *Task, action taskstate.Action, source string, o outcome) (outcome, error) {
from, kind, verb := "queued", events.KindTaskCancelled, "cancelled"
if action == taskstate.ActionAbandon {
from, kind, verb = "parked", events.KindTaskAbandoned, "abandoned"
}
o.event.Kind, o.event.Detail, o.verb = kind, verb+" via "+source, verb
return o, s.Store.Transition(ctx, task.ID, from, "closed_wont_do", o.event.Detail)
}
func (s Service) applyArchive(ctx context.Context, task *Task, source string, o outcome) (outcome, error) {
o.event.Kind, o.event.Detail = events.KindTaskArchiveRequested, "archive requested via "+source
id, err := s.Store.ArchiveTask(ctx, task.ID, task.Status, o.event)
if err != nil {
return o, err
}
o.event.ID = id
if s.RemoveLogs != nil {
if cleanupErr := s.RemoveLogs(task.ID); cleanupErr != nil {
s.warn("task log cleanup failed", "task", task.ID, "err", cleanupErr)
}
}
return o, nil
}
func (s Service) closeRejectedIssue(ctx context.Context, task *Task, identity *string, verb string) {
if s.CloseIssue == nil {
s.warn("task rejected but no forge is wired; the issue stays open and will be re-polled", "task", task.ID)
return
}
comment := fmt.Sprintf("Closing: this task was %s from the archie %s. Reopen the issue to have archie pick it up again.", verb, "dashboard")
if identity != nil {
comment = fmt.Sprintf("Closing: this task was %s from archie chat. Reopen the issue to have archie pick it up again.", verb)
}
if err := s.CloseIssue(ctx, task.Owner, task.Repo, task.IssueNumber, comment); err != nil {
s.warn("closing rejected issue failed; it stays open and will be re-polled", "task", task.ID, "err", err)
}
}
func (s Service) emit(ctx context.Context, e events.Event) {
if e.ID == 0 {
id, err := s.Store.InsertEvent(ctx, e)
if err != nil {
s.warn("operator activity persistence failed", "kind", e.Kind, "task", e.TaskID, "err", err)
} else {
e.ID = id
}
}
if s.Publish != nil {
s.Publish(e)
}
}
func (s Service) warn(msg string, args ...any) {
if s.Warn != nil {
s.Warn(msg, args...)
}
}
+62
View File
@@ -0,0 +1,62 @@
package gateway
import (
"context"
"github.com/samcharles93/archie-core/internal/taskstate"
)
// ChatContract is the conversational boundary consumed by channel frontends.
// Results are snapshots: callers must not rely on shared object identity.
type ChatContract interface { //nolint:interfacebloat // wire contract intentionally covers the complete Gateway facade
Snapshot(context.Context) (ChatSnapshot, error)
GetSession(context.Context, string) (SessionContext, bool, error)
RecentMessages(context.Context, string, int) ([]Message, error)
RecentTurns(context.Context, string, int) ([]TurnRecord, error)
Route(context.Context, Message) (ChatReply, error)
// Stream emits started, delta/tool/media, then done or error, in order.
// Callers must drain the stream or cancel the context. Cancellation closes it.
Stream(context.Context, Message) (<-chan ChatEvent, error)
Cancel(context.Context, string) (ChatCancellation, error)
SetPersona(context.Context, string, string) (bool, error)
ChatTaskActionContract
}
// ChatTaskActionContract is the operator task mutation capability exposed by
// the Gateway. It is separate so read/turn consumers do not need to model it.
type ChatTaskActionContract interface {
ApplyTaskAction(context.Context, string, int64, taskstate.Action) (TaskActionResult, error)
}
type ChatSnapshot struct {
Sessions []SessionContext
Models []string
ModelsByProvider map[string][]string
Providers []string
ActiveModel string
ActiveProvider string
Personas []string
ActivePersonas map[string]string
RestartAvailable bool
CancellationAvailable bool
PersonasAvailable bool
}
type ChatReply struct {
Text string
SessionID string
}
type ChatCancellation struct {
Cancelled bool
Dropped int
}
// ChatEvent contains values only; Text holds the error message for error events.
type ChatEvent struct {
Kind string
Text string
SessionID string
Tool ToolCallEvent
Media MediaEvent
}
+206
View File
@@ -0,0 +1,206 @@
package gateway
import (
"context"
"errors"
"slices"
"strings"
"github.com/samcharles93/archie-core/internal/taskstate"
)
// LocalChatAdapter connects the chat boundary to the existing gateway owners.
// Composition configures the Router, including updates and dangerous actions,
// before publishing this adapter to consumers.
type LocalChatAdapter struct {
Router *Router
Sessions SessionStore
Turns *Turns
Models ModelManager
Personas *PersonaRegistry
TaskActor ChatTaskActor
}
var _ ChatContract = (*LocalChatAdapter)(nil)
var ErrChatCapabilityUnavailable = errors.New("chat capability is not configured")
func (a *LocalChatAdapter) Snapshot(ctx context.Context) (ChatSnapshot, error) {
sessions, err := a.Sessions.List(ctx)
if err != nil {
return ChatSnapshot{}, err
}
s := ChatSnapshot{Sessions: sessions, Models: []string{}, Providers: []string{}, Personas: []string{}, ModelsByProvider: map[string][]string{}, ActivePersonas: map[string]string{}, RestartAvailable: a.Router.Restart != nil, CancellationAvailable: a.Turns != nil, PersonasAvailable: a.Personas != nil}
if a.Models != nil {
s.Models = slices.Clone(a.Models.Models())
s.ActiveModel = a.Models.ActiveModel()
if models, ok := a.Models.(ProviderModelManager); ok {
s.ActiveProvider = models.ActiveProvider()
s.Providers = slices.Clone(models.Providers())
for _, provider := range s.Providers {
s.ModelsByProvider[provider] = slices.Clone(models.ModelsForProvider(provider))
}
} else {
for _, model := range s.Models {
provider, _, ok := strings.Cut(model, "/")
if !ok {
provider = ""
}
s.ModelsByProvider[provider] = append(s.ModelsByProvider[provider], model)
}
}
}
if a.Personas != nil {
s.Personas = slices.Clone(a.Personas.List())
for _, session := range sessions {
s.ActivePersonas[session.SessionID] = a.Personas.ActiveName(session.SessionID)
}
}
return s, nil
}
func (a *LocalChatAdapter) GetSession(ctx context.Context, id string) (SessionContext, bool, error) {
session, err := a.Sessions.Get(ctx, id)
if err != nil || session == nil {
return SessionContext{}, false, err
}
return *session, true, nil
}
func (a *LocalChatAdapter) RecentMessages(ctx context.Context, id string, n int) ([]Message, error) {
return a.Sessions.RecentMessages(ctx, id, n)
}
func (a *LocalChatAdapter) RecentTurns(ctx context.Context, id string, n int) ([]TurnRecord, error) {
if history, ok := a.Sessions.(TurnHistory); ok {
return history.RecentTurns(ctx, id, n)
}
return []TurnRecord{}, nil
}
func (a *LocalChatAdapter) Route(ctx context.Context, msg Message) (ChatReply, error) {
reply, err := a.Router.Route(ctx, msg)
if err != nil {
return ChatReply{}, err
}
id, err := a.Router.ResolveSessionKey(ctx, msg)
return ChatReply{Text: reply, SessionID: id}, err
}
func (a *LocalChatAdapter) Cancel(ctx context.Context, id string) (ChatCancellation, error) {
if err := ctx.Err(); err != nil {
return ChatCancellation{}, err
}
if a.Turns == nil {
return ChatCancellation{}, ErrChatCapabilityUnavailable
}
cancelled, dropped := a.Turns.Stop(id)
return ChatCancellation{Cancelled: cancelled, Dropped: dropped}, nil
}
func (a *LocalChatAdapter) SetPersona(ctx context.Context, id, name string) (bool, error) {
if err := ctx.Err(); err != nil {
return false, err
}
if a.Personas == nil {
return false, ErrChatCapabilityUnavailable
}
return a.Personas.SetActive(id, strings.ToLower(name)), nil
}
func (a *LocalChatAdapter) ApplyTaskAction(ctx context.Context, identity string, taskID int64, action taskstate.Action) (TaskActionResult, error) {
if a.TaskActor == nil {
return TaskActionResult{}, ErrChatCapabilityUnavailable
}
return a.TaskActor.ApplyChatTaskAction(ctx, identity, taskID, action)
}
func (a *LocalChatAdapter) Stream(ctx context.Context, msg Message) (<-chan ChatEvent, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
id, err := a.Router.ResolveSessionKey(ctx, msg)
if err != nil {
return nil, err
}
events := make(chan ChatEvent, 32)
events <- ChatEvent{Kind: "started", SessionID: id}
go a.stream(ctx, msg, id, events)
return events, nil
}
func (a *LocalChatAdapter) stream(ctx context.Context, msg Message, id string, events chan ChatEvent) {
defer close(events)
pending := make(chan ChatEvent, 32)
stream := localChatStream{done: ctx.Done(), events: pending, sessionID: id}
run := func(turnCtx context.Context) ChatEvent {
reply, err := a.Router.RouteStream(turnCtx, msg, stream)
if err != nil {
return ChatEvent{Kind: "error", Text: err.Error(), SessionID: id}
}
resolvedID := id
if resolved, err := a.Router.ResolveSessionKey(ctx, msg); err == nil {
resolvedID = resolved
}
return ChatEvent{Kind: "done", Text: reply, SessionID: resolvedID}
}
result := make(chan ChatEvent, 1)
if a.Turns == nil {
go func() { result <- run(ctx) }()
} else {
a.Turns.Submit(ctx, id, func(turnCtx context.Context) { result <- run(turnCtx) })
}
emit := func(event ChatEvent) {
select {
case events <- event:
case <-ctx.Done():
}
}
for {
select {
case event := <-pending:
emit(event)
case terminal := <-result:
for {
select {
case event := <-pending:
emit(event)
default:
emit(terminal)
return
}
}
case <-ctx.Done():
if a.Turns != nil {
a.Turns.Stop(id)
}
return
}
}
}
type localChatStream struct {
done <-chan struct{}
events chan<- ChatEvent
sessionID string
}
func (s localChatStream) send(event ChatEvent) {
event.SessionID = s.sessionID
select {
case s.events <- event:
case <-s.done:
}
}
func (s localChatStream) Delta(text string) {
s.send(ChatEvent{Kind: "delta", Text: text})
}
func (s localChatStream) ToolCall(event ToolCallEvent) {
s.send(ChatEvent{Kind: "tool", Tool: event})
}
func (s localChatStream) Media(event MediaEvent) {
s.send(ChatEvent{Kind: "media", Media: event})
}
+38
View File
@@ -0,0 +1,38 @@
package gateway
import (
"context"
"testing"
)
func TestLocalChatSnapshotAndStream(t *testing.T) {
ctx := t.Context()
sessions := NewSessionStoreMemory()
t.Cleanup(func() { _ = sessions.Close() })
router := NewRouter(nil, nil, "web")
router.InitSessions(sessions)
chat := &LocalChatAdapter{Router: router, Sessions: sessions}
snapshot, err := chat.Snapshot(ctx)
if err != nil || snapshot.CancellationAvailable || snapshot.PersonasAvailable {
t.Fatalf("snapshot = %+v, %v", snapshot, err)
}
if _, found, err := chat.GetSession(ctx, "absent"); err != nil || found {
t.Fatalf("missing session = %v, %v", found, err)
}
events, err := chat.Stream(ctx, Message{ChannelID: "browser", From: "web", Text: "/help"})
if err != nil {
t.Fatal(err)
}
var got []ChatEvent
for event := range events {
got = append(got, event)
}
if len(got) < 2 || got[0].Kind != "started" || got[len(got)-1].Kind != "done" || got[len(got)-1].Text == "" {
t.Fatalf("events = %+v", got)
}
cancelCtx, cancel := context.WithCancel(ctx)
cancel()
if _, err := chat.Stream(cancelCtx, Message{}); err == nil {
t.Fatal("cancelled context accepted")
}
}
@@ -59,6 +59,9 @@ const (
// input was to not call them. Splitting them means defaults can be applied,
// inspected, and reasoned about independently of whether the result is valid.
func (l *Loader) applyDefaults(cfg *config.Config) {
if cfg.Services.Gateway.Target == "" {
cfg.Services.Gateway.Target = "127.0.0.1:8585"
}
l.applyGeneralDefaults(cfg)
applyForgeDefaults(cfg)
applyDispatchDefaults(cfg)
@@ -0,0 +1,30 @@
package configuration
import (
"os"
"path/filepath"
"testing"
)
func TestLoadGatewayServiceTarget(t *testing.T) {
for _, tt := range []struct {
name, section, wantTarget string
}{
{name: "default", wantTarget: "127.0.0.1:8585"},
{name: "explicit target", section: "[services.gateway]\ntarget = 'dns:///gateway:8443'", wantTarget: "dns:///gateway:8443"},
} {
t.Run(tt.name, func(t *testing.T) {
path := filepath.Join(t.TempDir(), "config.toml")
if err := os.WriteFile(path, []byte("bot_user = 'widget'\n"+tt.section), 0o600); err != nil {
t.Fatal(err)
}
cfg, err := loadFile(path)
if err != nil {
t.Fatal(err)
}
if cfg.Services.Gateway.Target != tt.wantTarget {
t.Fatalf("target = %q, want %q", cfg.Services.Gateway.Target, tt.wantTarget)
}
})
}
}
@@ -26,6 +26,9 @@ func minimalValidConfig() config.Config {
Containers: config.ContainerConfig{
Image: "ghcr.io/samcharles93/archie-agent:latest",
},
Services: config.Services{
Gateway: config.ServiceConnection{Target: "127.0.0.1:8585"},
},
}
}
@@ -0,0 +1,118 @@
// Package gatewayrpc adapts the Gateway chat contract to gRPC.
package gatewayrpc
import (
"context"
"errors"
"io"
"google.golang.org/grpc"
pb "github.com/samcharles93/archie-core/internal/contracts/gateway/v1"
"github.com/samcharles93/archie-core/internal/gateway"
"github.com/samcharles93/archie-core/internal/taskstate"
)
var _ gateway.ChatContract = (*Client)(nil)
type Client struct{ client pb.ChatServiceClient }
func NewClient(conn grpc.ClientConnInterface) *Client {
return &Client{client: pb.NewChatServiceClient(conn)}
}
func (c *Client) Snapshot(ctx context.Context) (gateway.ChatSnapshot, error) {
v, err := c.client.Snapshot(ctx, &pb.SnapshotRequest{})
if err != nil {
return gateway.ChatSnapshot{}, err
}
return snapshotValue(v), nil
}
func (c *Client) GetSession(ctx context.Context, id string) (gateway.SessionContext, bool, error) {
v, err := c.client.GetSession(ctx, &pb.GetSessionRequest{SessionId: id})
if err != nil {
return gateway.SessionContext{}, false, err
}
return sessionValue(v.Session), v.Found, nil
}
func (c *Client) RecentMessages(ctx context.Context, id string, n int) ([]gateway.Message, error) {
v, err := c.client.RecentMessages(ctx, &pb.RecentMessagesRequest{SessionId: id, Limit: int64(n)})
if err != nil {
return nil, err
}
return mapValues(v.Messages, messageValue), nil
}
func (c *Client) RecentTurns(ctx context.Context, id string, n int) ([]gateway.TurnRecord, error) {
v, err := c.client.RecentTurns(ctx, &pb.RecentTurnsRequest{SessionId: id, Limit: int64(n)})
if err != nil {
return nil, err
}
return mapValues(v.Turns, turnValue), nil
}
func (c *Client) Route(ctx context.Context, msg gateway.Message) (gateway.ChatReply, error) {
v, err := c.client.Route(ctx, &pb.RouteRequest{Message: messageProto(msg)})
if err != nil {
return gateway.ChatReply{}, err
}
return gateway.ChatReply{Text: v.Text, SessionID: v.SessionId}, nil
}
func (c *Client) Cancel(ctx context.Context, id string) (gateway.ChatCancellation, error) {
v, err := c.client.Cancel(ctx, &pb.CancelRequest{SessionId: id})
if err != nil {
return gateway.ChatCancellation{}, err
}
return gateway.ChatCancellation{Cancelled: v.Cancelled, Dropped: int(v.Dropped)}, nil
}
func (c *Client) SetPersona(ctx context.Context, id, name string) (bool, error) {
v, err := c.client.SetPersona(ctx, &pb.SetPersonaRequest{SessionId: id, Name: name})
if err != nil {
return false, err
}
return v.Found, nil
}
func (c *Client) ApplyTaskAction(ctx context.Context, identity string, taskID int64, action taskstate.Action) (gateway.TaskActionResult, error) {
v, err := c.client.ApplyTaskAction(ctx, &pb.ApplyTaskActionRequest{Identity: identity, TaskId: taskID, Action: string(action)})
if err != nil {
return gateway.TaskActionResult{}, err
}
return gateway.TaskActionResult{TaskID: v.TaskId, Action: v.Action, Message: v.Message}, nil
}
func (c *Client) Stream(ctx context.Context, msg gateway.Message) (<-chan gateway.ChatEvent, error) {
stream, err := c.client.Stream(ctx, &pb.StreamRequest{Message: messageProto(msg)})
if err != nil {
return nil, err
}
out := make(chan gateway.ChatEvent)
go func() {
defer close(out)
for {
v, err := stream.Recv()
if errors.Is(err, io.EOF) {
return
}
var event gateway.ChatEvent
if err != nil {
event = gateway.ChatEvent{Kind: "error", Text: err.Error()}
} else {
event = eventValue(v)
}
select {
case out <- event:
case <-ctx.Done():
return
}
if err != nil {
return
}
}
}()
return out, nil
}
@@ -0,0 +1,106 @@
package gatewayrpc
import (
"context"
"net"
"reflect"
"testing"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/test/bufconn"
"github.com/samcharles93/archie-core/internal/gateway"
)
func remoteChat(t *testing.T, local gateway.ChatContract) gateway.ChatContract {
t.Helper()
listener := bufconn.Listen(1 << 20)
server := grpc.NewServer()
RegisterServer(server, local)
go func() { _ = server.Serve(listener) }()
t.Cleanup(func() { server.Stop(); _ = listener.Close() })
conn, err := grpc.NewClient("passthrough:///gateway", grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return listener.DialContext(ctx) }))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = conn.Close() })
return NewClient(conn)
}
func TestChatContractConformance(t *testing.T) {
for _, mode := range []string{"local", "grpc"} {
t.Run(mode, func(t *testing.T) {
ctx := t.Context()
sessions := gateway.NewSessionStoreMemory()
t.Cleanup(func() { _ = sessions.Close() })
router := gateway.NewRouter(nil, nil, "web")
router.InitSessions(sessions)
local := &gateway.LocalChatAdapter{Router: router, Sessions: sessions}
var chat gateway.ChatContract = local
if mode == "grpc" {
chat = remoteChat(t, local)
}
if _, found, err := chat.GetSession(ctx, "missing"); err != nil || found {
t.Fatalf("missing session: %v %v", found, err)
}
msg := gateway.Message{ChannelID: "browser", From: "web", Text: "/help", Page: "/tasks"}
reply, err := chat.Route(ctx, msg)
if err != nil || reply.Text == "" || reply.SessionID == "" {
t.Fatalf("route: %+v %v", reply, err)
}
session, found, err := chat.GetSession(ctx, reply.SessionID)
if err != nil || !found || session.Source.Platform != "web" {
t.Fatalf("session: %+v %v %v", session, found, err)
}
snap, err := chat.Snapshot(ctx)
if err != nil || len(snap.Sessions) != 1 || snap.CancellationAvailable || snap.PersonasAvailable {
t.Fatalf("snapshot: %+v %v", snap, err)
}
if _, err := chat.RecentMessages(ctx, reply.SessionID, 200); err != nil {
t.Fatal(err)
}
if turns, err := chat.RecentTurns(ctx, reply.SessionID, 200); err != nil || len(turns) != 0 {
t.Fatalf("turns: %+v %v", turns, err)
}
if _, err := chat.Cancel(ctx, reply.SessionID); err == nil {
t.Fatal("missing cancellation capability accepted")
}
if _, err := chat.SetPersona(ctx, reply.SessionID, "missing"); err == nil {
t.Fatal("missing persona capability accepted")
}
events, err := chat.Stream(ctx, msg)
if err != nil {
t.Fatal(err)
}
var got []gateway.ChatEvent
for event := range events {
got = append(got, event)
}
if len(got) < 2 || got[0].Kind != "started" || got[len(got)-1].Kind != "done" || got[len(got)-1].Text != reply.Text {
t.Fatalf("stream: %+v", got)
}
})
}
}
func TestWireValuesPreserveHistoryAndMedia(t *testing.T) {
now := time.Date(2026, 9, 5, 1, 2, 3, 456, time.UTC)
tool := gateway.ToolCallEvent{ID: "tool-1", Name: "read", Parameters: "{}", Output: "result", Err: "failed"}
turn := gateway.TurnRecord{TurnID: "turn", SessionID: "session", SourceID: "source", Status: gateway.TurnStatusPartial, Attempt: 3, OwnerID: "owner", InputMessageID: "input", AssistantMessageID: "assistant", PartialText: "partial", ResponseText: "reply", ToolCalls: []gateway.ToolCallEvent{tool}, Error: "failure", CreatedAt: now, UpdatedAt: now}
if got := turnValue(turnProto(turn)); !reflect.DeepEqual(got, turn) {
t.Fatalf("turn round trip: %+v", got)
}
size := int64(0)
width := 640
height := 480
duration := 3
event := gateway.ChatEvent{Kind: "media", Text: "caption", SessionID: "session", Tool: tool, Media: gateway.MediaEvent{ToolName: "send_file", Attachment: gateway.MediaAttachment{Type: "video", FileID: "file", URL: "https://example.test/video", Path: "/tmp/video", MIMEType: "video/mp4", FileName: "video.mp4", FileSize: &size, Width: &width, Height: &height, Duration: &duration}}}
if got := eventValue(eventProto(event)); !reflect.DeepEqual(got, event) {
t.Fatalf("event round trip: %+v", got)
}
if got := messageValue(messageProto(gateway.Message{})); !got.At.IsZero() {
t.Fatalf("zero time became %v", got.At)
}
}
@@ -0,0 +1,104 @@
package gatewayrpc
import (
"context"
"google.golang.org/grpc"
pb "github.com/samcharles93/archie-core/internal/contracts/gateway/v1"
"github.com/samcharles93/archie-core/internal/gateway"
"github.com/samcharles93/archie-core/internal/taskstate"
)
type server struct {
pb.UnimplementedChatServiceServer
chat gateway.ChatContract
}
func RegisterServer(registrar grpc.ServiceRegistrar, chat gateway.ChatContract) {
pb.RegisterChatServiceServer(registrar, &server{chat: chat})
}
func (s *server) Snapshot(ctx context.Context, _ *pb.SnapshotRequest) (*pb.SnapshotResponse, error) {
v, err := s.chat.Snapshot(ctx)
if err != nil {
return nil, err
}
return snapshotProto(v), nil
}
func (s *server) GetSession(ctx context.Context, r *pb.GetSessionRequest) (*pb.GetSessionResponse, error) {
v, found, err := s.chat.GetSession(ctx, r.SessionId)
if err != nil {
return nil, err
}
return &pb.GetSessionResponse{Session: sessionProto(v), Found: found}, nil
}
func (s *server) RecentMessages(ctx context.Context, r *pb.RecentMessagesRequest) (*pb.RecentMessagesResponse, error) {
v, err := s.chat.RecentMessages(ctx, r.SessionId, int(r.Limit))
if err != nil {
return nil, err
}
return &pb.RecentMessagesResponse{Messages: mapValues(v, messageProto)}, nil
}
func (s *server) RecentTurns(ctx context.Context, r *pb.RecentTurnsRequest) (*pb.RecentTurnsResponse, error) {
v, err := s.chat.RecentTurns(ctx, r.SessionId, int(r.Limit))
if err != nil {
return nil, err
}
return &pb.RecentTurnsResponse{Turns: mapValues(v, turnProto)}, nil
}
func (s *server) Route(ctx context.Context, r *pb.RouteRequest) (*pb.RouteResponse, error) {
v, err := s.chat.Route(ctx, messageValue(r.Message))
if err != nil {
return nil, err
}
return &pb.RouteResponse{Text: v.Text, SessionId: v.SessionID}, nil
}
func (s *server) Cancel(ctx context.Context, r *pb.CancelRequest) (*pb.CancelResponse, error) {
v, err := s.chat.Cancel(ctx, r.SessionId)
if err != nil {
return nil, err
}
return &pb.CancelResponse{Cancelled: v.Cancelled, Dropped: int64(v.Dropped)}, nil
}
func (s *server) SetPersona(ctx context.Context, r *pb.SetPersonaRequest) (*pb.SetPersonaResponse, error) {
v, err := s.chat.SetPersona(ctx, r.SessionId, r.Name)
if err != nil {
return nil, err
}
return &pb.SetPersonaResponse{Found: v}, nil
}
func (s *server) ApplyTaskAction(ctx context.Context, r *pb.ApplyTaskActionRequest) (*pb.ApplyTaskActionResponse, error) {
v, err := s.chat.ApplyTaskAction(ctx, r.Identity, r.TaskId, taskstate.Action(r.Action))
if err != nil {
return nil, err
}
return &pb.ApplyTaskActionResponse{TaskId: v.TaskID, Action: v.Action, Message: v.Message}, nil
}
func (s *server) Stream(r *pb.StreamRequest, out grpc.ServerStreamingServer[pb.StreamResponse]) error {
events, err := s.chat.Stream(out.Context(), messageValue(r.Message))
if err != nil {
return err
}
for {
select {
case <-out.Context().Done():
return out.Context().Err()
case event, ok := <-events:
if !ok {
return nil
}
if err := out.Send(eventProto(event)); err != nil {
return err
}
}
}
}
@@ -0,0 +1,181 @@
package gatewayrpc
import (
"time"
"google.golang.org/protobuf/types/known/timestamppb"
pb "github.com/samcharles93/archie-core/internal/contracts/gateway/v1"
"github.com/samcharles93/archie-core/internal/gateway"
)
func timestamp(t time.Time) *timestamppb.Timestamp {
if t.IsZero() {
return nil
}
return timestamppb.New(t)
}
func timeValue(t *timestamppb.Timestamp) time.Time {
if t == nil {
return time.Time{}
}
return t.AsTime()
}
func messageProto(v gateway.Message) *pb.Message {
return &pb.Message{
MessageId: v.MessageID,
SourceId: v.SourceID,
ChannelId: v.ChannelID,
ThreadId: v.ThreadID,
From: v.From,
Text: v.Text,
Page: v.Page, At: timestamp(v.At),
}
}
func messageValue(v *pb.Message) gateway.Message {
if v == nil {
return gateway.Message{}
}
return gateway.Message{
MessageID: v.MessageId,
SourceID: v.SourceId,
ChannelID: v.ChannelId,
ThreadID: v.ThreadId,
From: v.From,
Text: v.Text,
Page: v.Page, At: timeValue(v.At),
}
}
func toolProto(v gateway.ToolCallEvent) *pb.ToolCall {
return &pb.ToolCall{
Id: v.ID,
Name: v.Name,
Parameters: v.Parameters,
Output: v.Output,
Error: v.Err,
}
}
func toolValue(v *pb.ToolCall) gateway.ToolCallEvent {
if v == nil {
return gateway.ToolCallEvent{}
}
return gateway.ToolCallEvent{
ID: v.Id,
Name: v.Name,
Parameters: v.Parameters,
Output: v.Output,
Err: v.Error,
}
}
func turnProto(v gateway.TurnRecord) *pb.Turn {
return &pb.Turn{
TurnId: v.TurnID,
SessionId: v.SessionID,
SourceId: v.SourceID,
OwnerId: v.OwnerID,
InputMessageId: v.InputMessageID,
AssistantMessageId: v.AssistantMessageID,
PartialText: v.PartialText,
ResponseText: v.ResponseText,
Error: v.Error, CreatedAt: timestamp(v.CreatedAt),
UpdatedAt: timestamp(v.UpdatedAt), Status: string(v.Status), Attempt: int64(v.Attempt), ToolCalls: mapValues(v.ToolCalls, toolProto),
}
}
func turnValue(v *pb.Turn) gateway.TurnRecord {
if v == nil {
return gateway.TurnRecord{}
}
return gateway.TurnRecord{
TurnID: v.TurnId,
SessionID: v.SessionId,
SourceID: v.SourceId,
OwnerID: v.OwnerId,
InputMessageID: v.InputMessageId,
AssistantMessageID: v.AssistantMessageId,
PartialText: v.PartialText,
ResponseText: v.ResponseText,
Error: v.Error, CreatedAt: timeValue(v.CreatedAt),
UpdatedAt: timeValue(v.UpdatedAt), Status: gateway.TurnStatus(v.Status), Attempt: int(v.Attempt), ToolCalls: mapValues(v.ToolCalls, toolValue),
}
}
func mapValues[A, B any](in []A, f func(A) B) []B {
if in == nil {
return nil
}
out := make([]B, len(in))
for i, v := range in {
out[i] = f(v)
}
return out
}
func sessionProto(v gateway.SessionContext) *pb.Session {
return &pb.Session{SessionId: v.SessionID, Platform: v.Source.Platform, BotUser: v.Source.BotUser, ChannelId: v.Source.ChannelID, ThreadId: v.Source.ThreadID, Title: v.Title, ParentSessionId: v.ParentSessionID, BranchName: v.BranchName, CreatedAt: timestamp(v.CreatedAt), LastActiveAt: timestamp(v.LastActiveAt)}
}
func sessionValue(v *pb.Session) gateway.SessionContext {
if v == nil {
return gateway.SessionContext{}
}
return gateway.SessionContext{SessionID: v.SessionId, Source: gateway.SessionSource{Platform: v.Platform, BotUser: v.BotUser, ChannelID: v.ChannelId, ThreadID: v.ThreadId}, Title: v.Title, ParentSessionID: v.ParentSessionId, BranchName: v.BranchName, CreatedAt: timeValue(v.CreatedAt), LastActiveAt: timeValue(v.LastActiveAt)}
}
func int64Pointer(v *int) *int64 {
if v == nil {
return nil
}
n := int64(*v)
return &n
}
func intPointer(v *int64) *int {
if v == nil {
return nil
}
n := int(*v)
return &n
}
func mediaProto(v gateway.MediaEvent) *pb.Media {
a := v.Attachment
return &pb.Media{ToolName: v.ToolName, Type: a.Type, FileId: a.FileID, Url: a.URL, Path: a.Path, MimeType: a.MIMEType, FileName: a.FileName, FileSize: a.FileSize, Width: int64Pointer(a.Width), Height: int64Pointer(a.Height), Duration: int64Pointer(a.Duration)}
}
func mediaValue(v *pb.Media) gateway.MediaEvent {
if v == nil {
return gateway.MediaEvent{}
}
return gateway.MediaEvent{ToolName: v.ToolName, Attachment: gateway.MediaAttachment{Type: v.Type, FileID: v.FileId, URL: v.Url, Path: v.Path, MIMEType: v.MimeType, FileName: v.FileName, FileSize: v.FileSize, Width: intPointer(v.Width), Height: intPointer(v.Height), Duration: intPointer(v.Duration)}}
}
func eventProto(v gateway.ChatEvent) *pb.StreamResponse {
return &pb.StreamResponse{Kind: v.Kind, Text: v.Text, SessionId: v.SessionID, Tool: toolProto(v.Tool), Media: mediaProto(v.Media)}
}
func eventValue(v *pb.StreamResponse) gateway.ChatEvent {
return gateway.ChatEvent{Kind: v.Kind, Text: v.Text, SessionID: v.SessionId, Tool: toolValue(v.Tool), Media: mediaValue(v.Media)}
}
func snapshotProto(v gateway.ChatSnapshot) *pb.SnapshotResponse {
groups := make(map[string]*pb.StringList, len(v.ModelsByProvider))
for k, list := range v.ModelsByProvider {
groups[k] = &pb.StringList{Values: list}
}
return &pb.SnapshotResponse{Sessions: mapValues(v.Sessions, sessionProto), Models: v.Models, ModelsByProvider: groups, Providers: v.Providers, ActiveModel: v.ActiveModel, ActiveProvider: v.ActiveProvider, Personas: v.Personas, ActivePersonas: v.ActivePersonas, RestartAvailable: v.RestartAvailable, CancellationAvailable: v.CancellationAvailable, PersonasAvailable: v.PersonasAvailable}
}
func snapshotValue(v *pb.SnapshotResponse) gateway.ChatSnapshot {
groups := make(map[string][]string, len(v.ModelsByProvider))
for k, list := range v.ModelsByProvider {
groups[k] = list.GetValues()
}
return gateway.ChatSnapshot{Sessions: mapValues(v.Sessions, sessionValue), Models: v.Models, ModelsByProvider: groups, Providers: v.Providers, ActiveModel: v.ActiveModel, ActiveProvider: v.ActiveProvider, Personas: v.Personas, ActivePersonas: v.ActivePersonas, RestartAvailable: v.RestartAvailable, CancellationAvailable: v.CancellationAvailable, PersonasAvailable: v.PersonasAvailable}
}
@@ -0,0 +1,77 @@
package taskactions
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"time"
"github.com/nats-io/nats.go"
"github.com/samcharles93/archie-core/internal/domain/taskactions"
"github.com/samcharles93/archie-core/internal/gateway"
"github.com/samcharles93/archie-core/internal/natsrpc"
"github.com/samcharles93/archie-core/internal/taskstate"
)
// actionSubject is the request/reply subject the Gateway's ChatTaskActor
// client issues and the daemon's responder serves. The daemon owns task
// execution; the standalone Gateway never mutates the task store directly.
const actionSubject = "archie.gateway.task-action"
type actionRequest struct {
Identity string `json:"identity"`
TaskID int64 `json:"task_id"`
Action taskstate.Action `json:"action"`
}
type actionResponse struct {
natsrpc.Envelope
}
// Register exposes only identity-scoped operator actions on the daemon. The
// daemon retains execution cancellation, retry policy, forge closure and event
// ownership; the Gateway's client reaches this responder over NATS.
// Handlers run with context.Background() (the storerpc convention): the
// daemon's lifecycle ctx is not request-scoped, and a cancelled boot ctx must
// not poison later requests.
func Register(nc *nats.Conn, service taskactions.Service, log *slog.Logger) (func(), error) {
return natsrpc.RegisterAll(nc, []natsrpc.Registration{{
Subject: actionSubject,
Handler: func(msg *nats.Msg) {
var req actionRequest
if err := json.Unmarshal(msg.Data, &req); err != nil {
natsrpc.Respond(msg, log, "taskactions", actionResponse{Envelope: natsrpc.NewEnvelope(err)})
return
}
err := service.Apply(context.Background(), &req.Identity, req.TaskID, req.Action)
natsrpc.Respond(msg, log, "taskactions", actionResponse{Envelope: natsrpc.NewEnvelope(err)})
},
}})
}
// Client forwards Gateway task actions to their daemon owner over NATS.
type Client struct {
Conn *nats.Conn
Timeout time.Duration // bounds each call when ctx has no deadline
}
func (c Client) rpc() *natsrpc.Client {
return &natsrpc.Client{Conn: c.Conn, Timeout: c.Timeout}
}
// ApplyChatTaskAction sends an operator action to the daemon's responder.
func (c Client) ApplyChatTaskAction(ctx context.Context, identity string, id int64, action taskstate.Action) (gateway.TaskActionResult, error) {
if c.Conn == nil {
return gateway.TaskActionResult{}, fmt.Errorf("task action connection is unavailable")
}
resp, err := natsrpc.Call[actionResponse](ctx, c.rpc(), actionSubject, actionRequest{Identity: identity, TaskID: id, Action: action})
if err != nil {
return gateway.TaskActionResult{}, err
}
if err := resp.Err(); err != nil {
return gateway.TaskActionResult{}, err
}
return gateway.TaskActionResult{TaskID: id, Action: string(action), Message: fmt.Sprintf("Applied %s to task %d.", action, id)}, nil
}
@@ -0,0 +1,32 @@
package taskactions
import (
"context"
"github.com/samcharles93/archie-core/internal/domain/taskactions"
"github.com/samcharles93/archie-core/internal/events"
)
// NewService assembles the operator task-action service from its production
// dependencies. Both the dashboard's in-process service (webui) and the
// daemon's NATS responder build through this one constructor so the two
// surfaces cannot diverge.
func NewService(
store taskactions.Store,
maxRetries func(*taskactions.Task) int,
cancel func(int64) bool,
closeIssue func(context.Context, string, string, int, string) error,
removeLogs func(int64) error,
publish func(events.Event),
warn func(string, ...any),
) taskactions.Service {
return taskactions.Service{
Store: store,
MaxRetries: maxRetries,
CancelTask: cancel,
CloseIssue: closeIssue,
RemoveLogs: removeLogs,
Publish: publish,
Warn: warn,
}
}
@@ -0,0 +1,35 @@
// Package taskactions adapts legacy task persistence to operator actions.
package taskactions
import (
"context"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/taskactions"
"github.com/samcharles93/archie-core/internal/store"
)
type Store struct{ store.TaskStore }
func (s Store) TaskByID(ctx context.Context, id int64) (*taskactions.Task, error) {
t, err := s.TaskStore.TaskByID(ctx, id)
if err != nil || t == nil {
return nil, err
}
return &taskactions.Task{ID: t.ID, Owner: t.Owner, Repo: t.Repo, Identity: t.Identity, Status: t.Status, Stage: t.Stage, ParkReason: t.ParkReason, IssueNumber: t.IssueNumber, RetryCount: t.RetryCount, ForgeBacked: t.IsForgeBacked()}, nil
}
func MaxRetries(cfg *config.Holder) func(*taskactions.Task) int {
return func(t *taskactions.Task) int {
if cfg == nil {
return 0
}
c := cfg.Get()
for _, repo := range c.Repos {
if repo.Owner == t.Owner && repo.Name == t.Repo {
return repo.EffectiveMaxRetries(c.MaxRetries)
}
}
return c.MaxRetries
}
}
@@ -69,6 +69,8 @@ type Event struct {
}
// ServiceRegistry resolves and watches the live endpoints of a named service.
// It models network endpoints only. In-process services do not register here;
// application composition selects local adapters independently of discovery.
type ServiceRegistry interface {
// Resolve returns the current healthy endpoints for service. It returns
// [ErrNotInstalled] if service has never been installed. If service is
+66 -195
View File
@@ -16,14 +16,10 @@ import (
)
// ChatService is the shared conversational surface exposed to the dashboard.
// It deliberately contains the gateway Router rather than duplicating command
// dispatch in the HTTP layer.
// Handlers depend on the Gateway-owned contract and never retain Gateway
// implementation objects.
type ChatService struct {
Router *gateway.Router
Sessions gateway.SessionStore
Turns *gateway.Turns
Models gateway.ModelManager
Personas *gateway.PersonaRegistry
Contract gateway.ChatContract
Updates ChatUpdateService
Dangerous *DangerousService
updateMu sync.Mutex
@@ -87,16 +83,10 @@ type dangerousDecisionRequest struct {
}
func (s *Server) chatReady(w http.ResponseWriter) (*ChatService, bool) {
if s.Chat == nil || s.Chat.Router == nil || s.Chat.Sessions == nil {
if s.Chat == nil || s.Chat.Contract == nil {
http.Error(w, "chat is not configured", http.StatusNotImplemented)
return nil, false
}
if !chatUpdateServiceConfigured(s.Chat.Router.Updates) && chatUpdateServiceConfigured(s.Chat.Updates) {
s.Chat.Router.Updates = s.Chat.Updates
}
if s.Chat.Router.Dangerous == nil && s.Chat.Dangerous != nil {
s.Chat.Router.Dangerous = s.Chat.Dangerous
}
return s.Chat, true
}
@@ -118,28 +108,32 @@ func (s *Server) handleChatSessions(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
sessions, err := chat.Sessions.List(r.Context())
snapshot, err := chat.Contract.Snapshot(r.Context())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
out := make([]gateway.SessionContext, 0, len(sessions))
for _, session := range sessions {
out := make([]gateway.SessionContext, 0, len(snapshot.Sessions))
active := make(map[string]string)
for _, session := range snapshot.Sessions {
if session.Source.Platform == "web" {
out = append(out, session)
if name, ok := snapshot.ActivePersonas[session.SessionID]; ok {
active[session.SessionID] = name
}
}
}
writeJSON(w, map[string]any{
"sessions": out,
"models": modelNames(chat.Models),
"models_by_provider": modelsByProvider(chat.Models),
"providers": modelProviders(chat.Models),
"active_model": activeModel(chat.Models),
"active_provider": activeProvider(chat.Models),
"personas": personaNames(chat.Personas),
"active_personas": activePersonas(chat.Personas, out),
"models": snapshot.Models,
"models_by_provider": snapshot.ModelsByProvider,
"providers": snapshot.Providers,
"active_model": snapshot.ActiveModel,
"active_provider": snapshot.ActiveProvider,
"personas": snapshot.Personas,
"active_personas": active,
"commands": chatCommandSpecs(chat),
"restart_available": chat.Router.Restart != nil,
"restart_available": snapshot.RestartAvailable,
"dangerous_available": chat.Dangerous != nil,
})
}
@@ -163,16 +157,16 @@ func (s *Server) handleChatMessages(w http.ResponseWriter, r *http.Request) {
return
}
sessionID := r.PathValue("id")
session, err := chat.Sessions.Get(r.Context(), sessionID)
session, found, err := chat.Contract.GetSession(r.Context(), sessionID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if session == nil || session.Source.Platform != "web" {
if !found || session.Source.Platform != "web" {
http.Error(w, "session not found", http.StatusNotFound)
return
}
messages, err := chat.Sessions.RecentMessages(r.Context(), sessionID, 200)
messages, err := chat.Contract.RecentMessages(r.Context(), sessionID, 200)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
@@ -186,21 +180,16 @@ func (s *Server) handleChatTurns(w http.ResponseWriter, r *http.Request) {
return
}
sessionID := r.PathValue("id")
session, err := chat.Sessions.Get(r.Context(), sessionID)
session, found, err := chat.Contract.GetSession(r.Context(), sessionID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if session == nil || session.Source.Platform != "web" {
if !found || session.Source.Platform != "web" {
http.Error(w, "session not found", http.StatusNotFound)
return
}
history, ok := chat.Sessions.(gateway.TurnHistory)
if !ok {
writeJSON(w, []gateway.TurnRecord{})
return
}
turns, err := history.RecentTurns(r.Context(), sessionID, 200)
turns, err := chat.Contract.RecentTurns(r.Context(), sessionID, 200)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
@@ -253,17 +242,12 @@ func (s *Server) handleChatMessage(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
reply, err := chat.Router.Route(r.Context(), msg)
reply, err := chat.Contract.Route(r.Context(), msg)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
sessionID, err := chat.Router.ResolveSessionKey(r.Context(), msg)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
writeJSON(w, map[string]string{"reply": reply, "session_id": sessionID})
writeJSON(w, map[string]string{"reply": reply.Text, "session_id": reply.SessionID})
}
// chatStreamEvent is one `data: {...}` frame of the chat stream. A tool frame
@@ -402,83 +386,21 @@ func (s *Server) handleChatStream(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprintf(w, "data: %s\n\n", payload)
flusher.Flush()
}
sessionID, err := chat.Router.ResolveSessionKey(r.Context(), msg)
events, err := chat.Contract.Stream(r.Context(), msg)
if err != nil {
writeChatEvent(chatStreamEvent{Type: "error", Text: err.Error()}, "")
return
}
writeChatEvent(chatStreamEvent{Type: "started"}, sessionID)
showToolCalls := s.chatShowToolCalls()
var reply string
if chat.Turns == nil {
reply, err = chat.Router.RouteStream(r.Context(), msg, chatStreamSink{
showToolCalls: showToolCalls,
write: func(event chatStreamEvent) {
writeChatEvent(event, sessionID)
},
})
} else {
var cancelled bool
reply, err, cancelled = s.runQueuedChatTurn(r, chat, sessionID, msg, showToolCalls, writeChatEvent)
if cancelled {
return
}
}
if err != nil {
writeChatEvent(chatStreamEvent{Type: "error", Text: err.Error()}, sessionID)
return
}
if resolved, resolveErr := chat.Router.ResolveSessionKey(r.Context(), msg); resolveErr == nil {
sessionID = resolved
}
writeChatEvent(chatStreamEvent{Type: "done", Text: reply}, sessionID)
}
// runQueuedChatTurn submits msg to the session's turn queue and streams its
// text/tool events as they arrive, in order, via writeChatEvent. One channel
// carries both text and tool events, because the order between them is the
// point: a tool line that overtakes the sentence it interrupted describes a
// turn that never happened. Returns cancelled=true when the request context
// was cancelled before the turn finished, in which case the caller must not
// write any further response.
func (s *Server) runQueuedChatTurn(
r *http.Request, chat *ChatService, sessionID string, msg gateway.Message, showToolCalls bool,
writeChatEvent func(chatStreamEvent, string),
) (reply string, err error, cancelled bool) {
type turnResult struct {
reply string
err error
}
events := make(chan chatStreamEvent, 32)
result := make(chan turnResult, 1)
chat.Turns.Submit(r.Context(), sessionID, func(turnCtx context.Context) {
turnReply, turnErr := chat.Router.RouteStream(turnCtx, msg, chatStreamSink{
showToolCalls: showToolCalls,
write: func(event chatStreamEvent) {
select {
case events <- event:
case <-r.Context().Done():
}
},
})
result <- turnResult{reply: turnReply, err: turnErr}
})
for {
select {
case event := <-events:
writeChatEvent(event, sessionID)
case turn := <-result:
for {
select {
case event := <-events:
writeChatEvent(event, sessionID)
default:
return turn.reply, turn.err, false
}
}
case <-r.Context().Done():
chat.Turns.Stop(sessionID)
return "", nil, true
sink := chatStreamSink{showToolCalls: s.chatShowToolCalls()}
for event := range events {
sink.write = func(frame chatStreamEvent) { writeChatEvent(frame, event.SessionID) }
switch event.Kind {
case "tool":
sink.ToolCall(event.Tool)
case "media":
sink.Media(event.Media)
default:
writeChatEvent(chatStreamEvent{Type: event.Kind, Text: event.Text}, event.SessionID)
}
}
}
@@ -488,7 +410,12 @@ func (s *Server) handleChatCancel(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
if chat.Turns == nil {
snapshot, err := chat.Contract.Snapshot(r.Context())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if !snapshot.CancellationAvailable {
http.Error(w, "chat cancellation is not configured", http.StatusNotImplemented)
return
}
@@ -497,17 +424,21 @@ func (s *Server) handleChatCancel(w http.ResponseWriter, r *http.Request) {
http.Error(w, "session_id is required", http.StatusBadRequest)
return
}
session, err := chat.Sessions.Get(r.Context(), req.SessionID)
session, found, err := chat.Contract.GetSession(r.Context(), req.SessionID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if session == nil || session.Source.Platform != "web" {
if !found || session.Source.Platform != "web" {
http.Error(w, "session not found", http.StatusNotFound)
return
}
cancelled, dropped := chat.Turns.Stop(req.SessionID)
writeJSON(w, map[string]any{"cancelled": cancelled, "dropped": dropped})
result, err := chat.Contract.Cancel(r.Context(), req.SessionID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
writeJSON(w, map[string]any{"cancelled": result.Cancelled, "dropped": result.Dropped})
}
func (s *Server) handleChatPersona(w http.ResponseWriter, r *http.Request) {
@@ -515,7 +446,12 @@ func (s *Server) handleChatPersona(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
if chat.Personas == nil {
snapshot, err := chat.Contract.Snapshot(r.Context())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if !snapshot.PersonasAvailable {
http.Error(w, "personality switching is not configured", http.StatusNotImplemented)
return
}
@@ -524,14 +460,19 @@ func (s *Server) handleChatPersona(w http.ResponseWriter, r *http.Request) {
http.Error(w, "session_id and name are required", http.StatusBadRequest)
return
}
if session, err := chat.Sessions.Get(r.Context(), req.SessionID); err != nil {
if session, found, err := chat.Contract.GetSession(r.Context(), req.SessionID); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
} else if session == nil || session.Source.Platform != "web" {
} else if !found || session.Source.Platform != "web" {
http.Error(w, "session not found", http.StatusNotFound)
return
}
if !chat.Personas.SetActive(req.SessionID, strings.ToLower(req.Name)) {
changed, err := chat.Contract.SetPersona(r.Context(), req.SessionID, strings.ToLower(req.Name))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if !changed {
http.Error(w, fmt.Sprintf("unknown personality %q", req.Name), http.StatusBadRequest)
return
}
@@ -693,76 +634,6 @@ func (s *Server) handleChatDangerousDecision(w http.ResponseWriter, r *http.Requ
writeJSON(w, map[string]any{"ok": true, "result": result})
}
func modelNames(models gateway.ModelManager) []string {
if models == nil {
return []string{}
}
return models.Models()
}
func activeModel(models gateway.ModelManager) string {
if models == nil {
return ""
}
return models.ActiveModel()
}
func activeProvider(models gateway.ModelManager) string {
manager, ok := models.(gateway.ProviderModelManager)
if !ok {
return ""
}
return manager.ActiveProvider()
}
func modelProviders(models gateway.ModelManager) []string {
manager, ok := models.(gateway.ProviderModelManager)
if !ok {
return []string{}
}
return manager.Providers()
}
func modelsByProvider(models gateway.ModelManager) map[string][]string {
if models == nil {
return map[string][]string{}
}
if manager, ok := models.(gateway.ProviderModelManager); ok {
groups := make(map[string][]string, len(manager.Providers()))
for _, provider := range manager.Providers() {
groups[provider] = manager.ModelsForProvider(provider)
}
return groups
}
groups := make(map[string][]string)
for _, model := range models.Models() {
provider, _, ok := strings.Cut(model, "/")
if !ok {
provider = ""
}
groups[provider] = append(groups[provider], model)
}
return groups
}
func activePersonas(personas *gateway.PersonaRegistry, sessions []gateway.SessionContext) map[string]string {
active := make(map[string]string, len(sessions))
if personas == nil {
return active
}
for _, session := range sessions {
active[session.SessionID] = personas.ActiveName(session.SessionID)
}
return active
}
func personaNames(personas *gateway.PersonaRegistry) []string {
if personas == nil {
return []string{}
}
return personas.List()
}
func newChatSourceID() string {
id, err := uuid.NewV7()
if err != nil {
+19 -27
View File
@@ -105,7 +105,7 @@ func TestChatSessionAndMessageEndpoints(t *testing.T) {
t.Cleanup(func() { _ = sessions.Close() })
router := gateway.NewRouter(chatStatusStub{}, nil, "web")
router.InitSessions(sessions)
server := &Server{Chat: &ChatService{Router: router, Sessions: sessions}}
server := &Server{Chat: testChatService(router, sessions, nil, nil, nil, nil, nil)}
session := gateway.SessionContext{
SessionID: "session-1",
Source: gateway.SessionSource{Platform: "web", ChannelID: "browser-1"},
@@ -179,12 +179,7 @@ func TestChatSessionsExposeActiveSelectorState(t *testing.T) {
router.InitSessions(sessions)
models := &chatProviderModelStub{active: "openrouter/sonnet"}
router.Models = models
server := &Server{Chat: &ChatService{
Router: router,
Models: models,
Sessions: sessions,
Personas: gateway.NewPersonaRegistry(gateway.DefaultPersonas()),
}}
server := &Server{Chat: testChatService(router, sessions, nil, models, gateway.NewPersonaRegistry(gateway.DefaultPersonas()), nil, nil)}
session := gateway.SessionContext{
SessionID: "selector-session",
Source: gateway.SessionSource{Platform: "web", ChannelID: "selector-browser"},
@@ -192,7 +187,7 @@ func TestChatSessionsExposeActiveSelectorState(t *testing.T) {
if err := sessions.Save(context.Background(), session); err != nil {
t.Fatal(err)
}
if !server.Chat.Personas.SetActive(session.SessionID, "concise") {
if !testLocalChat(server.Chat).Personas.SetActive(session.SessionID, "concise") {
t.Fatal("set active persona failed")
}
@@ -227,7 +222,7 @@ func TestChatUpdateEndpoints(t *testing.T) {
sessions := gateway.NewSessionStoreMemory()
t.Cleanup(func() { _ = sessions.Close() })
router := gateway.NewRouter(chatStatusStub{}, nil, "web")
server := &Server{Chat: &ChatService{Router: router, Sessions: sessions, Updates: updates}}
server := &Server{Chat: testChatService(router, sessions, nil, nil, nil, updates, nil)}
get := httptest.NewRecorder()
server.Handler().ServeHTTP(get, httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/api/chat/update", nil))
@@ -265,7 +260,7 @@ func TestChatUpdateEndpointRejectsTypedNilService(t *testing.T) {
sessions := gateway.NewSessionStoreMemory()
t.Cleanup(func() { _ = sessions.Close() })
router := gateway.NewRouter(chatStatusStub{}, nil, "web")
server := &Server{Chat: &ChatService{Router: router, Sessions: sessions, Updates: updates}}
server := &Server{Chat: testChatService(router, sessions, nil, nil, nil, updates, nil)}
res := httptest.NewRecorder()
server.Handler().ServeHTTP(res, httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/api/chat/update", nil))
@@ -279,7 +274,7 @@ func TestChatDangerousApprovalEndpoints(t *testing.T) {
t.Cleanup(func() { _ = sessions.Close() })
authority := &webDangerousStub{}
router := gateway.NewRouter(chatStatusStub{}, nil, "web")
server := &Server{Chat: &ChatService{Router: router, Sessions: sessions, Dangerous: NewDangerousService(authority)}}
server := &Server{Chat: testChatService(router, sessions, nil, nil, nil, nil, NewDangerousService(authority))}
state := httptest.NewRecorder()
server.Handler().ServeHTTP(state, httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/api/chat/dangerous", nil))
@@ -311,10 +306,7 @@ func TestChatCommandCatalogIncludesEnabledCapabilities(t *testing.T) {
sessions := gateway.NewSessionStoreMemory()
t.Cleanup(func() { _ = sessions.Close() })
router := gateway.NewRouter(chatStatusStub{}, nil, "web")
server := &Server{Chat: &ChatService{
Router: router, Sessions: sessions,
Updates: &chatUpdateStub{}, Dangerous: NewDangerousService(&webDangerousStub{}),
}}
server := &Server{Chat: testChatService(router, sessions, nil, nil, nil, &chatUpdateStub{}, NewDangerousService(&webDangerousStub{}))}
res := httptest.NewRecorder()
server.Handler().ServeHTTP(res, httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/api/chat/sessions", nil))
if res.Code != http.StatusOK {
@@ -343,7 +335,7 @@ func TestChatCancelEndpointStopsSessionTurn(t *testing.T) {
router := gateway.NewRouter(chatStatusStub{}, nil, "web")
router.InitSessions(sessions)
turns := gateway.NewTurns(slog.Default())
server := &Server{Chat: &ChatService{Router: router, Sessions: sessions, Turns: turns}}
server := &Server{Chat: testChatService(router, sessions, turns, nil, nil, nil, nil)}
if err := sessions.Save(context.Background(), gateway.SessionContext{
SessionID: "session-1", Source: gateway.SessionSource{Platform: "web", ChannelID: "browser-1"},
}); err != nil {
@@ -389,7 +381,7 @@ func chatTestServer(t *testing.T) (*Server, gateway.SessionStore) {
t.Cleanup(func() { _ = sessions.Close() })
router := gateway.NewRouter(chatStatusStub{}, nil, "web")
router.InitSessions(sessions)
return &Server{Chat: &ChatService{Router: router, Sessions: sessions}}, sessions
return &Server{Chat: testChatService(router, sessions, nil, nil, nil, nil, nil)}, sessions
}
func saveWebSession(t *testing.T, sessions gateway.SessionStore, id string) {
@@ -580,7 +572,7 @@ func TestChatStreamEndsWithDone(t *testing.T) {
func TestChatStreamDeltas(t *testing.T) {
server, sessions := chatTestServer(t)
var gotDeltas []string
server.Chat.Router.LLMStream = func(_ context.Context, _ gateway.Message, stream gateway.TurnStream) (string, error) {
testLocalChat(server.Chat).Router.LLMStream = func(_ context.Context, _ gateway.Message, stream gateway.TurnStream) (string, error) {
stream.Delta("part one")
stream.Delta("part two")
return "full reply", nil
@@ -636,13 +628,13 @@ func TestChatStreamReportsToolCalls(t *testing.T) {
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
server, sessions := chatTestServer(t)
server.Chat.Router.LLMStream = stream
testLocalChat(server.Chat).Router.LLMStream = stream
// Enabled explicitly: this test exercises the tool-narration
// path itself, which is off by default (see
// TestChatStreamHidesToolCallsWhenShowToolCallsIsOff).
server.Cfg = config.NewHolder(config.Config{Chat: config.ChatConfig{ShowToolCalls: true}})
if tc.queued {
server.Chat.Turns = gateway.NewTurns(slog.Default())
testLocalChat(server.Chat).Turns = gateway.NewTurns(slog.Default())
}
saveWebSession(t, sessions, "web-1")
@@ -698,7 +690,7 @@ func TestChatStreamRendersMediaAsALinkFallback(t *testing.T) {
}
server, sessions := chatTestServer(t)
server.Chat.Router.LLMStream = stream
testLocalChat(server.Chat).Router.LLMStream = stream
saveWebSession(t, sessions, "web-1")
req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/api/chat/stream",
@@ -730,7 +722,7 @@ func TestChatStreamSkipsMediaWithNoURL(t *testing.T) {
}
server, sessions := chatTestServer(t)
server.Chat.Router.LLMStream = stream
testLocalChat(server.Chat).Router.LLMStream = stream
saveWebSession(t, sessions, "web-1")
req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/api/chat/stream",
@@ -774,7 +766,7 @@ func TestChatStreamHidesToolCallsWhenShowToolCallsIsOff(t *testing.T) {
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
server, sessions := chatTestServer(t)
server.Chat.Router.LLMStream = stream
testLocalChat(server.Chat).Router.LLMStream = stream
server.Cfg = tc.cfg
saveWebSession(t, sessions, "web-1")
@@ -801,7 +793,7 @@ func TestChatStreamHidesToolCallsWhenShowToolCallsIsOff(t *testing.T) {
// and an unconfigured registry degrades to 501.
func TestChatPersonaEndpoint(t *testing.T) {
server, sessions := chatTestServer(t)
server.Chat.Personas = gateway.NewPersonaRegistry(gateway.DefaultPersonas())
testLocalChat(server.Chat).Personas = gateway.NewPersonaRegistry(gateway.DefaultPersonas())
saveWebSession(t, sessions, "web-1")
post := func(body string) *httptest.ResponseRecorder {
@@ -856,7 +848,7 @@ func TestChatStreamReportsUndeliverableLocalFile(t *testing.T) {
}
server, sessions := chatTestServer(t)
server.Chat.Router.LLMStream = stream
testLocalChat(server.Chat).Router.LLMStream = stream
saveWebSession(t, sessions, "web-1")
req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/api/chat/stream",
@@ -888,7 +880,7 @@ func TestChatStreamReportsUndeliverableLocalFile(t *testing.T) {
func TestChatStreamCarriesCurrentPage(t *testing.T) {
server, sessions := chatTestServer(t)
var got gateway.Message
server.Chat.Router.LLMStream = func(_ context.Context, msg gateway.Message, stream gateway.TurnStream) (string, error) {
testLocalChat(server.Chat).Router.LLMStream = func(_ context.Context, msg gateway.Message, stream gateway.TurnStream) (string, error) {
got = msg
stream.Delta("on it")
return "on it", nil
@@ -930,7 +922,7 @@ func TestChatStreamEmitsNavigateChip(t *testing.T) {
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
server, sessions := chatTestServer(t)
server.Chat.Router.LLMStream = stream
testLocalChat(server.Chat).Router.LLMStream = stream
server.Cfg = tc.cfg
saveWebSession(t, sessions, "web-1")
+43 -243
View File
@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"mime"
"net/http"
@@ -13,7 +12,9 @@ import (
"strings"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/taskactions"
"github.com/samcharles93/archie-core/internal/events"
taskactionstore "github.com/samcharles93/archie-core/internal/infrastructure/taskactions"
"github.com/samcharles93/archie-core/internal/store"
"github.com/samcharles93/archie-core/internal/taskstate"
)
@@ -146,36 +147,20 @@ func (s *Server) handleTaskAction(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
task, err := s.Store.TaskByID(r.Context(), id)
if err != nil {
s.logf("task action lookup failed", "task", id, "err", err)
http.Error(w, "task action failed", http.StatusInternalServerError)
if err := s.TaskActionService().Apply(r.Context(), nil, id, action); err != nil {
switch {
case errors.Is(err, taskactions.ErrNotFound):
http.Error(w, "task not found", http.StatusNotFound)
case errors.Is(err, taskactions.ErrConflict), errors.Is(err, store.ErrStaleTransition):
http.Error(w, err.Error(), http.StatusConflict)
case errors.Is(err, taskactions.ErrUnavailable):
http.Error(w, err.Error(), http.StatusServiceUnavailable)
default:
s.logf("task action failed", "task", id, "err", err)
http.Error(w, "task action failed", http.StatusInternalServerError)
}
return
}
if task == nil {
http.Error(w, "task not found", http.StatusNotFound)
return
}
if err := taskstate.CheckAction(task.Status, action); err != nil {
http.Error(w, err.Error(), http.StatusConflict)
return
}
// Each action reports the event to record, or writes its own error
// response and returns nothing. Keeping the dispatch flat here and the
// rules in one function each is what stops this growing back into a
// single branch nobody can read.
outcome := s.applyTaskAction(r.Context(), w, task, action)
if outcome == nil {
return
}
s.emit(r.Context(), events.Event{
ID: outcome.eventID,
Kind: outcome.kind, TaskID: task.ID,
Repo: task.Owner + "/" + task.Repo, Issue: task.IssueNumber,
Detail: outcome.detail, Data: outcome.data,
})
writeJSON(w, map[string]any{"ok": true, "action": action, "task_id": id})
}
@@ -204,32 +189,6 @@ func decodeTaskAction(w http.ResponseWriter, r *http.Request) (taskstate.Action,
return action, true
}
func (s *Server) applyTaskAction(
ctx context.Context,
w http.ResponseWriter,
task *store.Task,
action taskstate.Action,
) *actionOutcome {
switch action {
case taskstate.ActionCancel:
return s.declineTask(ctx, w, task, store.StatusQueued, events.KindTaskCancelled, "cancelled")
case taskstate.ActionStop:
return s.stopTask(ctx, w, task)
case taskstate.ActionApprove:
return s.approveTask(ctx, w, task)
case taskstate.ActionRetry:
return s.retryTask(ctx, w, task)
case taskstate.ActionReject:
return s.rejectTask(ctx, w, task)
case taskstate.ActionAbandon:
return s.declineTask(ctx, w, task, store.StatusParked, events.KindTaskAbandoned, "abandoned")
case taskstate.ActionArchive:
return s.archiveTask(ctx, w, task)
default:
return nil
}
}
func taskMutation(action taskstate.Action) bool {
switch action {
case taskstate.ActionCancel, taskstate.ActionStop, taskstate.ActionApprove,
@@ -315,205 +274,46 @@ func validOrigin(u *url.URL, wantScheme, wantHost string) bool {
return strings.EqualFold(u.Scheme, wantScheme) && strings.EqualFold(u.Host, wantHost)
}
// actionOutcome is what a completed operator action should record.
type actionOutcome struct {
kind string
detail string
data map[string]any
eventID int64
// TaskActionService supplies the same operator action implementation used by
// the daemon's task-control endpoint.
func (s *Server) TaskActionService() taskactions.Service {
return taskactionstore.NewService(
taskactionstore.Store{TaskStore: s.Store},
taskactionstore.MaxRetries(s.Cfg),
s.taskStopper(),
s.issueCloser(),
s.logRemover(),
s.eventPublisher(),
s.logf,
)
}
// storeFailed writes the response for a failed store write and reports
// whether it did. A store write that fails is not the caller's fault;
// answering 409 made the UI say "conflict" for a broken database.
func (s *Server) storeFailed(w http.ResponseWriter, err error) bool {
if err == nil {
return false
}
if errors.Is(err, store.ErrStaleTransition) {
http.Error(w, "task changed state; refresh and try again", http.StatusConflict)
return true
}
s.logf("task action store write failed", "err", err)
http.Error(w, "task action failed", http.StatusInternalServerError)
return true
}
func (s *Server) declineTask(
ctx context.Context,
w http.ResponseWriter,
task *store.Task,
from, kind, verb string,
) *actionOutcome {
detail := verb + " via the dashboard"
if s.storeFailed(w, s.Store.Transition(ctx, task.ID, from, store.StatusClosedWontDo, detail)) {
return nil
}
s.closeDeclinedIssue(ctx, task, verb)
return &actionOutcome{kind: kind, detail: detail}
}
func (s *Server) stopTask(ctx context.Context, w http.ResponseWriter, task *store.Task) *actionOutcome {
func (s *Server) taskStopper() func(int64) bool {
if s.TaskStopper == nil {
http.Error(w, "runtime task control is unavailable", http.StatusServiceUnavailable)
return nil
}
cancelled := s.TaskStopper.CancelTask(task.ID)
detail := "stopped via the dashboard; recoverable work remains parked"
if !cancelled {
// A running row without a runtime entry is stale work from a crashed or
// migrated process. Nothing is executing, but parking the guarded row
// still gives the operator the promised recoverable state.
detail = "no active execution was found; recoverable work was parked via the dashboard"
}
if s.storeFailed(w, s.Store.Transition(ctx, task.ID, store.StatusRunning, store.StatusParked, detail)) {
return nil
}
return &actionOutcome{kind: events.KindTaskStopped, detail: detail}
return s.TaskStopper.CancelTask
}
func (s *Server) archiveTask(ctx context.Context, w http.ResponseWriter, task *store.Task) *actionOutcome {
detail := "archive requested via the dashboard"
eventID, err := s.Store.ArchiveTask(ctx, task.ID, task.Status, events.Event{
Kind: events.KindTaskArchiveRequested, TaskID: task.ID,
Repo: task.Owner + "/" + task.Repo, Issue: task.IssueNumber,
Detail: detail,
})
if s.storeFailed(w, err) {
return nil
}
// Best-effort: an archived task's log files not getting cleaned up is
// far less costly than the archive action itself failing over it, so
// this never blocks the response the way s.storeFailed above does.
//
// Known, accepted gap: a task reaches a terminal status (satisfying
// ArchiveTask's precondition) partway through Daemon.process, but its
// TaskLogs sink isn't closed until process() itself returns -- which can
// be later, if teardown after the terminal transition takes any time at
// all. A system-log message landing in that window races this Remove
// with an open Write to the same directory. Not corrupting (the write
// lands on a soon-to-be-unlinked inode and is discarded) and not worth
// closing here: doing so would mean tying TaskLogs.Close to the store
// transition instead of to process()'s return, a larger change than
// this call site should make unilaterally.
if err := s.TaskLogs.Remove(task.ID); err != nil {
s.Log.Warn("task log cleanup failed", "task", task.ID, "err", err)
}
return &actionOutcome{kind: events.KindTaskArchiveRequested, detail: detail, eventID: eventID}
}
func (s *Server) approveTask(ctx context.Context, w http.ResponseWriter, task *store.Task) *actionOutcome {
if err := taskstate.CheckApprove(task.Status); err != nil {
http.Error(w, err.Error(), http.StatusConflict)
return nil
}
if s.storeFailed(w, s.Store.Requeue(ctx, task.ID, store.StatusWaitingHuman, "implement")) {
return nil
}
return &actionOutcome{kind: events.KindHumanApproved, detail: "approved via the dashboard"}
}
// retryTask requeues a parked task, or retires it once max_retries is spent.
//
// max_retries was configured, defaulted and reported by /api/config while
// nothing enforced it: retry_count climbed forever, so a task that fails
// every time could be retried without limit. At the cap the task belongs in
// dead, which is what the setting exists to say.
func (s *Server) retryTask(ctx context.Context, w http.ResponseWriter, task *store.Task) *actionOutcome {
if err := taskstate.CheckRetry(task.Status); err != nil {
http.Error(w, err.Error(), http.StatusConflict)
return nil
}
if limit := s.maxRetriesFor(task); limit > 0 && task.RetryCount >= limit {
s.retireTask(ctx, task, fmt.Sprintf("max retries reached (%d/%d)", task.RetryCount, limit))
http.Error(w, fmt.Sprintf("max retries reached (%d/%d)", task.RetryCount, limit), http.StatusConflict)
return nil
}
if s.storeFailed(w, s.Store.RetryTask(ctx, task.ID, store.StatusParked, "")) {
return nil
}
return &actionOutcome{
kind: events.KindTaskRetried,
detail: "retried via the dashboard",
data: map[string]any{
"retry_count": task.RetryCount + 1,
"previous_stage": task.Stage,
"previous_reason": task.ParkReason,
},
}
}
// retireTask moves a spent task to dead. Failure is logged, not returned:
// the caller is already answering with the reason it refused the retry.
func (s *Server) retireTask(ctx context.Context, task *store.Task, reason string) {
if err := s.Store.Transition(ctx, task.ID, store.StatusParked, store.StatusDead, reason); err != nil {
s.logf("transition to dead failed", "task", task.ID, "err", err)
return
}
s.emit(ctx, events.Event{
Kind: events.KindTaskDead, TaskID: task.ID,
Repo: task.Owner + "/" + task.Repo, Issue: task.IssueNumber, Detail: reason,
})
}
func (s *Server) rejectTask(ctx context.Context, w http.ResponseWriter, task *store.Task) *actionOutcome {
// Reject is available from any non-terminal lifecycle state: work the
// operator refuses belongs in the terminal Declined state regardless of
// where it currently sits. Running work is interrupted first so nothing
// keeps executing against a task that is being closed out.
if task.Status == store.StatusRunning && s.TaskStopper != nil {
s.TaskStopper.CancelTask(task.ID)
}
err := s.Store.Transition(ctx, task.ID, task.Status, store.StatusClosedWontDo, "declined from the dashboard")
if s.storeFailed(w, err) {
return nil
}
s.closeDeclinedIssue(ctx, task, "rejected")
return &actionOutcome{kind: events.KindHumanRejected, detail: "rejected via the dashboard"}
}
// maxRetriesFor resolves the retry cap for a task, honouring a per-repo
// override. Zero means unlimited.
func (s *Server) maxRetriesFor(task *store.Task) int {
if s.Cfg == nil {
return 0
}
cfg := s.Cfg.Get()
for _, repo := range cfg.Repos {
if repo.Owner == task.Owner && repo.Name == task.Repo {
return repo.EffectiveMaxRetries(cfg.MaxRetries)
}
}
return cfg.MaxRetries
}
// closeRejectedIssue closes the forge issue behind a task the operator has
// declined.
//
// Without this the issue stays open, labelled and assigned, so the next poll
// re-enqueues it -- and once the operator uses Clear, which deletes the task
// row, that is a second implementation and a second PR for work already
// refused. Approve and retry deliberately leave the issue open: the task is
// going back to work.
//
// Failure is logged, not returned. The operator's decision is already
// recorded, and reporting an error would invite them to click again.
func (s *Server) closeDeclinedIssue(ctx context.Context, task *store.Task, verb string) {
func (s *Server) issueCloser() func(context.Context, string, string, int, string) error {
if s.Issues == nil {
s.logf("task rejected but no forge is wired; the issue stays open and will be re-polled",
"task", task.ID, "issue", task.IssueNumber)
return
return nil
}
// A chat task's issue number is synthetic and matches no forge issue.
if !task.IsForgeBacked() {
return
return s.Issues.CloseIssue
}
func (s *Server) logRemover() func(int64) error {
if s.TaskLogs == nil {
return nil
}
comment := fmt.Sprintf("Closing: this task was %s from the archie dashboard. "+
"Reopen the issue to have archie pick it up again.", verb)
if err := s.Issues.CloseIssue(ctx, task.Owner, task.Repo, task.IssueNumber, comment); err != nil {
s.logf("closing rejected issue failed; it stays open and will be re-polled",
"task", task.ID, "issue", task.IssueNumber, "err", err)
return s.TaskLogs.Remove
}
func (s *Server) eventPublisher() func(events.Event) {
if s.Events == nil {
return nil
}
return s.Events.Publish
}
// emit publishes an operator action so it reaches the task timeline and the
+2 -2
View File
@@ -85,7 +85,7 @@ func TestHandleVersionComposesCheckAndRunningVersions(t *testing.T) {
{ID: "agent", Label: "Runtime", Installed: "1.0.0", InstallType: "container", Reference: "img@sha256:abc"},
}}}
server := &Server{
Chat: &ChatService{Router: gateway.NewRouter(chatStatusStub{}, nil, "web"), Sessions: sessions, Updates: updates},
Chat: testChatService(gateway.NewRouter(chatStatusStub{}, nil, "web"), sessions, nil, nil, nil, updates, nil),
RunningVersions: func() map[string]string { return map[string]string{"daemon": "1.0.0"} },
}
@@ -130,7 +130,7 @@ func TestHandleVersionTreatsPresentButEmptyRunningVersionAsUnobserved(t *testing
{ID: "agent", Label: "Runtime", Installed: "1.0.0"},
}}}
server := &Server{
Chat: &ChatService{Router: gateway.NewRouter(chatStatusStub{}, nil, "web"), Sessions: sessions, Updates: updates},
Chat: testChatService(gateway.NewRouter(chatStatusStub{}, nil, "web"), sessions, nil, nil, nil, updates, nil),
RunningVersions: func() map[string]string { return map[string]string{"agent": ""} },
}
+17
View File
@@ -0,0 +1,17 @@
package webui
import "github.com/samcharles93/archie-core/internal/gateway"
func testChatService(router *gateway.Router, sessions gateway.SessionStore, turns *gateway.Turns, models gateway.ModelManager, personas *gateway.PersonaRegistry, updates ChatUpdateService, dangerous *DangerousService) *ChatService {
return &ChatService{Contract: &gateway.LocalChatAdapter{
Router: router, Sessions: sessions, Turns: turns, Models: models, Personas: personas,
}, Updates: updates, Dangerous: dangerous}
}
func testLocalChat(service *ChatService) *gateway.LocalChatAdapter {
local, ok := service.Contract.(*gateway.LocalChatAdapter)
if !ok {
panic("test chat contract is not local")
}
return local
}
+2 -2
View File
@@ -120,8 +120,8 @@ type Server struct {
// an empty curator list rather than failing the dashboard.
Curators *curator.Registry
// Chat exposes the same gateway router used by the conversational
// channels. Optional: the dashboard simply omits chat when it is nil.
// Chat exposes the Gateway's wire-safe conversational contract. Optional:
// the dashboard simply omits chat when it is nil.
Chat *ChatService
// Health runs the operator readiness probes served by /health/detailed.
+2 -2
View File
@@ -144,7 +144,7 @@ func TestHandleChatUpdateInstallSetsReportPath(t *testing.T) {
sessions := gateway.NewSessionStoreMemory()
t.Cleanup(func() { _ = sessions.Close() })
router := gateway.NewRouter(chatStatusStub{}, nil, "web")
server := &Server{Chat: &ChatService{Router: router, Sessions: sessions, Updates: updates}, UpdateReportPath: reportPath}
server := &Server{Chat: testChatService(router, sessions, nil, nil, nil, updates, nil), UpdateReportPath: reportPath}
body, err := json.Marshal(chatUpdateRequest{Snapshot: updates.snapshot})
if err != nil {
@@ -169,7 +169,7 @@ func TestHandleChatUpdateInstallRoutesRestartReportToTelegram(t *testing.T) {
t.Cleanup(func() { _ = sessions.Close() })
router := gateway.NewRouter(chatStatusStub{}, nil, "web")
server := &Server{
Chat: &ChatService{Router: router, Sessions: sessions, Updates: updates},
Chat: testChatService(router, sessions, nil, nil, nil, updates, nil),
UpdateReportPath: filepath.Join(t.TempDir(), "webui-update-report.json"),
TelegramUpdateReportPath: reportPath,
TelegramUpdateChatID: 42,
+26
View File
@@ -0,0 +1,26 @@
# Service wire contracts
Each canonical service owns `proto/<service>/v1/*.proto` in this single Buf
module. The service directory matches its registry, DNS and chart name.
Breaking changes require a new `v2`, `v3`, etc. directory; retain published
versions for existing consumers. Buf's FILE rules compare against local `main`.
The first introduction skips that comparison only when `main` has no Buf config.
Run `task proto:install` once to install the pinned Buf and Go plugins, with
`$(go env GOPATH)/bin` on PATH. Run `task proto:generate` after editing a schema.
Managed mode sets Go package paths; do not set `go_package` in the source.
Generated grpc-go and protobuf files belong in `internal/contracts/<service>/v1/`
and must be committed, including formatter output. This directory is generated
in full; handwritten adapters belong outside it.
`task proto:lint` checks lint and compatibility; `task proto:check` regenerates
and rejects differences or untracked generated files. Both run in `task check`
and the deployment quality gate. Normal build and test commands use committed
Go files and do not require Buf.
Compatibility smoke verification (2026-09-05): copied the gateway schema and
gate script into a temporary Git repository, committed it on `main`, and ran
the lint gate from a linked worktree. The unchanged schema passed. Deleting
`ChatService.Cancel` then failed with `Previously present RPC "Cancel" on
service "ChatService" was deleted.` This exercises the same Git-baseline
comparison as the gate without modifying the working schema or real `main`.
+14
View File
@@ -0,0 +1,14 @@
version: v2
clean: true
managed:
enabled: true
override:
- file_option: go_package_prefix
value: github.com/samcharles93/archie-core/internal/contracts
plugins:
- local: protoc-gen-go
out: ../internal/contracts
opt: paths=source_relative
- local: protoc-gen-go-grpc
out: ../internal/contracts
opt: paths=source_relative
+9
View File
@@ -0,0 +1,9 @@
version: v2
modules:
- path: .
lint:
use:
- STANDARD
breaking:
use:
- FILE
+113
View File
@@ -0,0 +1,113 @@
syntax = "proto3";
package gateway.v1;
import "google/protobuf/timestamp.proto";
service ChatService {
rpc Snapshot(SnapshotRequest) returns (SnapshotResponse);
rpc GetSession(GetSessionRequest) returns (GetSessionResponse);
rpc RecentMessages(RecentMessagesRequest) returns (RecentMessagesResponse);
rpc RecentTurns(RecentTurnsRequest) returns (RecentTurnsResponse);
rpc Route(RouteRequest) returns (RouteResponse);
rpc Stream(StreamRequest) returns (stream StreamResponse);
rpc Cancel(CancelRequest) returns (CancelResponse);
rpc SetPersona(SetPersonaRequest) returns (SetPersonaResponse);
rpc ApplyTaskAction(ApplyTaskActionRequest) returns (ApplyTaskActionResponse);
}
message Session {
string session_id = 1;
string platform = 2;
string bot_user = 3;
string channel_id = 4;
string thread_id = 5;
string title = 6;
string parent_session_id = 7;
string branch_name = 8;
google.protobuf.Timestamp created_at = 9;
google.protobuf.Timestamp last_active_at = 10;
}
message Message {
string message_id = 1;
string source_id = 2;
string channel_id = 3;
string thread_id = 4;
string from = 5;
string text = 6;
string page = 7;
google.protobuf.Timestamp at = 8;
}
message ToolCall {
string id = 1;
string name = 2;
string parameters = 3;
string output = 4;
string error = 5;
}
message Media {
string tool_name = 1;
string type = 2;
string file_id = 3;
string url = 4;
string path = 5;
string mime_type = 6;
string file_name = 7;
optional int64 file_size = 8;
optional int64 width = 9;
optional int64 height = 10;
optional int64 duration = 11;
}
message Turn {
string turn_id = 1;
string session_id = 2;
string source_id = 3;
string status = 4;
int64 attempt = 5;
string owner_id = 6;
string input_message_id = 7;
string assistant_message_id = 8;
string partial_text = 9;
string response_text = 10;
repeated ToolCall tool_calls = 11;
string error = 12;
google.protobuf.Timestamp created_at = 13;
google.protobuf.Timestamp updated_at = 14;
}
message StringList { repeated string values = 1; }
message SnapshotRequest {}
message SnapshotResponse {
repeated Session sessions = 1;
repeated string models = 2;
map<string, StringList> models_by_provider = 3;
repeated string providers = 4;
string active_model = 5;
string active_provider = 6;
repeated string personas = 7;
map<string, string> active_personas = 8;
bool restart_available = 9;
bool cancellation_available = 10;
bool personas_available = 11;
}
message GetSessionRequest { string session_id = 1; }
message GetSessionResponse { Session session = 1; bool found = 2; }
message RecentMessagesRequest { string session_id = 1; int64 limit = 2; }
message RecentMessagesResponse { repeated Message messages = 1; }
message RecentTurnsRequest { string session_id = 1; int64 limit = 2; }
message RecentTurnsResponse { repeated Turn turns = 1; }
message RouteRequest { Message message = 1; }
message RouteResponse { string text = 1; string session_id = 2; }
message StreamRequest { Message message = 1; }
message StreamResponse {
string kind = 1;
string text = 2;
string session_id = 3;
ToolCall tool = 4;
Media media = 5;
}
message CancelRequest { string session_id = 1; }
message CancelResponse { bool cancelled = 1; int64 dropped = 2; }
message SetPersonaRequest { string session_id = 1; string name = 2; }
message SetPersonaResponse { bool found = 1; }
message ApplyTaskActionRequest { string identity = 1; int64 task_id = 2; string action = 3; }
message ApplyTaskActionResponse { int64 task_id = 1; string action = 2; string message = 3; }
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
case "${1:-}" in
install)
go install github.com/bufbuild/buf/cmd/buf@v1.71.0
go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.36.11
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.6.2
;;
generate)
(cd proto && buf generate)
gofumpt -w internal/contracts
;;
lint)
(cd proto && buf lint)
# A missing main ref is an error; only the initial introduction of proto
# has no published contract to compare. Tags in CI also need this ref.
git rev-parse --verify refs/heads/main >/dev/null
if git cat-file -e main:proto/buf.yaml 2>/dev/null; then
buf breaking proto --against "$(git rev-parse --git-common-dir)#branch=main,subdir=proto"
else
echo 'No proto baseline on main yet; checking the first contract with buf lint.'
fi
;;
check)
bash tools/proto.sh generate
git diff --exit-code -- internal/contracts
if [[ -n "$(git ls-files --others --exclude-standard -- internal/contracts)" ]]; then
echo 'Generated contracts are untracked; add them before running proto:check.' >&2
exit 1
fi
;;
*)
echo 'usage: bash tools/proto.sh {install|generate|lint|check}' >&2
exit 2
;;
esac