feat(contracts): add gateway service seams and protobuf toolchain
This commit is contained in:
1 parent
3c304b26ce
commit
c0a91c011c
35 files changed
+3534
-255
No files matched your search
@@ -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
|
||||
|
||||
+23
-1
@@ -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:
|
||||
@@ -144,10 +164,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
|
||||
|
||||
@@ -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
|
||||
)
|
||||
@@ -1,7 +1,5 @@
|
||||
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=
|
||||
@@ -65,6 +63,8 @@ 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-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/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=
|
||||
@@ -103,12 +103,8 @@ 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/nats-io/jwt/v2 v2.8.2 h1:XXRgB60MSTnqsRwejQurVDs/hcv2dkt+86GjI+I/bMc=
|
||||
@@ -167,13 +163,10 @@ 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=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
|
||||
@@ -197,19 +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=
|
||||
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=
|
||||
golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo=
|
||||
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/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=
|
||||
|
||||
@@ -555,11 +555,14 @@ func (b *boot) setupLLMAndChat(ctx context.Context) {
|
||||
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{
|
||||
localChat := &gateway.LocalChatAdapter{
|
||||
Router: b.webRouter, Sessions: b.chatSessionStore,
|
||||
Turns: gateway.NewTurns(log),
|
||||
Models: b.chatModels, Personas: b.personas,
|
||||
}
|
||||
contract, closeContract := b.chatContract(cfg.Services.Gateway, localChat)
|
||||
b.addCleanup(closeContract)
|
||||
b.web.Chat = &webui.ChatService{Contract: contract}
|
||||
if b.updateService != nil {
|
||||
b.web.Chat.Updates = b.updateService
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc"
|
||||
)
|
||||
|
||||
// composeChatContract selects transport without involving network discovery
|
||||
// in local calls. The returned cleanup belongs to the application lifecycle.
|
||||
func composeChatContract(settings config.ServiceConnection, local gateway.ChatContract, options ...grpc.DialOption) (gateway.ChatContract, func(), error) {
|
||||
switch settings.Mode {
|
||||
case "", "inproc":
|
||||
if settings.Target != "" {
|
||||
return nil, nil, fmt.Errorf("gateway target requires remote mode")
|
||||
}
|
||||
return local, func() {}, nil
|
||||
case "remote":
|
||||
if strings.TrimSpace(settings.Target) == "" {
|
||||
return nil, nil, fmt.Errorf("remote gateway requires a target")
|
||||
}
|
||||
opts := append([]grpc.DialOption{grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{MinVersion: tls.VersionTLS12}))}, 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
|
||||
default:
|
||||
return nil, nil, fmt.Errorf("unknown gateway service mode %q", settings.Mode)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *boot) chatContract(settings config.ServiceConnection, local gateway.ChatContract) (gateway.ChatContract, func()) {
|
||||
contract, cleanup, err := composeChatContract(settings, local)
|
||||
if err != nil {
|
||||
b.log.Error("configure gateway contract", "error", err)
|
||||
return nil, func() {}
|
||||
}
|
||||
return contract, cleanup
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
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 TestComposeChatContractLocal(t *testing.T) {
|
||||
for _, mode := range []string{"", "inproc"} {
|
||||
t.Run("mode="+mode, func(t *testing.T) {
|
||||
local := &gateway.LocalChatAdapter{}
|
||||
chat, cleanup, err := composeChatContract(config.ServiceConnection{Mode: mode}, local)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cleanup == nil {
|
||||
t.Fatal("local composition returned no cleanup")
|
||||
}
|
||||
t.Cleanup(cleanup)
|
||||
if chat != local {
|
||||
t.Fatalf("local composition returned %T instead of the supplied adapter", chat)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestComposeChatContractRejectsInvalidSettings(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
settings config.ServiceConnection
|
||||
}{
|
||||
{name: "unknown mode", settings: config.ServiceConnection{Mode: "automatic"}},
|
||||
{name: "default with target", settings: config.ServiceConnection{Target: "localhost:1234"}},
|
||||
{name: "inproc with target", settings: config.ServiceConnection{Mode: "inproc", Target: "localhost:1234"}},
|
||||
{name: "remote missing target", settings: config.ServiceConnection{Mode: "remote"}},
|
||||
{name: "remote blank target", settings: config.ServiceConnection{Mode: "remote", Target: " \t\n"}},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
chat, cleanup, err := composeChatContract(tt.settings, &gateway.LocalChatAdapter{})
|
||||
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)
|
||||
}
|
||||
})
|
||||
|
||||
local := compositionChat{snapshot: gateway.ChatSnapshot{ActiveModel: "local-model"}}
|
||||
chat, cleanup, err := composeChatContract(
|
||||
config.ServiceConnection{Mode: "remote", Target: "passthrough:///chat"}, local,
|
||||
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
|
||||
}
|
||||
@@ -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:
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package config
|
||||
|
||||
// Services selects contract adapters at application composition time.
|
||||
type Services struct {
|
||||
Gateway ServiceConnection `toml:"gateway" yaml:"gateway"`
|
||||
}
|
||||
|
||||
// ServiceConnection selects local calls or a TLS gRPC target. It does not
|
||||
// register services or start listeners. Changes require a daemon restart.
|
||||
type ServiceConnection struct {
|
||||
Mode string `toml:"mode" yaml:"mode"`
|
||||
Target string `toml:"target" yaml:"target"`
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,391 @@
|
||||
// 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"
|
||||
)
|
||||
|
||||
// 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)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
// 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)
|
||||
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) 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)
|
||||
}
|
||||
|
||||
// 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,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{
|
||||
{
|
||||
StreamName: "Stream",
|
||||
Handler: _ChatService_Stream_Handler,
|
||||
ServerStreams: true,
|
||||
},
|
||||
},
|
||||
Metadata: "gateway/v1/chat.proto",
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package gateway
|
||||
|
||||
import "context"
|
||||
|
||||
// ChatContract is the conversational boundary consumed by channel frontends.
|
||||
// Results are snapshots: callers must not rely on shared object identity.
|
||||
type ChatContract interface {
|
||||
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)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
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) 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})
|
||||
}
|
||||
@@ -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.Mode == "" {
|
||||
cfg.Services.Gateway.Mode = "inproc"
|
||||
}
|
||||
l.applyGeneralDefaults(cfg)
|
||||
applyForgeDefaults(cfg)
|
||||
applyDispatchDefaults(cfg)
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package configuration
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLoadGatewayServiceMode(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name, section string
|
||||
wantError bool
|
||||
}{
|
||||
{name: "default"},
|
||||
{name: "local", section: "[services.gateway]\nmode = 'inproc'"},
|
||||
{name: "remote", section: "[services.gateway]\nmode = 'remote'\ntarget = 'dns:///gateway:8443'"},
|
||||
{name: "invalid mode", section: "[services.gateway]\nmode = 'typo'", wantError: true},
|
||||
{name: "remote without target", section: "[services.gateway]\nmode = 'remote'", wantError: true},
|
||||
{name: "local with ignored target", section: "[services.gateway]\nmode = 'inproc'\ntarget = 'gateway:8443'", wantError: true},
|
||||
} {
|
||||
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) != tt.wantError {
|
||||
t.Fatalf("load error = %v, want error %v", err, tt.wantError)
|
||||
}
|
||||
if err == nil {
|
||||
want := "inproc"
|
||||
if tt.name == "remote" {
|
||||
want = "remote"
|
||||
if cfg.Services.Gateway.Target != "dns:///gateway:8443" {
|
||||
t.Fatalf("target = %q", cfg.Services.Gateway.Target)
|
||||
}
|
||||
}
|
||||
if cfg.Services.Gateway.Mode != want {
|
||||
t.Fatalf("mode = %q, want %q", cfg.Services.Gateway.Mode, want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -59,6 +59,9 @@ func Validate(cfg *config.Config) error {
|
||||
// validate reports the first problem that would stop the daemon running.
|
||||
// It does not modify cfg -- run applyDefaults first.
|
||||
func validate(cfg *config.Config) error {
|
||||
if err := validateGatewayService(cfg.Services.Gateway); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateDispatch(cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -93,6 +96,22 @@ func validate(cfg *config.Config) error {
|
||||
return validateCapture(cfg)
|
||||
}
|
||||
|
||||
func validateGatewayService(service config.ServiceConnection) error {
|
||||
switch service.Mode {
|
||||
case "", "inproc":
|
||||
if service.Target != "" {
|
||||
return fmt.Errorf("%w: services.gateway.target requires remote mode", ErrInvalidInput)
|
||||
}
|
||||
case "remote":
|
||||
if strings.TrimSpace(service.Target) == "" {
|
||||
return fmt.Errorf("%w: services.gateway.target is required in remote mode", ErrInvalidInput)
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("%w: services.gateway.mode must be inproc or remote", ErrInvalidInput)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateImage rejects an enabled hosted provider with no class or no
|
||||
// resolvable credential, and a Default naming a provider that is not both
|
||||
// present and enabled -- either would let /image silently fall back to
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
// 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"
|
||||
)
|
||||
|
||||
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) 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,95 @@
|
||||
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"
|
||||
)
|
||||
|
||||
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) 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}
|
||||
}
|
||||
@@ -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
@@ -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 {
|
||||
|
||||
@@ -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")
|
||||
|
||||
|
||||
@@ -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": ""} },
|
||||
}
|
||||
|
||||
|
||||
@@ -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 ChatService does not use LocalChatAdapter")
|
||||
}
|
||||
return local
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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`.
|
||||
@@ -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
|
||||
@@ -0,0 +1,9 @@
|
||||
version: v2
|
||||
modules:
|
||||
- path: .
|
||||
lint:
|
||||
use:
|
||||
- STANDARD
|
||||
breaking:
|
||||
use:
|
||||
- FILE
|
||||
@@ -0,0 +1,110 @@
|
||||
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);
|
||||
}
|
||||
|
||||
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; }
|
||||
@@ -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
|
||||
Reference in new issue
Block a user