From c0a91c011c7c92a9919730487576bad3dd786eef Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sat, 5 Sep 2026 22:39:17 +1000 Subject: [PATCH] feat(contracts): add gateway service seams and protobuf toolchain --- .github/workflows/deploy.yml | 11 + Taskfile.yml | 24 +- go.mod | 4 +- go.sum | 26 +- internal/app/archied/bootstrap.go | 5 +- internal/app/archied/chat_service.go | 47 + internal/app/archied/chat_service_test.go | 119 ++ internal/app/archied/readiness.go | 6 +- internal/app/archied/readiness_test.go | 7 +- internal/config/config.go | 3 +- internal/config/services.go | 13 + internal/contracts/gateway/v1/chat.pb.go | 1755 +++++++++++++++++ internal/contracts/gateway/v1/chat_grpc.pb.go | 391 ++++ internal/gateway/chat_contract.go | 51 + internal/gateway/chat_local.go | 196 ++ internal/gateway/chat_local_test.go | 38 + .../infrastructure/configuration/defaults.go | 3 + .../configuration/services_test.go | 44 + .../infrastructure/configuration/validate.go | 19 + internal/infrastructure/gatewayrpc/client.go | 109 + .../gatewayrpc/conformance_test.go | 106 + internal/infrastructure/gatewayrpc/server.go | 95 + internal/infrastructure/gatewayrpc/values.go | 181 ++ internal/servicediscovery/servicediscovery.go | 2 + internal/webui/api_chat.go | 261 +-- internal/webui/api_chat_test.go | 46 +- internal/webui/api_version_test.go | 4 +- internal/webui/chat_test_helpers_test.go | 17 + internal/webui/server.go | 4 +- internal/webui/update_report_test.go | 4 +- proto/README.md | 26 + proto/buf.gen.yaml | 14 + proto/buf.yaml | 9 + proto/gateway/v1/chat.proto | 110 ++ tools/proto.sh | 39 + 35 files changed, 3534 insertions(+), 255 deletions(-) create mode 100644 internal/app/archied/chat_service.go create mode 100644 internal/app/archied/chat_service_test.go create mode 100644 internal/config/services.go create mode 100644 internal/contracts/gateway/v1/chat.pb.go create mode 100644 internal/contracts/gateway/v1/chat_grpc.pb.go create mode 100644 internal/gateway/chat_contract.go create mode 100644 internal/gateway/chat_local.go create mode 100644 internal/gateway/chat_local_test.go create mode 100644 internal/infrastructure/configuration/services_test.go create mode 100644 internal/infrastructure/gatewayrpc/client.go create mode 100644 internal/infrastructure/gatewayrpc/conformance_test.go create mode 100644 internal/infrastructure/gatewayrpc/server.go create mode 100644 internal/infrastructure/gatewayrpc/values.go create mode 100644 internal/webui/chat_test_helpers_test.go create mode 100644 proto/README.md create mode 100644 proto/buf.gen.yaml create mode 100644 proto/buf.yaml create mode 100644 proto/gateway/v1/chat.proto create mode 100644 tools/proto.sh diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 6e08611c6..42ec8d375 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -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 diff --git a/Taskfile.yml b/Taskfile.yml index da0472a3f..c66e7cef3 100644 --- a/Taskfile.yml +++ b/Taskfile.yml @@ -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 diff --git a/go.mod b/go.mod index c67de64bb..047f7352b 100644 --- a/go.mod +++ b/go.mod @@ -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 ) diff --git a/go.sum b/go.sum index 7a01a2ac2..fcf604c64 100644 --- a/go.sum +++ b/go.sum @@ -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= diff --git a/internal/app/archied/bootstrap.go b/internal/app/archied/bootstrap.go index 06fda3d89..547e5b334 100644 --- a/internal/app/archied/bootstrap.go +++ b/internal/app/archied/bootstrap.go @@ -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 } diff --git a/internal/app/archied/chat_service.go b/internal/app/archied/chat_service.go new file mode 100644 index 000000000..1c89d7aca --- /dev/null +++ b/internal/app/archied/chat_service.go @@ -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 +} diff --git a/internal/app/archied/chat_service_test.go b/internal/app/archied/chat_service_test.go new file mode 100644 index 000000000..28ff5be78 --- /dev/null +++ b/internal/app/archied/chat_service_test.go @@ -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 +} diff --git a/internal/app/archied/readiness.go b/internal/app/archied/readiness.go index 601383800..8def9b0b5 100644 --- a/internal/app/archied/readiness.go +++ b/internal/app/archied/readiness.go @@ -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: diff --git a/internal/app/archied/readiness_test.go b/internal/app/archied/readiness_test.go index 460823d12..f64eefa0e 100644 --- a/internal/app/archied/readiness_test.go +++ b/internal/app/archied/readiness_test.go @@ -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), diff --git a/internal/config/config.go b/internal/config/config.go index ea7320b5d..12287d019 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -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 diff --git a/internal/config/services.go b/internal/config/services.go new file mode 100644 index 000000000..3fda055ee --- /dev/null +++ b/internal/config/services.go @@ -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"` +} diff --git a/internal/contracts/gateway/v1/chat.pb.go b/internal/contracts/gateway/v1/chat.pb.go new file mode 100644 index 000000000..49032032d --- /dev/null +++ b/internal/contracts/gateway/v1/chat.pb.go @@ -0,0 +1,1755 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.36.11 +// protoc (unknown) +// source: gateway/v1/chat.proto + +package gatewayv1 + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + timestamppb "google.golang.org/protobuf/types/known/timestamppb" + reflect "reflect" + sync "sync" + unsafe "unsafe" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type Session struct { + state protoimpl.MessageState `protogen:"open.v1"` + SessionId string `protobuf:"bytes,1,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"` + Platform string `protobuf:"bytes,2,opt,name=platform,proto3" json:"platform,omitempty"` + BotUser string `protobuf:"bytes,3,opt,name=bot_user,json=botUser,proto3" json:"bot_user,omitempty"` + ChannelId string `protobuf:"bytes,4,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` + ThreadId string `protobuf:"bytes,5,opt,name=thread_id,json=threadId,proto3" json:"thread_id,omitempty"` + Title string `protobuf:"bytes,6,opt,name=title,proto3" json:"title,omitempty"` + ParentSessionId string `protobuf:"bytes,7,opt,name=parent_session_id,json=parentSessionId,proto3" json:"parent_session_id,omitempty"` + BranchName string `protobuf:"bytes,8,opt,name=branch_name,json=branchName,proto3" json:"branch_name,omitempty"` + CreatedAt *timestamppb.Timestamp `protobuf:"bytes,9,opt,name=created_at,json=createdAt,proto3" json:"created_at,omitempty"` + LastActiveAt *timestamppb.Timestamp `protobuf:"bytes,10,opt,name=last_active_at,json=lastActiveAt,proto3" json:"last_active_at,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Session) Reset() { + *x = Session{} + mi := &file_gateway_v1_chat_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Session) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Session) ProtoMessage() {} + +func (x *Session) ProtoReflect() protoreflect.Message { + mi := &file_gateway_v1_chat_proto_msgTypes[0] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Session.ProtoReflect.Descriptor instead. +func (*Session) Descriptor() ([]byte, []int) { + return file_gateway_v1_chat_proto_rawDescGZIP(), []int{0} +} + +func (x *Session) GetSessionId() string { + if x != nil { + return x.SessionId + } + return "" +} + +func (x *Session) GetPlatform() string { + if x != nil { + return x.Platform + } + return "" +} + +func (x *Session) GetBotUser() string { + if x != nil { + return x.BotUser + } + return "" +} + +func (x *Session) GetChannelId() string { + if x != nil { + return x.ChannelId + } + return "" +} + +func (x *Session) GetThreadId() string { + if x != nil { + return x.ThreadId + } + return "" +} + +func (x *Session) GetTitle() string { + if x != nil { + return x.Title + } + return "" +} + +func (x *Session) GetParentSessionId() string { + if x != nil { + return x.ParentSessionId + } + return "" +} + +func (x *Session) GetBranchName() string { + if x != nil { + return x.BranchName + } + return "" +} + +func (x *Session) GetCreatedAt() *timestamppb.Timestamp { + if x != nil { + return x.CreatedAt + } + return nil +} + +func (x *Session) GetLastActiveAt() *timestamppb.Timestamp { + if x != nil { + return x.LastActiveAt + } + return nil +} + +type Message struct { + state protoimpl.MessageState `protogen:"open.v1"` + MessageId string `protobuf:"bytes,1,opt,name=message_id,json=messageId,proto3" json:"message_id,omitempty"` + SourceId string `protobuf:"bytes,2,opt,name=source_id,json=sourceId,proto3" json:"source_id,omitempty"` + ChannelId string `protobuf:"bytes,3,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` + ThreadId string `protobuf:"bytes,4,opt,name=thread_id,json=threadId,proto3" json:"thread_id,omitempty"` + From string `protobuf:"bytes,5,opt,name=from,proto3" json:"from,omitempty"` + Text string `protobuf:"bytes,6,opt,name=text,proto3" json:"text,omitempty"` + Page string `protobuf:"bytes,7,opt,name=page,proto3" json:"page,omitempty"` + At *timestamppb.Timestamp `protobuf:"bytes,8,opt,name=at,proto3" json:"at,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Message) Reset() { + *x = Message{} + mi := &file_gateway_v1_chat_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Message) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Message) ProtoMessage() {} + +func (x *Message) ProtoReflect() protoreflect.Message { + mi := &file_gateway_v1_chat_proto_msgTypes[1] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Message.ProtoReflect.Descriptor instead. +func (*Message) Descriptor() ([]byte, []int) { + return file_gateway_v1_chat_proto_rawDescGZIP(), []int{1} +} + +func (x *Message) GetMessageId() string { + if x != nil { + return x.MessageId + } + return "" +} + +func (x *Message) GetSourceId() string { + if x != nil { + return x.SourceId + } + return "" +} + +func (x *Message) GetChannelId() string { + if x != nil { + return x.ChannelId + } + return "" +} + +func (x *Message) GetThreadId() string { + if x != nil { + return x.ThreadId + } + return "" +} + +func (x *Message) GetFrom() string { + if x != nil { + return x.From + } + return "" +} + +func (x *Message) GetText() string { + if x != nil { + return x.Text + } + return "" +} + +func (x *Message) GetPage() string { + if x != nil { + return x.Page + } + return "" +} + +func (x *Message) GetAt() *timestamppb.Timestamp { + if x != nil { + return x.At + } + return nil +} + +type ToolCall struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` + Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` + Parameters string `protobuf:"bytes,3,opt,name=parameters,proto3" json:"parameters,omitempty"` + Output string `protobuf:"bytes,4,opt,name=output,proto3" json:"output,omitempty"` + Error string `protobuf:"bytes,5,opt,name=error,proto3" json:"error,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ToolCall) Reset() { + *x = ToolCall{} + mi := &file_gateway_v1_chat_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ToolCall) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ToolCall) ProtoMessage() {} + +func (x *ToolCall) ProtoReflect() protoreflect.Message { + mi := &file_gateway_v1_chat_proto_msgTypes[2] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ToolCall.ProtoReflect.Descriptor instead. +func (*ToolCall) Descriptor() ([]byte, []int) { + return file_gateway_v1_chat_proto_rawDescGZIP(), []int{2} +} + +func (x *ToolCall) GetId() string { + if x != nil { + return x.Id + } + return "" +} + +func (x *ToolCall) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *ToolCall) GetParameters() string { + if x != nil { + return x.Parameters + } + return "" +} + +func (x *ToolCall) GetOutput() string { + if x != nil { + return x.Output + } + return "" +} + +func (x *ToolCall) GetError() string { + if x != nil { + return x.Error + } + return "" +} + +type Media struct { + state protoimpl.MessageState `protogen:"open.v1"` + ToolName string `protobuf:"bytes,1,opt,name=tool_name,json=toolName,proto3" json:"tool_name,omitempty"` + Type string `protobuf:"bytes,2,opt,name=type,proto3" json:"type,omitempty"` + FileId string `protobuf:"bytes,3,opt,name=file_id,json=fileId,proto3" json:"file_id,omitempty"` + Url string `protobuf:"bytes,4,opt,name=url,proto3" json:"url,omitempty"` + Path string `protobuf:"bytes,5,opt,name=path,proto3" json:"path,omitempty"` + MimeType string `protobuf:"bytes,6,opt,name=mime_type,json=mimeType,proto3" json:"mime_type,omitempty"` + FileName string `protobuf:"bytes,7,opt,name=file_name,json=fileName,proto3" json:"file_name,omitempty"` + FileSize *int64 `protobuf:"varint,8,opt,name=file_size,json=fileSize,proto3,oneof" json:"file_size,omitempty"` + Width *int64 `protobuf:"varint,9,opt,name=width,proto3,oneof" json:"width,omitempty"` + Height *int64 `protobuf:"varint,10,opt,name=height,proto3,oneof" json:"height,omitempty"` + Duration *int64 `protobuf:"varint,11,opt,name=duration,proto3,oneof" json:"duration,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Media) Reset() { + *x = Media{} + mi := &file_gateway_v1_chat_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Media) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Media) ProtoMessage() {} + +func (x *Media) ProtoReflect() protoreflect.Message { + mi := &file_gateway_v1_chat_proto_msgTypes[3] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Media.ProtoReflect.Descriptor instead. +func (*Media) Descriptor() ([]byte, []int) { + return file_gateway_v1_chat_proto_rawDescGZIP(), []int{3} +} + +func (x *Media) GetToolName() string { + if x != nil { + return x.ToolName + } + return "" +} + +func (x *Media) GetType() string { + if x != nil { + return x.Type + } + return "" +} + +func (x *Media) GetFileId() string { + if x != nil { + return x.FileId + } + return "" +} + +func (x *Media) GetUrl() string { + if x != nil { + return x.Url + } + return "" +} + +func (x *Media) GetPath() string { + if x != nil { + return x.Path + } + return "" +} + +func (x *Media) GetMimeType() string { + if x != nil { + return x.MimeType + } + return "" +} + +func (x *Media) GetFileName() string { + if x != nil { + return x.FileName + } + return "" +} + +func (x *Media) GetFileSize() int64 { + if x != nil && x.FileSize != nil { + return *x.FileSize + } + return 0 +} + +func (x *Media) GetWidth() int64 { + if x != nil && x.Width != nil { + return *x.Width + } + return 0 +} + +func (x *Media) GetHeight() int64 { + if x != nil && x.Height != nil { + return *x.Height + } + return 0 +} + +func (x *Media) GetDuration() int64 { + if x != nil && x.Duration != nil { + return *x.Duration + } + return 0 +} + +type Turn struct { + state protoimpl.MessageState `protogen:"open.v1"` + TurnId string `protobuf:"bytes,1,opt,name=turn_id,json=turnId,proto3" json:"turn_id,omitempty"` + SessionId string `protobuf:"bytes,2,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"` + SourceId string `protobuf:"bytes,3,opt,name=source_id,json=sourceId,proto3" json:"source_id,omitempty"` + Status string `protobuf:"bytes,4,opt,name=status,proto3" json:"status,omitempty"` + Attempt int64 `protobuf:"varint,5,opt,name=attempt,proto3" json:"attempt,omitempty"` + OwnerId string `protobuf:"bytes,6,opt,name=owner_id,json=ownerId,proto3" json:"owner_id,omitempty"` + InputMessageId string `protobuf:"bytes,7,opt,name=input_message_id,json=inputMessageId,proto3" json:"input_message_id,omitempty"` + AssistantMessageId string `protobuf:"bytes,8,opt,name=assistant_message_id,json=assistantMessageId,proto3" json:"assistant_message_id,omitempty"` + PartialText string `protobuf:"bytes,9,opt,name=partial_text,json=partialText,proto3" json:"partial_text,omitempty"` + ResponseText string `protobuf:"bytes,10,opt,name=response_text,json=responseText,proto3" json:"response_text,omitempty"` + ToolCalls []*ToolCall `protobuf:"bytes,11,rep,name=tool_calls,json=toolCalls,proto3" json:"tool_calls,omitempty"` + Error string `protobuf:"bytes,12,opt,name=error,proto3" json:"error,omitempty"` + CreatedAt *timestamppb.Timestamp `protobuf:"bytes,13,opt,name=created_at,json=createdAt,proto3" json:"created_at,omitempty"` + UpdatedAt *timestamppb.Timestamp `protobuf:"bytes,14,opt,name=updated_at,json=updatedAt,proto3" json:"updated_at,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Turn) Reset() { + *x = Turn{} + mi := &file_gateway_v1_chat_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Turn) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Turn) ProtoMessage() {} + +func (x *Turn) ProtoReflect() protoreflect.Message { + mi := &file_gateway_v1_chat_proto_msgTypes[4] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Turn.ProtoReflect.Descriptor instead. +func (*Turn) Descriptor() ([]byte, []int) { + return file_gateway_v1_chat_proto_rawDescGZIP(), []int{4} +} + +func (x *Turn) GetTurnId() string { + if x != nil { + return x.TurnId + } + return "" +} + +func (x *Turn) GetSessionId() string { + if x != nil { + return x.SessionId + } + return "" +} + +func (x *Turn) GetSourceId() string { + if x != nil { + return x.SourceId + } + return "" +} + +func (x *Turn) GetStatus() string { + if x != nil { + return x.Status + } + return "" +} + +func (x *Turn) GetAttempt() int64 { + if x != nil { + return x.Attempt + } + return 0 +} + +func (x *Turn) GetOwnerId() string { + if x != nil { + return x.OwnerId + } + return "" +} + +func (x *Turn) GetInputMessageId() string { + if x != nil { + return x.InputMessageId + } + return "" +} + +func (x *Turn) GetAssistantMessageId() string { + if x != nil { + return x.AssistantMessageId + } + return "" +} + +func (x *Turn) GetPartialText() string { + if x != nil { + return x.PartialText + } + return "" +} + +func (x *Turn) GetResponseText() string { + if x != nil { + return x.ResponseText + } + return "" +} + +func (x *Turn) GetToolCalls() []*ToolCall { + if x != nil { + return x.ToolCalls + } + return nil +} + +func (x *Turn) GetError() string { + if x != nil { + return x.Error + } + return "" +} + +func (x *Turn) GetCreatedAt() *timestamppb.Timestamp { + if x != nil { + return x.CreatedAt + } + return nil +} + +func (x *Turn) GetUpdatedAt() *timestamppb.Timestamp { + if x != nil { + return x.UpdatedAt + } + return nil +} + +type StringList struct { + state protoimpl.MessageState `protogen:"open.v1"` + Values []string `protobuf:"bytes,1,rep,name=values,proto3" json:"values,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *StringList) Reset() { + *x = StringList{} + mi := &file_gateway_v1_chat_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *StringList) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*StringList) ProtoMessage() {} + +func (x *StringList) ProtoReflect() protoreflect.Message { + mi := &file_gateway_v1_chat_proto_msgTypes[5] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use StringList.ProtoReflect.Descriptor instead. +func (*StringList) Descriptor() ([]byte, []int) { + return file_gateway_v1_chat_proto_rawDescGZIP(), []int{5} +} + +func (x *StringList) GetValues() []string { + if x != nil { + return x.Values + } + return nil +} + +type SnapshotRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SnapshotRequest) Reset() { + *x = SnapshotRequest{} + mi := &file_gateway_v1_chat_proto_msgTypes[6] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SnapshotRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SnapshotRequest) ProtoMessage() {} + +func (x *SnapshotRequest) ProtoReflect() protoreflect.Message { + mi := &file_gateway_v1_chat_proto_msgTypes[6] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SnapshotRequest.ProtoReflect.Descriptor instead. +func (*SnapshotRequest) Descriptor() ([]byte, []int) { + return file_gateway_v1_chat_proto_rawDescGZIP(), []int{6} +} + +type SnapshotResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Sessions []*Session `protobuf:"bytes,1,rep,name=sessions,proto3" json:"sessions,omitempty"` + Models []string `protobuf:"bytes,2,rep,name=models,proto3" json:"models,omitempty"` + ModelsByProvider map[string]*StringList `protobuf:"bytes,3,rep,name=models_by_provider,json=modelsByProvider,proto3" json:"models_by_provider,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + Providers []string `protobuf:"bytes,4,rep,name=providers,proto3" json:"providers,omitempty"` + ActiveModel string `protobuf:"bytes,5,opt,name=active_model,json=activeModel,proto3" json:"active_model,omitempty"` + ActiveProvider string `protobuf:"bytes,6,opt,name=active_provider,json=activeProvider,proto3" json:"active_provider,omitempty"` + Personas []string `protobuf:"bytes,7,rep,name=personas,proto3" json:"personas,omitempty"` + ActivePersonas map[string]string `protobuf:"bytes,8,rep,name=active_personas,json=activePersonas,proto3" json:"active_personas,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + RestartAvailable bool `protobuf:"varint,9,opt,name=restart_available,json=restartAvailable,proto3" json:"restart_available,omitempty"` + CancellationAvailable bool `protobuf:"varint,10,opt,name=cancellation_available,json=cancellationAvailable,proto3" json:"cancellation_available,omitempty"` + PersonasAvailable bool `protobuf:"varint,11,opt,name=personas_available,json=personasAvailable,proto3" json:"personas_available,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SnapshotResponse) Reset() { + *x = SnapshotResponse{} + mi := &file_gateway_v1_chat_proto_msgTypes[7] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SnapshotResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SnapshotResponse) ProtoMessage() {} + +func (x *SnapshotResponse) ProtoReflect() protoreflect.Message { + mi := &file_gateway_v1_chat_proto_msgTypes[7] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SnapshotResponse.ProtoReflect.Descriptor instead. +func (*SnapshotResponse) Descriptor() ([]byte, []int) { + return file_gateway_v1_chat_proto_rawDescGZIP(), []int{7} +} + +func (x *SnapshotResponse) GetSessions() []*Session { + if x != nil { + return x.Sessions + } + return nil +} + +func (x *SnapshotResponse) GetModels() []string { + if x != nil { + return x.Models + } + return nil +} + +func (x *SnapshotResponse) GetModelsByProvider() map[string]*StringList { + if x != nil { + return x.ModelsByProvider + } + return nil +} + +func (x *SnapshotResponse) GetProviders() []string { + if x != nil { + return x.Providers + } + return nil +} + +func (x *SnapshotResponse) GetActiveModel() string { + if x != nil { + return x.ActiveModel + } + return "" +} + +func (x *SnapshotResponse) GetActiveProvider() string { + if x != nil { + return x.ActiveProvider + } + return "" +} + +func (x *SnapshotResponse) GetPersonas() []string { + if x != nil { + return x.Personas + } + return nil +} + +func (x *SnapshotResponse) GetActivePersonas() map[string]string { + if x != nil { + return x.ActivePersonas + } + return nil +} + +func (x *SnapshotResponse) GetRestartAvailable() bool { + if x != nil { + return x.RestartAvailable + } + return false +} + +func (x *SnapshotResponse) GetCancellationAvailable() bool { + if x != nil { + return x.CancellationAvailable + } + return false +} + +func (x *SnapshotResponse) GetPersonasAvailable() bool { + if x != nil { + return x.PersonasAvailable + } + return false +} + +type GetSessionRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + SessionId string `protobuf:"bytes,1,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetSessionRequest) Reset() { + *x = GetSessionRequest{} + mi := &file_gateway_v1_chat_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetSessionRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetSessionRequest) ProtoMessage() {} + +func (x *GetSessionRequest) ProtoReflect() protoreflect.Message { + mi := &file_gateway_v1_chat_proto_msgTypes[8] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetSessionRequest.ProtoReflect.Descriptor instead. +func (*GetSessionRequest) Descriptor() ([]byte, []int) { + return file_gateway_v1_chat_proto_rawDescGZIP(), []int{8} +} + +func (x *GetSessionRequest) GetSessionId() string { + if x != nil { + return x.SessionId + } + return "" +} + +type GetSessionResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Session *Session `protobuf:"bytes,1,opt,name=session,proto3" json:"session,omitempty"` + Found bool `protobuf:"varint,2,opt,name=found,proto3" json:"found,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetSessionResponse) Reset() { + *x = GetSessionResponse{} + mi := &file_gateway_v1_chat_proto_msgTypes[9] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetSessionResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetSessionResponse) ProtoMessage() {} + +func (x *GetSessionResponse) ProtoReflect() protoreflect.Message { + mi := &file_gateway_v1_chat_proto_msgTypes[9] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetSessionResponse.ProtoReflect.Descriptor instead. +func (*GetSessionResponse) Descriptor() ([]byte, []int) { + return file_gateway_v1_chat_proto_rawDescGZIP(), []int{9} +} + +func (x *GetSessionResponse) GetSession() *Session { + if x != nil { + return x.Session + } + return nil +} + +func (x *GetSessionResponse) GetFound() bool { + if x != nil { + return x.Found + } + return false +} + +type RecentMessagesRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + SessionId string `protobuf:"bytes,1,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"` + Limit int64 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *RecentMessagesRequest) Reset() { + *x = RecentMessagesRequest{} + mi := &file_gateway_v1_chat_proto_msgTypes[10] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *RecentMessagesRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RecentMessagesRequest) ProtoMessage() {} + +func (x *RecentMessagesRequest) ProtoReflect() protoreflect.Message { + mi := &file_gateway_v1_chat_proto_msgTypes[10] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use RecentMessagesRequest.ProtoReflect.Descriptor instead. +func (*RecentMessagesRequest) Descriptor() ([]byte, []int) { + return file_gateway_v1_chat_proto_rawDescGZIP(), []int{10} +} + +func (x *RecentMessagesRequest) GetSessionId() string { + if x != nil { + return x.SessionId + } + return "" +} + +func (x *RecentMessagesRequest) GetLimit() int64 { + if x != nil { + return x.Limit + } + return 0 +} + +type RecentMessagesResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Messages []*Message `protobuf:"bytes,1,rep,name=messages,proto3" json:"messages,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *RecentMessagesResponse) Reset() { + *x = RecentMessagesResponse{} + mi := &file_gateway_v1_chat_proto_msgTypes[11] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *RecentMessagesResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RecentMessagesResponse) ProtoMessage() {} + +func (x *RecentMessagesResponse) ProtoReflect() protoreflect.Message { + mi := &file_gateway_v1_chat_proto_msgTypes[11] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use RecentMessagesResponse.ProtoReflect.Descriptor instead. +func (*RecentMessagesResponse) Descriptor() ([]byte, []int) { + return file_gateway_v1_chat_proto_rawDescGZIP(), []int{11} +} + +func (x *RecentMessagesResponse) GetMessages() []*Message { + if x != nil { + return x.Messages + } + return nil +} + +type RecentTurnsRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + SessionId string `protobuf:"bytes,1,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"` + Limit int64 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *RecentTurnsRequest) Reset() { + *x = RecentTurnsRequest{} + mi := &file_gateway_v1_chat_proto_msgTypes[12] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *RecentTurnsRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RecentTurnsRequest) ProtoMessage() {} + +func (x *RecentTurnsRequest) ProtoReflect() protoreflect.Message { + mi := &file_gateway_v1_chat_proto_msgTypes[12] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use RecentTurnsRequest.ProtoReflect.Descriptor instead. +func (*RecentTurnsRequest) Descriptor() ([]byte, []int) { + return file_gateway_v1_chat_proto_rawDescGZIP(), []int{12} +} + +func (x *RecentTurnsRequest) GetSessionId() string { + if x != nil { + return x.SessionId + } + return "" +} + +func (x *RecentTurnsRequest) GetLimit() int64 { + if x != nil { + return x.Limit + } + return 0 +} + +type RecentTurnsResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Turns []*Turn `protobuf:"bytes,1,rep,name=turns,proto3" json:"turns,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *RecentTurnsResponse) Reset() { + *x = RecentTurnsResponse{} + mi := &file_gateway_v1_chat_proto_msgTypes[13] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *RecentTurnsResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RecentTurnsResponse) ProtoMessage() {} + +func (x *RecentTurnsResponse) ProtoReflect() protoreflect.Message { + mi := &file_gateway_v1_chat_proto_msgTypes[13] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use RecentTurnsResponse.ProtoReflect.Descriptor instead. +func (*RecentTurnsResponse) Descriptor() ([]byte, []int) { + return file_gateway_v1_chat_proto_rawDescGZIP(), []int{13} +} + +func (x *RecentTurnsResponse) GetTurns() []*Turn { + if x != nil { + return x.Turns + } + return nil +} + +type RouteRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Message *Message `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *RouteRequest) Reset() { + *x = RouteRequest{} + mi := &file_gateway_v1_chat_proto_msgTypes[14] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *RouteRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RouteRequest) ProtoMessage() {} + +func (x *RouteRequest) ProtoReflect() protoreflect.Message { + mi := &file_gateway_v1_chat_proto_msgTypes[14] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use RouteRequest.ProtoReflect.Descriptor instead. +func (*RouteRequest) Descriptor() ([]byte, []int) { + return file_gateway_v1_chat_proto_rawDescGZIP(), []int{14} +} + +func (x *RouteRequest) GetMessage() *Message { + if x != nil { + return x.Message + } + return nil +} + +type RouteResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Text string `protobuf:"bytes,1,opt,name=text,proto3" json:"text,omitempty"` + SessionId string `protobuf:"bytes,2,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *RouteResponse) Reset() { + *x = RouteResponse{} + mi := &file_gateway_v1_chat_proto_msgTypes[15] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *RouteResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RouteResponse) ProtoMessage() {} + +func (x *RouteResponse) ProtoReflect() protoreflect.Message { + mi := &file_gateway_v1_chat_proto_msgTypes[15] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use RouteResponse.ProtoReflect.Descriptor instead. +func (*RouteResponse) Descriptor() ([]byte, []int) { + return file_gateway_v1_chat_proto_rawDescGZIP(), []int{15} +} + +func (x *RouteResponse) GetText() string { + if x != nil { + return x.Text + } + return "" +} + +func (x *RouteResponse) GetSessionId() string { + if x != nil { + return x.SessionId + } + return "" +} + +type StreamRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Message *Message `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *StreamRequest) Reset() { + *x = StreamRequest{} + mi := &file_gateway_v1_chat_proto_msgTypes[16] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *StreamRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*StreamRequest) ProtoMessage() {} + +func (x *StreamRequest) ProtoReflect() protoreflect.Message { + mi := &file_gateway_v1_chat_proto_msgTypes[16] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use StreamRequest.ProtoReflect.Descriptor instead. +func (*StreamRequest) Descriptor() ([]byte, []int) { + return file_gateway_v1_chat_proto_rawDescGZIP(), []int{16} +} + +func (x *StreamRequest) GetMessage() *Message { + if x != nil { + return x.Message + } + return nil +} + +type StreamResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Kind string `protobuf:"bytes,1,opt,name=kind,proto3" json:"kind,omitempty"` + Text string `protobuf:"bytes,2,opt,name=text,proto3" json:"text,omitempty"` + SessionId string `protobuf:"bytes,3,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"` + Tool *ToolCall `protobuf:"bytes,4,opt,name=tool,proto3" json:"tool,omitempty"` + Media *Media `protobuf:"bytes,5,opt,name=media,proto3" json:"media,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *StreamResponse) Reset() { + *x = StreamResponse{} + mi := &file_gateway_v1_chat_proto_msgTypes[17] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *StreamResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*StreamResponse) ProtoMessage() {} + +func (x *StreamResponse) ProtoReflect() protoreflect.Message { + mi := &file_gateway_v1_chat_proto_msgTypes[17] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use StreamResponse.ProtoReflect.Descriptor instead. +func (*StreamResponse) Descriptor() ([]byte, []int) { + return file_gateway_v1_chat_proto_rawDescGZIP(), []int{17} +} + +func (x *StreamResponse) GetKind() string { + if x != nil { + return x.Kind + } + return "" +} + +func (x *StreamResponse) GetText() string { + if x != nil { + return x.Text + } + return "" +} + +func (x *StreamResponse) GetSessionId() string { + if x != nil { + return x.SessionId + } + return "" +} + +func (x *StreamResponse) GetTool() *ToolCall { + if x != nil { + return x.Tool + } + return nil +} + +func (x *StreamResponse) GetMedia() *Media { + if x != nil { + return x.Media + } + return nil +} + +type CancelRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + SessionId string `protobuf:"bytes,1,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *CancelRequest) Reset() { + *x = CancelRequest{} + mi := &file_gateway_v1_chat_proto_msgTypes[18] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *CancelRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CancelRequest) ProtoMessage() {} + +func (x *CancelRequest) ProtoReflect() protoreflect.Message { + mi := &file_gateway_v1_chat_proto_msgTypes[18] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CancelRequest.ProtoReflect.Descriptor instead. +func (*CancelRequest) Descriptor() ([]byte, []int) { + return file_gateway_v1_chat_proto_rawDescGZIP(), []int{18} +} + +func (x *CancelRequest) GetSessionId() string { + if x != nil { + return x.SessionId + } + return "" +} + +type CancelResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Cancelled bool `protobuf:"varint,1,opt,name=cancelled,proto3" json:"cancelled,omitempty"` + Dropped int64 `protobuf:"varint,2,opt,name=dropped,proto3" json:"dropped,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *CancelResponse) Reset() { + *x = CancelResponse{} + mi := &file_gateway_v1_chat_proto_msgTypes[19] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *CancelResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CancelResponse) ProtoMessage() {} + +func (x *CancelResponse) ProtoReflect() protoreflect.Message { + mi := &file_gateway_v1_chat_proto_msgTypes[19] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CancelResponse.ProtoReflect.Descriptor instead. +func (*CancelResponse) Descriptor() ([]byte, []int) { + return file_gateway_v1_chat_proto_rawDescGZIP(), []int{19} +} + +func (x *CancelResponse) GetCancelled() bool { + if x != nil { + return x.Cancelled + } + return false +} + +func (x *CancelResponse) GetDropped() int64 { + if x != nil { + return x.Dropped + } + return 0 +} + +type SetPersonaRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + SessionId string `protobuf:"bytes,1,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"` + Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SetPersonaRequest) Reset() { + *x = SetPersonaRequest{} + mi := &file_gateway_v1_chat_proto_msgTypes[20] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SetPersonaRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SetPersonaRequest) ProtoMessage() {} + +func (x *SetPersonaRequest) ProtoReflect() protoreflect.Message { + mi := &file_gateway_v1_chat_proto_msgTypes[20] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SetPersonaRequest.ProtoReflect.Descriptor instead. +func (*SetPersonaRequest) Descriptor() ([]byte, []int) { + return file_gateway_v1_chat_proto_rawDescGZIP(), []int{20} +} + +func (x *SetPersonaRequest) GetSessionId() string { + if x != nil { + return x.SessionId + } + return "" +} + +func (x *SetPersonaRequest) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +type SetPersonaResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Found bool `protobuf:"varint,1,opt,name=found,proto3" json:"found,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SetPersonaResponse) Reset() { + *x = SetPersonaResponse{} + mi := &file_gateway_v1_chat_proto_msgTypes[21] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SetPersonaResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SetPersonaResponse) ProtoMessage() {} + +func (x *SetPersonaResponse) ProtoReflect() protoreflect.Message { + mi := &file_gateway_v1_chat_proto_msgTypes[21] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SetPersonaResponse.ProtoReflect.Descriptor instead. +func (*SetPersonaResponse) Descriptor() ([]byte, []int) { + return file_gateway_v1_chat_proto_rawDescGZIP(), []int{21} +} + +func (x *SetPersonaResponse) GetFound() bool { + if x != nil { + return x.Found + } + return false +} + +var File_gateway_v1_chat_proto protoreflect.FileDescriptor + +const file_gateway_v1_chat_proto_rawDesc = "" + + "\n" + + "\x15gateway/v1/chat.proto\x12\n" + + "gateway.v1\x1a\x1fgoogle/protobuf/timestamp.proto\"\xfb\x02\n" + + "\aSession\x12\x1d\n" + + "\n" + + "session_id\x18\x01 \x01(\tR\tsessionId\x12\x1a\n" + + "\bplatform\x18\x02 \x01(\tR\bplatform\x12\x19\n" + + "\bbot_user\x18\x03 \x01(\tR\abotUser\x12\x1d\n" + + "\n" + + "channel_id\x18\x04 \x01(\tR\tchannelId\x12\x1b\n" + + "\tthread_id\x18\x05 \x01(\tR\bthreadId\x12\x14\n" + + "\x05title\x18\x06 \x01(\tR\x05title\x12*\n" + + "\x11parent_session_id\x18\a \x01(\tR\x0fparentSessionId\x12\x1f\n" + + "\vbranch_name\x18\b \x01(\tR\n" + + "branchName\x129\n" + + "\n" + + "created_at\x18\t \x01(\v2\x1a.google.protobuf.TimestampR\tcreatedAt\x12@\n" + + "\x0elast_active_at\x18\n" + + " \x01(\v2\x1a.google.protobuf.TimestampR\flastActiveAt\"\xe9\x01\n" + + "\aMessage\x12\x1d\n" + + "\n" + + "message_id\x18\x01 \x01(\tR\tmessageId\x12\x1b\n" + + "\tsource_id\x18\x02 \x01(\tR\bsourceId\x12\x1d\n" + + "\n" + + "channel_id\x18\x03 \x01(\tR\tchannelId\x12\x1b\n" + + "\tthread_id\x18\x04 \x01(\tR\bthreadId\x12\x12\n" + + "\x04from\x18\x05 \x01(\tR\x04from\x12\x12\n" + + "\x04text\x18\x06 \x01(\tR\x04text\x12\x12\n" + + "\x04page\x18\a \x01(\tR\x04page\x12*\n" + + "\x02at\x18\b \x01(\v2\x1a.google.protobuf.TimestampR\x02at\"|\n" + + "\bToolCall\x12\x0e\n" + + "\x02id\x18\x01 \x01(\tR\x02id\x12\x12\n" + + "\x04name\x18\x02 \x01(\tR\x04name\x12\x1e\n" + + "\n" + + "parameters\x18\x03 \x01(\tR\n" + + "parameters\x12\x16\n" + + "\x06output\x18\x04 \x01(\tR\x06output\x12\x14\n" + + "\x05error\x18\x05 \x01(\tR\x05error\"\xdc\x02\n" + + "\x05Media\x12\x1b\n" + + "\ttool_name\x18\x01 \x01(\tR\btoolName\x12\x12\n" + + "\x04type\x18\x02 \x01(\tR\x04type\x12\x17\n" + + "\afile_id\x18\x03 \x01(\tR\x06fileId\x12\x10\n" + + "\x03url\x18\x04 \x01(\tR\x03url\x12\x12\n" + + "\x04path\x18\x05 \x01(\tR\x04path\x12\x1b\n" + + "\tmime_type\x18\x06 \x01(\tR\bmimeType\x12\x1b\n" + + "\tfile_name\x18\a \x01(\tR\bfileName\x12 \n" + + "\tfile_size\x18\b \x01(\x03H\x00R\bfileSize\x88\x01\x01\x12\x19\n" + + "\x05width\x18\t \x01(\x03H\x01R\x05width\x88\x01\x01\x12\x1b\n" + + "\x06height\x18\n" + + " \x01(\x03H\x02R\x06height\x88\x01\x01\x12\x1f\n" + + "\bduration\x18\v \x01(\x03H\x03R\bduration\x88\x01\x01B\f\n" + + "\n" + + "_file_sizeB\b\n" + + "\x06_widthB\t\n" + + "\a_heightB\v\n" + + "\t_duration\"\x8d\x04\n" + + "\x04Turn\x12\x17\n" + + "\aturn_id\x18\x01 \x01(\tR\x06turnId\x12\x1d\n" + + "\n" + + "session_id\x18\x02 \x01(\tR\tsessionId\x12\x1b\n" + + "\tsource_id\x18\x03 \x01(\tR\bsourceId\x12\x16\n" + + "\x06status\x18\x04 \x01(\tR\x06status\x12\x18\n" + + "\aattempt\x18\x05 \x01(\x03R\aattempt\x12\x19\n" + + "\bowner_id\x18\x06 \x01(\tR\aownerId\x12(\n" + + "\x10input_message_id\x18\a \x01(\tR\x0einputMessageId\x120\n" + + "\x14assistant_message_id\x18\b \x01(\tR\x12assistantMessageId\x12!\n" + + "\fpartial_text\x18\t \x01(\tR\vpartialText\x12#\n" + + "\rresponse_text\x18\n" + + " \x01(\tR\fresponseText\x123\n" + + "\n" + + "tool_calls\x18\v \x03(\v2\x14.gateway.v1.ToolCallR\ttoolCalls\x12\x14\n" + + "\x05error\x18\f \x01(\tR\x05error\x129\n" + + "\n" + + "created_at\x18\r \x01(\v2\x1a.google.protobuf.TimestampR\tcreatedAt\x129\n" + + "\n" + + "updated_at\x18\x0e \x01(\v2\x1a.google.protobuf.TimestampR\tupdatedAt\"$\n" + + "\n" + + "StringList\x12\x16\n" + + "\x06values\x18\x01 \x03(\tR\x06values\"\x11\n" + + "\x0fSnapshotRequest\"\xd1\x05\n" + + "\x10SnapshotResponse\x12/\n" + + "\bsessions\x18\x01 \x03(\v2\x13.gateway.v1.SessionR\bsessions\x12\x16\n" + + "\x06models\x18\x02 \x03(\tR\x06models\x12`\n" + + "\x12models_by_provider\x18\x03 \x03(\v22.gateway.v1.SnapshotResponse.ModelsByProviderEntryR\x10modelsByProvider\x12\x1c\n" + + "\tproviders\x18\x04 \x03(\tR\tproviders\x12!\n" + + "\factive_model\x18\x05 \x01(\tR\vactiveModel\x12'\n" + + "\x0factive_provider\x18\x06 \x01(\tR\x0eactiveProvider\x12\x1a\n" + + "\bpersonas\x18\a \x03(\tR\bpersonas\x12Y\n" + + "\x0factive_personas\x18\b \x03(\v20.gateway.v1.SnapshotResponse.ActivePersonasEntryR\x0eactivePersonas\x12+\n" + + "\x11restart_available\x18\t \x01(\bR\x10restartAvailable\x125\n" + + "\x16cancellation_available\x18\n" + + " \x01(\bR\x15cancellationAvailable\x12-\n" + + "\x12personas_available\x18\v \x01(\bR\x11personasAvailable\x1a[\n" + + "\x15ModelsByProviderEntry\x12\x10\n" + + "\x03key\x18\x01 \x01(\tR\x03key\x12,\n" + + "\x05value\x18\x02 \x01(\v2\x16.gateway.v1.StringListR\x05value:\x028\x01\x1aA\n" + + "\x13ActivePersonasEntry\x12\x10\n" + + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"2\n" + + "\x11GetSessionRequest\x12\x1d\n" + + "\n" + + "session_id\x18\x01 \x01(\tR\tsessionId\"Y\n" + + "\x12GetSessionResponse\x12-\n" + + "\asession\x18\x01 \x01(\v2\x13.gateway.v1.SessionR\asession\x12\x14\n" + + "\x05found\x18\x02 \x01(\bR\x05found\"L\n" + + "\x15RecentMessagesRequest\x12\x1d\n" + + "\n" + + "session_id\x18\x01 \x01(\tR\tsessionId\x12\x14\n" + + "\x05limit\x18\x02 \x01(\x03R\x05limit\"I\n" + + "\x16RecentMessagesResponse\x12/\n" + + "\bmessages\x18\x01 \x03(\v2\x13.gateway.v1.MessageR\bmessages\"I\n" + + "\x12RecentTurnsRequest\x12\x1d\n" + + "\n" + + "session_id\x18\x01 \x01(\tR\tsessionId\x12\x14\n" + + "\x05limit\x18\x02 \x01(\x03R\x05limit\"=\n" + + "\x13RecentTurnsResponse\x12&\n" + + "\x05turns\x18\x01 \x03(\v2\x10.gateway.v1.TurnR\x05turns\"=\n" + + "\fRouteRequest\x12-\n" + + "\amessage\x18\x01 \x01(\v2\x13.gateway.v1.MessageR\amessage\"B\n" + + "\rRouteResponse\x12\x12\n" + + "\x04text\x18\x01 \x01(\tR\x04text\x12\x1d\n" + + "\n" + + "session_id\x18\x02 \x01(\tR\tsessionId\">\n" + + "\rStreamRequest\x12-\n" + + "\amessage\x18\x01 \x01(\v2\x13.gateway.v1.MessageR\amessage\"\xaa\x01\n" + + "\x0eStreamResponse\x12\x12\n" + + "\x04kind\x18\x01 \x01(\tR\x04kind\x12\x12\n" + + "\x04text\x18\x02 \x01(\tR\x04text\x12\x1d\n" + + "\n" + + "session_id\x18\x03 \x01(\tR\tsessionId\x12(\n" + + "\x04tool\x18\x04 \x01(\v2\x14.gateway.v1.ToolCallR\x04tool\x12'\n" + + "\x05media\x18\x05 \x01(\v2\x11.gateway.v1.MediaR\x05media\".\n" + + "\rCancelRequest\x12\x1d\n" + + "\n" + + "session_id\x18\x01 \x01(\tR\tsessionId\"H\n" + + "\x0eCancelResponse\x12\x1c\n" + + "\tcancelled\x18\x01 \x01(\bR\tcancelled\x12\x18\n" + + "\adropped\x18\x02 \x01(\x03R\adropped\"F\n" + + "\x11SetPersonaRequest\x12\x1d\n" + + "\n" + + "session_id\x18\x01 \x01(\tR\tsessionId\x12\x12\n" + + "\x04name\x18\x02 \x01(\tR\x04name\"*\n" + + "\x12SetPersonaResponse\x12\x14\n" + + "\x05found\x18\x01 \x01(\bR\x05found2\xd9\x04\n" + + "\vChatService\x12E\n" + + "\bSnapshot\x12\x1b.gateway.v1.SnapshotRequest\x1a\x1c.gateway.v1.SnapshotResponse\x12K\n" + + "\n" + + "GetSession\x12\x1d.gateway.v1.GetSessionRequest\x1a\x1e.gateway.v1.GetSessionResponse\x12W\n" + + "\x0eRecentMessages\x12!.gateway.v1.RecentMessagesRequest\x1a\".gateway.v1.RecentMessagesResponse\x12N\n" + + "\vRecentTurns\x12\x1e.gateway.v1.RecentTurnsRequest\x1a\x1f.gateway.v1.RecentTurnsResponse\x12<\n" + + "\x05Route\x12\x18.gateway.v1.RouteRequest\x1a\x19.gateway.v1.RouteResponse\x12A\n" + + "\x06Stream\x12\x19.gateway.v1.StreamRequest\x1a\x1a.gateway.v1.StreamResponse0\x01\x12?\n" + + "\x06Cancel\x12\x19.gateway.v1.CancelRequest\x1a\x1a.gateway.v1.CancelResponse\x12K\n" + + "\n" + + "SetPersona\x12\x1d.gateway.v1.SetPersonaRequest\x1a\x1e.gateway.v1.SetPersonaResponseB\xb1\x01\n" + + "\x0ecom.gateway.v1B\tChatProtoP\x01ZKgithub.com/samcharles93/archie-core/internal/contracts/gateway/v1;gatewayv1\xa2\x02\x03GXX\xaa\x02\n" + + "Gateway.V1\xca\x02\n" + + "Gateway\\V1\xe2\x02\x16Gateway\\V1\\GPBMetadata\xea\x02\vGateway::V1b\x06proto3" + +var ( + file_gateway_v1_chat_proto_rawDescOnce sync.Once + file_gateway_v1_chat_proto_rawDescData []byte +) + +func file_gateway_v1_chat_proto_rawDescGZIP() []byte { + file_gateway_v1_chat_proto_rawDescOnce.Do(func() { + file_gateway_v1_chat_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_gateway_v1_chat_proto_rawDesc), len(file_gateway_v1_chat_proto_rawDesc))) + }) + return file_gateway_v1_chat_proto_rawDescData +} + +var file_gateway_v1_chat_proto_msgTypes = make([]protoimpl.MessageInfo, 24) +var file_gateway_v1_chat_proto_goTypes = []any{ + (*Session)(nil), // 0: gateway.v1.Session + (*Message)(nil), // 1: gateway.v1.Message + (*ToolCall)(nil), // 2: gateway.v1.ToolCall + (*Media)(nil), // 3: gateway.v1.Media + (*Turn)(nil), // 4: gateway.v1.Turn + (*StringList)(nil), // 5: gateway.v1.StringList + (*SnapshotRequest)(nil), // 6: gateway.v1.SnapshotRequest + (*SnapshotResponse)(nil), // 7: gateway.v1.SnapshotResponse + (*GetSessionRequest)(nil), // 8: gateway.v1.GetSessionRequest + (*GetSessionResponse)(nil), // 9: gateway.v1.GetSessionResponse + (*RecentMessagesRequest)(nil), // 10: gateway.v1.RecentMessagesRequest + (*RecentMessagesResponse)(nil), // 11: gateway.v1.RecentMessagesResponse + (*RecentTurnsRequest)(nil), // 12: gateway.v1.RecentTurnsRequest + (*RecentTurnsResponse)(nil), // 13: gateway.v1.RecentTurnsResponse + (*RouteRequest)(nil), // 14: gateway.v1.RouteRequest + (*RouteResponse)(nil), // 15: gateway.v1.RouteResponse + (*StreamRequest)(nil), // 16: gateway.v1.StreamRequest + (*StreamResponse)(nil), // 17: gateway.v1.StreamResponse + (*CancelRequest)(nil), // 18: gateway.v1.CancelRequest + (*CancelResponse)(nil), // 19: gateway.v1.CancelResponse + (*SetPersonaRequest)(nil), // 20: gateway.v1.SetPersonaRequest + (*SetPersonaResponse)(nil), // 21: gateway.v1.SetPersonaResponse + nil, // 22: gateway.v1.SnapshotResponse.ModelsByProviderEntry + nil, // 23: gateway.v1.SnapshotResponse.ActivePersonasEntry + (*timestamppb.Timestamp)(nil), // 24: google.protobuf.Timestamp +} +var file_gateway_v1_chat_proto_depIdxs = []int32{ + 24, // 0: gateway.v1.Session.created_at:type_name -> google.protobuf.Timestamp + 24, // 1: gateway.v1.Session.last_active_at:type_name -> google.protobuf.Timestamp + 24, // 2: gateway.v1.Message.at:type_name -> google.protobuf.Timestamp + 2, // 3: gateway.v1.Turn.tool_calls:type_name -> gateway.v1.ToolCall + 24, // 4: gateway.v1.Turn.created_at:type_name -> google.protobuf.Timestamp + 24, // 5: gateway.v1.Turn.updated_at:type_name -> google.protobuf.Timestamp + 0, // 6: gateway.v1.SnapshotResponse.sessions:type_name -> gateway.v1.Session + 22, // 7: gateway.v1.SnapshotResponse.models_by_provider:type_name -> gateway.v1.SnapshotResponse.ModelsByProviderEntry + 23, // 8: gateway.v1.SnapshotResponse.active_personas:type_name -> gateway.v1.SnapshotResponse.ActivePersonasEntry + 0, // 9: gateway.v1.GetSessionResponse.session:type_name -> gateway.v1.Session + 1, // 10: gateway.v1.RecentMessagesResponse.messages:type_name -> gateway.v1.Message + 4, // 11: gateway.v1.RecentTurnsResponse.turns:type_name -> gateway.v1.Turn + 1, // 12: gateway.v1.RouteRequest.message:type_name -> gateway.v1.Message + 1, // 13: gateway.v1.StreamRequest.message:type_name -> gateway.v1.Message + 2, // 14: gateway.v1.StreamResponse.tool:type_name -> gateway.v1.ToolCall + 3, // 15: gateway.v1.StreamResponse.media:type_name -> gateway.v1.Media + 5, // 16: gateway.v1.SnapshotResponse.ModelsByProviderEntry.value:type_name -> gateway.v1.StringList + 6, // 17: gateway.v1.ChatService.Snapshot:input_type -> gateway.v1.SnapshotRequest + 8, // 18: gateway.v1.ChatService.GetSession:input_type -> gateway.v1.GetSessionRequest + 10, // 19: gateway.v1.ChatService.RecentMessages:input_type -> gateway.v1.RecentMessagesRequest + 12, // 20: gateway.v1.ChatService.RecentTurns:input_type -> gateway.v1.RecentTurnsRequest + 14, // 21: gateway.v1.ChatService.Route:input_type -> gateway.v1.RouteRequest + 16, // 22: gateway.v1.ChatService.Stream:input_type -> gateway.v1.StreamRequest + 18, // 23: gateway.v1.ChatService.Cancel:input_type -> gateway.v1.CancelRequest + 20, // 24: gateway.v1.ChatService.SetPersona:input_type -> gateway.v1.SetPersonaRequest + 7, // 25: gateway.v1.ChatService.Snapshot:output_type -> gateway.v1.SnapshotResponse + 9, // 26: gateway.v1.ChatService.GetSession:output_type -> gateway.v1.GetSessionResponse + 11, // 27: gateway.v1.ChatService.RecentMessages:output_type -> gateway.v1.RecentMessagesResponse + 13, // 28: gateway.v1.ChatService.RecentTurns:output_type -> gateway.v1.RecentTurnsResponse + 15, // 29: gateway.v1.ChatService.Route:output_type -> gateway.v1.RouteResponse + 17, // 30: gateway.v1.ChatService.Stream:output_type -> gateway.v1.StreamResponse + 19, // 31: gateway.v1.ChatService.Cancel:output_type -> gateway.v1.CancelResponse + 21, // 32: gateway.v1.ChatService.SetPersona:output_type -> gateway.v1.SetPersonaResponse + 25, // [25:33] is the sub-list for method output_type + 17, // [17:25] is the sub-list for method input_type + 17, // [17:17] is the sub-list for extension type_name + 17, // [17:17] is the sub-list for extension extendee + 0, // [0:17] is the sub-list for field type_name +} + +func init() { file_gateway_v1_chat_proto_init() } +func file_gateway_v1_chat_proto_init() { + if File_gateway_v1_chat_proto != nil { + return + } + file_gateway_v1_chat_proto_msgTypes[3].OneofWrappers = []any{} + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_gateway_v1_chat_proto_rawDesc), len(file_gateway_v1_chat_proto_rawDesc)), + NumEnums: 0, + NumMessages: 24, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_gateway_v1_chat_proto_goTypes, + DependencyIndexes: file_gateway_v1_chat_proto_depIdxs, + MessageInfos: file_gateway_v1_chat_proto_msgTypes, + }.Build() + File_gateway_v1_chat_proto = out.File + file_gateway_v1_chat_proto_goTypes = nil + file_gateway_v1_chat_proto_depIdxs = nil +} diff --git a/internal/contracts/gateway/v1/chat_grpc.pb.go b/internal/contracts/gateway/v1/chat_grpc.pb.go new file mode 100644 index 000000000..c99b36f83 --- /dev/null +++ b/internal/contracts/gateway/v1/chat_grpc.pb.go @@ -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", +} diff --git a/internal/gateway/chat_contract.go b/internal/gateway/chat_contract.go new file mode 100644 index 000000000..3bccb0eb0 --- /dev/null +++ b/internal/gateway/chat_contract.go @@ -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 +} diff --git a/internal/gateway/chat_local.go b/internal/gateway/chat_local.go new file mode 100644 index 000000000..492d84b40 --- /dev/null +++ b/internal/gateway/chat_local.go @@ -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}) +} diff --git a/internal/gateway/chat_local_test.go b/internal/gateway/chat_local_test.go new file mode 100644 index 000000000..6ac885304 --- /dev/null +++ b/internal/gateway/chat_local_test.go @@ -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") + } +} diff --git a/internal/infrastructure/configuration/defaults.go b/internal/infrastructure/configuration/defaults.go index 5d1cf168c..c9fd8ecaf 100644 --- a/internal/infrastructure/configuration/defaults.go +++ b/internal/infrastructure/configuration/defaults.go @@ -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) diff --git a/internal/infrastructure/configuration/services_test.go b/internal/infrastructure/configuration/services_test.go new file mode 100644 index 000000000..f5a7e4051 --- /dev/null +++ b/internal/infrastructure/configuration/services_test.go @@ -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) + } + } + }) + } +} diff --git a/internal/infrastructure/configuration/validate.go b/internal/infrastructure/configuration/validate.go index e47e8cf15..8cb9eecfb 100644 --- a/internal/infrastructure/configuration/validate.go +++ b/internal/infrastructure/configuration/validate.go @@ -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 diff --git a/internal/infrastructure/gatewayrpc/client.go b/internal/infrastructure/gatewayrpc/client.go new file mode 100644 index 000000000..5826ad16c --- /dev/null +++ b/internal/infrastructure/gatewayrpc/client.go @@ -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 +} diff --git a/internal/infrastructure/gatewayrpc/conformance_test.go b/internal/infrastructure/gatewayrpc/conformance_test.go new file mode 100644 index 000000000..348c4099e --- /dev/null +++ b/internal/infrastructure/gatewayrpc/conformance_test.go @@ -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) + } +} diff --git a/internal/infrastructure/gatewayrpc/server.go b/internal/infrastructure/gatewayrpc/server.go new file mode 100644 index 000000000..02a7d6c9d --- /dev/null +++ b/internal/infrastructure/gatewayrpc/server.go @@ -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 + } + } + } +} diff --git a/internal/infrastructure/gatewayrpc/values.go b/internal/infrastructure/gatewayrpc/values.go new file mode 100644 index 000000000..7038dad43 --- /dev/null +++ b/internal/infrastructure/gatewayrpc/values.go @@ -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} +} diff --git a/internal/servicediscovery/servicediscovery.go b/internal/servicediscovery/servicediscovery.go index 80bde4730..4545fb6a7 100644 --- a/internal/servicediscovery/servicediscovery.go +++ b/internal/servicediscovery/servicediscovery.go @@ -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 diff --git a/internal/webui/api_chat.go b/internal/webui/api_chat.go index 060f3a6c8..e6e57ad54 100644 --- a/internal/webui/api_chat.go +++ b/internal/webui/api_chat.go @@ -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 { diff --git a/internal/webui/api_chat_test.go b/internal/webui/api_chat_test.go index 3845c1fb6..91812bc89 100644 --- a/internal/webui/api_chat_test.go +++ b/internal/webui/api_chat_test.go @@ -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") diff --git a/internal/webui/api_version_test.go b/internal/webui/api_version_test.go index 9be9f7e7f..bc497ffb4 100644 --- a/internal/webui/api_version_test.go +++ b/internal/webui/api_version_test.go @@ -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": ""} }, } diff --git a/internal/webui/chat_test_helpers_test.go b/internal/webui/chat_test_helpers_test.go new file mode 100644 index 000000000..8069734bd --- /dev/null +++ b/internal/webui/chat_test_helpers_test.go @@ -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 +} diff --git a/internal/webui/server.go b/internal/webui/server.go index 84867f7da..79f7be439 100644 --- a/internal/webui/server.go +++ b/internal/webui/server.go @@ -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. diff --git a/internal/webui/update_report_test.go b/internal/webui/update_report_test.go index aa6b352ea..d341bbeeb 100644 --- a/internal/webui/update_report_test.go +++ b/internal/webui/update_report_test.go @@ -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, diff --git a/proto/README.md b/proto/README.md new file mode 100644 index 000000000..0e27a3c91 --- /dev/null +++ b/proto/README.md @@ -0,0 +1,26 @@ +# Service wire contracts + +Each canonical service owns `proto//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//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`. diff --git a/proto/buf.gen.yaml b/proto/buf.gen.yaml new file mode 100644 index 000000000..7a450a2c3 --- /dev/null +++ b/proto/buf.gen.yaml @@ -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 diff --git a/proto/buf.yaml b/proto/buf.yaml new file mode 100644 index 000000000..f74da98a3 --- /dev/null +++ b/proto/buf.yaml @@ -0,0 +1,9 @@ +version: v2 +modules: + - path: . +lint: + use: + - STANDARD +breaking: + use: + - FILE diff --git a/proto/gateway/v1/chat.proto b/proto/gateway/v1/chat.proto new file mode 100644 index 000000000..5cff6009d --- /dev/null +++ b/proto/gateway/v1/chat.proto @@ -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 models_by_provider = 3; + repeated string providers = 4; + string active_model = 5; + string active_provider = 6; + repeated string personas = 7; + map 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; } diff --git a/tools/proto.sh b/tools/proto.sh new file mode 100644 index 000000000..7683ab68e --- /dev/null +++ b/tools/proto.sh @@ -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