From c0a91c011c7c92a9919730487576bad3dd786eef Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sat, 5 Sep 2026 22:39:17 +1000 Subject: [PATCH 1/6] 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 From 34cb25f1308ddcaec4fa587257620a055a4a6ab7 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sat, 5 Sep 2026 22:39:17 +1000 Subject: [PATCH 2/6] feat(contracts): add gateway service seams and protobuf toolchain --- internal/webui/chat_test_helpers_test.go | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/internal/webui/chat_test_helpers_test.go b/internal/webui/chat_test_helpers_test.go index 8069734bd..991cda755 100644 --- a/internal/webui/chat_test_helpers_test.go +++ b/internal/webui/chat_test_helpers_test.go @@ -9,9 +9,5 @@ func testChatService(router *gateway.Router, sessions gateway.SessionStore, turn } func testLocalChat(service *ChatService) *gateway.LocalChatAdapter { - local, ok := service.Contract.(*gateway.LocalChatAdapter) - if !ok { - panic("test ChatService does not use LocalChatAdapter") - } - return local + return service.Contract.(*gateway.LocalChatAdapter) } From 0a6496d2cdd366d83472d691ee236d8a8475e15d Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sat, 5 Sep 2026 23:06:16 +1000 Subject: [PATCH 3/6] feat(gateway): extract ChatContract service --- Taskfile.yml | 4 +- cmd/archie-gateway/main.go | 10 + deployments/README.md | 7 +- deployments/docker-nats-stack.toml | 4 + deployments/local-ollama-standalone.toml | 4 + deployments/multi-forge-github-gitea.toml | 4 + deployments/single-forge-github.toml | 6 + deployments/systemd-user-service.md | 22 +- internal/app/archied/bootstrap.go | 38 ++- internal/app/archied/chat_service.go | 9 +- internal/app/archied/gateway.go | 103 ++++++++ internal/app/archied/main.go | 52 +++- internal/contracts/gateway/v1/chat.pb.go | 225 ++++++++++++++---- internal/contracts/gateway/v1/chat_grpc.pb.go | 54 ++++- internal/gateway/chat_contract.go | 15 +- internal/gateway/chat_local.go | 20 +- internal/infrastructure/gatewayrpc/client.go | 9 + internal/infrastructure/gatewayrpc/server.go | 9 + internal/webui/chat_test_helpers_test.go | 6 +- proto/gateway/v1/chat.proto | 3 + 20 files changed, 525 insertions(+), 79 deletions(-) create mode 100644 cmd/archie-gateway/main.go create mode 100644 internal/app/archied/gateway.go diff --git a/Taskfile.yml b/Taskfile.yml index c66e7cef3..45a6bb9e6 100644 --- a/Taskfile.yml +++ b/Taskfile.yml @@ -135,7 +135,7 @@ tasks: - go run ./cmd/archied -config-overlay ~/.config/archie/mobile.toml build: - desc: Build archied and archie-agent binaries + desc: Build archie services and agent binaries # Version stamping used to live only in Dockerfile.archied, so any build # from source -- including a host deployment -- reported "dev" for # both components and /version was useless there. Derive the same @@ -153,9 +153,11 @@ tasks: - go.sum generates: - "{{.BIN_DIR}}/archied" + - "{{.BIN_DIR}}/archie-gateway" - "{{.BIN_DIR}}/archie-agent" cmds: - go build -ldflags "-X github.com/samcharles93/archie-core/internal/app/archied.gatewayVersion={{.GATEWAY_VERSION}} -X github.com/samcharles93/archie-core/internal/app/archied.runtimeVersion={{.RUNTIME_VERSION}} -X github.com/samcharles93/archie-core/internal/installtype.buildType=binary" -o {{.BIN_DIR}}/archied ./cmd/archied + - go build -ldflags "-X github.com/samcharles93/archie-core/internal/app/archied.gatewayVersion={{.GATEWAY_VERSION}} -X github.com/samcharles93/archie-core/internal/installtype.buildType=binary" -o {{.BIN_DIR}}/archie-gateway ./cmd/archie-gateway - go build -ldflags "-X github.com/samcharles93/archie-core/internal/app/agentworker.version={{.RUNTIME_VERSION}} -X github.com/samcharles93/archie-core/internal/installtype.buildType=binary" -o {{.BIN_DIR}}/archie-agent ./cmd/archie-agent test: diff --git a/cmd/archie-gateway/main.go b/cmd/archie-gateway/main.go new file mode 100644 index 000000000..c409f8542 --- /dev/null +++ b/cmd/archie-gateway/main.go @@ -0,0 +1,10 @@ +// Command archie-gateway hosts the Gateway Service's gRPC contract. +package main + +import ( + "os" + + "github.com/samcharles93/archie-core/internal/app/archied" +) + +func main() { os.Exit(archied.RunGateway()) } diff --git a/deployments/README.md b/deployments/README.md index f475e03f4..85f6c394e 100644 --- a/deployments/README.md +++ b/deployments/README.md @@ -33,7 +33,12 @@ cp deployments/single-forge-github.toml ~/.config/archie/config.toml Edit API keys in `~/.config/archie/env` or directly in `config.toml`, then launch Archie Core: ```bash -archied +archie-gateway -config ~/.config/archie/config.toml -listen 127.0.0.1:8585 & +archied -config ~/.config/archie/config.toml # or via systemd: systemctl --user start archied ``` + +The templates use the extracted Gateway Service by default. Start +`archie-gateway` before `archied`; it owns the conversation SQLite file and +serves the `ChatContract` gRPC API on the configured target. diff --git a/deployments/docker-nats-stack.toml b/deployments/docker-nats-stack.toml index 91bdcf7c0..3da07a826 100644 --- a/deployments/docker-nats-stack.toml +++ b/deployments/docker-nats-stack.toml @@ -17,6 +17,10 @@ diff_cap_lines = 0 work_dir = "~/.local/share/archie/work" db_path = "~/.local/share/archie/archie.db" +[services.gateway] +mode = "remote" +target = "127.0.0.1:8585" + [forge] type = "gitea" host = "https://git.example.com" diff --git a/deployments/local-ollama-standalone.toml b/deployments/local-ollama-standalone.toml index b94c8841f..bbb4e7e6b 100644 --- a/deployments/local-ollama-standalone.toml +++ b/deployments/local-ollama-standalone.toml @@ -7,6 +7,10 @@ work_dir = "~/.local/share/archie/work" db_path = "~/.local/share/archie/archie.db" + +[services.gateway] +mode = "remote" +target = "127.0.0.1:8585" poll_interval = "60s" # Standalone execution: Forge polling is disabled diff --git a/deployments/multi-forge-github-gitea.toml b/deployments/multi-forge-github-gitea.toml index 55d80b100..06fedf91f 100644 --- a/deployments/multi-forge-github-gitea.toml +++ b/deployments/multi-forge-github-gitea.toml @@ -8,6 +8,10 @@ work_dir = "~/.local/share/archie/work" db_path = "~/.local/share/archie/archie.db" + +[services.gateway] +mode = "remote" +target = "127.0.0.1:8585" poll_interval = "60s" [models] diff --git a/deployments/single-forge-github.toml b/deployments/single-forge-github.toml index 0e48059fd..4ddec6ca6 100644 --- a/deployments/single-forge-github.toml +++ b/deployments/single-forge-github.toml @@ -13,6 +13,12 @@ bot_user = "archie-bot" bot_email = "archie-bot@users.noreply.github.com" diff_cap_lines = 400 +# The Gateway Service owns conversational state and serves ChatContract over +# gRPC. Run archie-gateway alongside archied with this address. +[services.gateway] +mode = "remote" +target = "127.0.0.1:8585" + [forge] type = "github" host = "https://github.com" diff --git a/deployments/systemd-user-service.md b/deployments/systemd-user-service.md index 34c678910..76b00f467 100644 --- a/deployments/systemd-user-service.md +++ b/deployments/systemd-user-service.md @@ -4,7 +4,7 @@ This runbook describes how to manage `archied` as a background user service on L --- -## 1. Unit File (`~/.config/systemd/user/archied.service`) +## 1. Unit Files (`~/.config/systemd/user/archied.service` and `archie-gateway.service`) Create the systemd user service file at `~/.config/systemd/user/archied.service`: @@ -25,6 +25,24 @@ RestartSec=5s WantedBy=default.target ``` +Create the Gateway Service unit beside it: + +```ini +[Unit] +Description=Archie Gateway Service +After=network.target + +[Service] +Type=simple +ExecStart=%h/.local/bin/archie-gateway -config %h/.config/archie/config.toml -listen 127.0.0.1:8585 +EnvironmentFile=-%h/.config/archie/env +Restart=on-failure +RestartSec=5s + +[Install] +WantedBy=default.target +``` + --- ## 2. Enabling User Linger (`loginctl`) @@ -52,7 +70,7 @@ systemctl --user daemon-reload Enable and start the service immediately: ```bash -systemctl --user enable --now archied +systemctl --user enable --now archie-gateway archied ``` Check service status: diff --git a/internal/app/archied/bootstrap.go b/internal/app/archied/bootstrap.go index 547e5b334..7cd8c07fd 100644 --- a/internal/app/archied/bootstrap.go +++ b/internal/app/archied/bootstrap.go @@ -481,7 +481,7 @@ func (b *boot) setupContainers(ctx context.Context) func() { // setupLLMAndChat wires the runtime, tool registry, model management, // personas and the dashboard's chat service. -func (b *boot) setupLLMAndChat(ctx context.Context) { +func (b *boot) setupLLMAndChat(ctx context.Context) { //nolint:funlen // composition root keeps the Gateway wiring in one lifecycle phase cfg, log := b.cfg, b.log // ── LLM runtime ────────────────────────────────────────────────── @@ -515,6 +515,19 @@ func (b *boot) setupLLMAndChat(ctx context.Context) { b.chatController = chatController b.updateService = makeUpdateService(telegramSetup{Cfg: config.NewHolder(cfg)}) b.web.WorkRequests = b.chatTasks + if cfg.Services.Gateway.Mode == "remote" { + // The daemon is a Gateway consumer in this mode. The Gateway Service + // owns Router, session SQLite, model selection and persona state; keep + // those implementation objects out of the daemon's web composition. + contract, closeContract := b.chatContract(cfg.Services.Gateway, nil) + b.addCleanup(closeContract) + b.web.Chat = &webui.ChatService{Contract: contract} + if b.updateService != nil { + b.web.Chat.Updates = b.updateService + } + b.setupReadinessProbes() + return + } // The dashboard is another gateway, not a second chat implementation. It // shares the router, session history, model selection, personas and LLM @@ -545,9 +558,14 @@ func (b *boot) setupLLMAndChat(ctx context.Context) { taskLogs: b.taskLogs, }, ChatTaskActor: chatTaskActorAdapter{ - tasks: b.st.TaskByID, - handler: b.web.Handler(), - token: func() string { return b.web.Token }, + tasks: b.st.TaskByID, + contract: func() gateway.ChatContract { + if b.cfg.Services.Gateway.Mode == "remote" && b.web != nil && b.web.Chat != nil { + return b.web.Chat.Contract + } + return nil + }(), + token: func() string { return b.web.Token }, }, DefaultChatIdentity: b.defaultChatIdentity, SessionStore: b.chatSessionStore, Bus: b.bus, Log: log, Secrets: b.secrets, @@ -559,6 +577,7 @@ func (b *boot) setupLLMAndChat(ctx context.Context) { Router: b.webRouter, Sessions: b.chatSessionStore, Turns: gateway.NewTurns(log), Models: b.chatModels, Personas: b.personas, + TaskActor: chatTaskActorAdapter{tasks: b.st.TaskByID, apply: applyGatewayTaskAction(b.st)}, } contract, closeContract := b.chatContract(cfg.Services.Gateway, localChat) b.addCleanup(closeContract) @@ -589,9 +608,14 @@ func (b *boot) setupGateways(ctx context.Context, cfgPath, overlayPath string) b taskLogs: b.taskLogs, }, ChatTaskActor: chatTaskActorAdapter{ - tasks: b.st.TaskByID, - handler: b.web.Handler(), - token: func() string { return b.web.Token }, + tasks: b.st.TaskByID, + contract: func() gateway.ChatContract { + if b.cfg.Services.Gateway.Mode == "remote" && b.web != nil && b.web.Chat != nil { + return b.web.Chat.Contract + } + return nil + }(), + token: func() string { return b.web.Token }, }, DefaultChatIdentity: b.defaultChatIdentity, SessionStore: b.chatSessionStore, Updates: b.updateService, Secrets: b.secrets, diff --git a/internal/app/archied/chat_service.go b/internal/app/archied/chat_service.go index 1c89d7aca..0ff5cc390 100644 --- a/internal/app/archied/chat_service.go +++ b/internal/app/archied/chat_service.go @@ -1,12 +1,11 @@ package archied import ( - "crypto/tls" "fmt" "strings" "google.golang.org/grpc" - "google.golang.org/grpc/credentials" + "google.golang.org/grpc/credentials/insecure" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/gateway" @@ -26,7 +25,11 @@ func composeChatContract(settings config.ServiceConnection, local gateway.ChatCo 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...) + // The first extraction uses a loopback gRPC hop. Deployments that put + // the Gateway on a separate trust boundary supply their own transport + // credentials through options; the local process split must be usable + // without manufacturing a certificate in the config loader. + opts := append([]grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}, options...) conn, err := grpc.NewClient(settings.Target, opts...) if err != nil { return nil, nil, fmt.Errorf("create gateway client: %w", err) diff --git a/internal/app/archied/gateway.go b/internal/app/archied/gateway.go new file mode 100644 index 000000000..afaccc67c --- /dev/null +++ b/internal/app/archied/gateway.go @@ -0,0 +1,103 @@ +package archied + +import ( + "context" + "flag" + "fmt" + "net" + "os" + "os/signal" + "syscall" + + "google.golang.org/grpc" + + "github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc" +) + +// RunGateway starts the standalone Gateway Service. The service owns the +// conversation store and the Gateway composition; the daemon reaches it only +// through the generated ChatContract RPC. +func RunGateway() int { + args := gatewayArgs() + if args.version { + fmt.Printf("archie-gateway %s\n", gatewayVersion) + return 0 + } + + root, cancel := context.WithCancel(context.Background()) + defer cancel() + ctx, stop := signal.NotifyContext(root, os.Interrupt, syscall.SIGTERM) + defer stop() + + b := newBootstrap() + if err := b.loadConfig(ctx, args.config, args.overlay, false); err != nil { + return 1 + } + defer b.cleanup() + if err := b.openStores(ctx); err != nil { + return 1 + } + b.loadCatalog(ctx, args.config) + // setupLLMAndChat also wires the task adapters used by Gateway tools. It + // normally publishes a dashboard contract, but the standalone service + // publishes that same local adapter over gRPC below. + b.setupObservability() + b.cfg.Services.Gateway.Mode = "inproc" + b.cfg.Services.Gateway.Target = "" + b.setupLLMAndChat(ctx) + if b.web == nil || b.web.Chat == nil || b.web.Chat.Contract == nil { + b.log.Error("gateway contract was not composed") + return 1 + } + + listener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", args.listen) + if err != nil { + b.log.Error("listen for gateway", "addr", args.listen, "err", err) + return 1 + } + defer listener.Close() + server := grpc.NewServer() + gatewayrpc.RegisterServer(server, b.web.Chat.Contract) + serveErr := make(chan error, 1) + go func() { serveErr <- server.Serve(listener) }() + b.log.Info("archie-gateway running", "addr", listener.Addr().String()) + + select { + case <-ctx.Done(): + server.GracefulStop() + return 0 + case err := <-serveErr: + if err != nil { + b.log.Error("gateway server stopped", "err", err) + return 1 + } + return 0 + } +} + +type gatewayRunArgs struct { + config string + overlay string + listen string + version bool +} + +func gatewayArgs() gatewayRunArgs { + args := gatewayRunArgs{config: filepathConfigHome()} + flag.StringVar(&args.config, "config", args.config, "path to a TOML/YAML config file or configuration directory") + flag.StringVar(&args.overlay, "config-overlay", "", "path to a TOML/YAML overlay file or configuration directory") + flag.StringVar(&args.listen, "listen", "127.0.0.1:8585", "gateway gRPC listen address") + flag.BoolVar(&args.version, "version", false, "print the Gateway Service version and exit") + flag.Parse() + return args +} + +func filepathConfigHome() string { + base := os.Getenv("XDG_CONFIG_HOME") + if base == "" { + if home, err := os.UserHomeDir(); err == nil { + base = home + "/.config" + } + } + return base + "/archie/config.toml" +} diff --git a/internal/app/archied/main.go b/internal/app/archied/main.go index c0fbdc10d..1ef46337e 100644 --- a/internal/app/archied/main.go +++ b/internal/app/archied/main.go @@ -665,14 +665,60 @@ func (a chatTaskLogReaderAdapter) ReadChatTaskLogs( // It enforces identity scoping so an identity cannot mutate another // identity's tasks. type chatTaskActorAdapter struct { - tasks func(context.Context, int64) (*store.Task, error) - handler http.Handler - token func() string + tasks func(context.Context, int64) (*store.Task, error) + apply func(context.Context, string, int64, taskstate.Action) (gateway.TaskActionResult, error) + contract gateway.ChatContract + handler http.Handler + token func() string +} + +func applyGatewayTaskAction(st store.TaskStore) func(context.Context, string, int64, taskstate.Action) (gateway.TaskActionResult, error) { + return func(ctx context.Context, identity string, taskID int64, action taskstate.Action) (gateway.TaskActionResult, error) { + task, err := st.TaskByID(ctx, taskID) + if err != nil { + return gateway.TaskActionResult{}, err + } + if task == nil { + return gateway.TaskActionResult{}, fmt.Errorf("task %d not found", taskID) + } + if task.Identity != identity { + return gateway.TaskActionResult{}, fmt.Errorf("task %d belongs to %q, not %q", taskID, task.Identity, identity) + } + if err := taskstate.CheckAction(task.Status, action); err != nil { + return gateway.TaskActionResult{}, err + } + switch action { + case taskstate.ActionApprove: + err = st.Requeue(ctx, taskID, store.StatusWaitingHuman, "implement") + case taskstate.ActionRetry: + err = st.RetryTask(ctx, taskID, store.StatusParked, task.Workflow) + case taskstate.ActionCancel, taskstate.ActionReject: + err = st.Transition(ctx, taskID, task.Status, store.StatusClosedWontDo, "declined by "+identity) + case taskstate.ActionAbandon: + err = st.Transition(ctx, taskID, store.StatusParked, store.StatusClosedWontDo, "abandoned by "+identity) + case taskstate.ActionStop: + return gateway.TaskActionResult{}, fmt.Errorf("stopping running tasks is unavailable in the Gateway Service") + case taskstate.ActionArchive: + _, err = st.ArchiveTask(ctx, taskID, task.Status, events.Event{Kind: events.KindTaskArchiveRequested, TaskID: taskID}) + default: + return gateway.TaskActionResult{}, fmt.Errorf("unsupported task action %q", action) + } + if err != nil { + return gateway.TaskActionResult{}, err + } + return gateway.TaskActionResult{TaskID: taskID, Action: string(action), Message: fmt.Sprintf("Applied %s to task %d.", action, taskID)}, nil + } } func (a chatTaskActorAdapter) ApplyChatTaskAction( ctx context.Context, identity string, taskID int64, action taskstate.Action, ) (gateway.TaskActionResult, error) { + if a.contract != nil { + return a.contract.ApplyTaskAction(ctx, identity, taskID, action) + } + if a.apply != nil { + return a.apply(ctx, identity, taskID, action) + } if a.tasks == nil || a.handler == nil { return gateway.TaskActionResult{}, fmt.Errorf("task actions are not configured") } diff --git a/internal/contracts/gateway/v1/chat.pb.go b/internal/contracts/gateway/v1/chat.pb.go index 49032032d..a81a28008 100644 --- a/internal/contracts/gateway/v1/chat.pb.go +++ b/internal/contracts/gateway/v1/chat.pb.go @@ -1486,6 +1486,126 @@ func (x *SetPersonaResponse) GetFound() bool { return false } +type ApplyTaskActionRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Identity string `protobuf:"bytes,1,opt,name=identity,proto3" json:"identity,omitempty"` + TaskId int64 `protobuf:"varint,2,opt,name=task_id,json=taskId,proto3" json:"task_id,omitempty"` + Action string `protobuf:"bytes,3,opt,name=action,proto3" json:"action,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ApplyTaskActionRequest) Reset() { + *x = ApplyTaskActionRequest{} + mi := &file_gateway_v1_chat_proto_msgTypes[22] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ApplyTaskActionRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ApplyTaskActionRequest) ProtoMessage() {} + +func (x *ApplyTaskActionRequest) ProtoReflect() protoreflect.Message { + mi := &file_gateway_v1_chat_proto_msgTypes[22] + 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 ApplyTaskActionRequest.ProtoReflect.Descriptor instead. +func (*ApplyTaskActionRequest) Descriptor() ([]byte, []int) { + return file_gateway_v1_chat_proto_rawDescGZIP(), []int{22} +} + +func (x *ApplyTaskActionRequest) GetIdentity() string { + if x != nil { + return x.Identity + } + return "" +} + +func (x *ApplyTaskActionRequest) GetTaskId() int64 { + if x != nil { + return x.TaskId + } + return 0 +} + +func (x *ApplyTaskActionRequest) GetAction() string { + if x != nil { + return x.Action + } + return "" +} + +type ApplyTaskActionResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + TaskId int64 `protobuf:"varint,1,opt,name=task_id,json=taskId,proto3" json:"task_id,omitempty"` + Action string `protobuf:"bytes,2,opt,name=action,proto3" json:"action,omitempty"` + Message string `protobuf:"bytes,3,opt,name=message,proto3" json:"message,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ApplyTaskActionResponse) Reset() { + *x = ApplyTaskActionResponse{} + mi := &file_gateway_v1_chat_proto_msgTypes[23] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ApplyTaskActionResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ApplyTaskActionResponse) ProtoMessage() {} + +func (x *ApplyTaskActionResponse) ProtoReflect() protoreflect.Message { + mi := &file_gateway_v1_chat_proto_msgTypes[23] + 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 ApplyTaskActionResponse.ProtoReflect.Descriptor instead. +func (*ApplyTaskActionResponse) Descriptor() ([]byte, []int) { + return file_gateway_v1_chat_proto_rawDescGZIP(), []int{23} +} + +func (x *ApplyTaskActionResponse) GetTaskId() int64 { + if x != nil { + return x.TaskId + } + return 0 +} + +func (x *ApplyTaskActionResponse) GetAction() string { + if x != nil { + return x.Action + } + return "" +} + +func (x *ApplyTaskActionResponse) GetMessage() string { + if x != nil { + return x.Message + } + return "" +} + var File_gateway_v1_chat_proto protoreflect.FileDescriptor const file_gateway_v1_chat_proto_rawDesc = "" + @@ -1632,7 +1752,15 @@ const file_gateway_v1_chat_proto_rawDesc = "" + "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" + + "\x05found\x18\x01 \x01(\bR\x05found\"e\n" + + "\x16ApplyTaskActionRequest\x12\x1a\n" + + "\bidentity\x18\x01 \x01(\tR\bidentity\x12\x17\n" + + "\atask_id\x18\x02 \x01(\x03R\x06taskId\x12\x16\n" + + "\x06action\x18\x03 \x01(\tR\x06action\"d\n" + + "\x17ApplyTaskActionResponse\x12\x17\n" + + "\atask_id\x18\x01 \x01(\x03R\x06taskId\x12\x16\n" + + "\x06action\x18\x02 \x01(\tR\x06action\x12\x18\n" + + "\amessage\x18\x03 \x01(\tR\amessage2\xb5\x05\n" + "\vChatService\x12E\n" + "\bSnapshot\x12\x1b.gateway.v1.SnapshotRequest\x1a\x1c.gateway.v1.SnapshotResponse\x12K\n" + "\n" + @@ -1643,7 +1771,8 @@ const file_gateway_v1_chat_proto_rawDesc = "" + "\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" + + "SetPersona\x12\x1d.gateway.v1.SetPersonaRequest\x1a\x1e.gateway.v1.SetPersonaResponse\x12Z\n" + + "\x0fApplyTaskAction\x12\".gateway.v1.ApplyTaskActionRequest\x1a#.gateway.v1.ApplyTaskActionResponseB\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" @@ -1660,44 +1789,46 @@ func file_gateway_v1_chat_proto_rawDescGZIP() []byte { return file_gateway_v1_chat_proto_rawDescData } -var file_gateway_v1_chat_proto_msgTypes = make([]protoimpl.MessageInfo, 24) +var file_gateway_v1_chat_proto_msgTypes = make([]protoimpl.MessageInfo, 26) 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 + (*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 + (*ApplyTaskActionRequest)(nil), // 22: gateway.v1.ApplyTaskActionRequest + (*ApplyTaskActionResponse)(nil), // 23: gateway.v1.ApplyTaskActionResponse + nil, // 24: gateway.v1.SnapshotResponse.ModelsByProviderEntry + nil, // 25: gateway.v1.SnapshotResponse.ActivePersonasEntry + (*timestamppb.Timestamp)(nil), // 26: 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 + 26, // 0: gateway.v1.Session.created_at:type_name -> google.protobuf.Timestamp + 26, // 1: gateway.v1.Session.last_active_at:type_name -> google.protobuf.Timestamp + 26, // 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 + 26, // 4: gateway.v1.Turn.created_at:type_name -> google.protobuf.Timestamp + 26, // 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 + 24, // 7: gateway.v1.SnapshotResponse.models_by_provider:type_name -> gateway.v1.SnapshotResponse.ModelsByProviderEntry + 25, // 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 @@ -1714,16 +1845,18 @@ var file_gateway_v1_chat_proto_depIdxs = []int32{ 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 + 22, // 25: gateway.v1.ChatService.ApplyTaskAction:input_type -> gateway.v1.ApplyTaskActionRequest + 7, // 26: gateway.v1.ChatService.Snapshot:output_type -> gateway.v1.SnapshotResponse + 9, // 27: gateway.v1.ChatService.GetSession:output_type -> gateway.v1.GetSessionResponse + 11, // 28: gateway.v1.ChatService.RecentMessages:output_type -> gateway.v1.RecentMessagesResponse + 13, // 29: gateway.v1.ChatService.RecentTurns:output_type -> gateway.v1.RecentTurnsResponse + 15, // 30: gateway.v1.ChatService.Route:output_type -> gateway.v1.RouteResponse + 17, // 31: gateway.v1.ChatService.Stream:output_type -> gateway.v1.StreamResponse + 19, // 32: gateway.v1.ChatService.Cancel:output_type -> gateway.v1.CancelResponse + 21, // 33: gateway.v1.ChatService.SetPersona:output_type -> gateway.v1.SetPersonaResponse + 23, // 34: gateway.v1.ChatService.ApplyTaskAction:output_type -> gateway.v1.ApplyTaskActionResponse + 26, // [26:35] is the sub-list for method output_type + 17, // [17:26] 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 @@ -1741,7 +1874,7 @@ func file_gateway_v1_chat_proto_init() { 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, + NumMessages: 26, NumExtensions: 0, NumServices: 1, }, diff --git a/internal/contracts/gateway/v1/chat_grpc.pb.go b/internal/contracts/gateway/v1/chat_grpc.pb.go index c99b36f83..adec876a9 100644 --- a/internal/contracts/gateway/v1/chat_grpc.pb.go +++ b/internal/contracts/gateway/v1/chat_grpc.pb.go @@ -19,14 +19,15 @@ import ( const _ = grpc.SupportPackageIsVersion9 const ( - ChatService_Snapshot_FullMethodName = "/gateway.v1.ChatService/Snapshot" - ChatService_GetSession_FullMethodName = "/gateway.v1.ChatService/GetSession" - ChatService_RecentMessages_FullMethodName = "/gateway.v1.ChatService/RecentMessages" - ChatService_RecentTurns_FullMethodName = "/gateway.v1.ChatService/RecentTurns" - ChatService_Route_FullMethodName = "/gateway.v1.ChatService/Route" - ChatService_Stream_FullMethodName = "/gateway.v1.ChatService/Stream" - ChatService_Cancel_FullMethodName = "/gateway.v1.ChatService/Cancel" - ChatService_SetPersona_FullMethodName = "/gateway.v1.ChatService/SetPersona" + ChatService_Snapshot_FullMethodName = "/gateway.v1.ChatService/Snapshot" + ChatService_GetSession_FullMethodName = "/gateway.v1.ChatService/GetSession" + ChatService_RecentMessages_FullMethodName = "/gateway.v1.ChatService/RecentMessages" + ChatService_RecentTurns_FullMethodName = "/gateway.v1.ChatService/RecentTurns" + ChatService_Route_FullMethodName = "/gateway.v1.ChatService/Route" + ChatService_Stream_FullMethodName = "/gateway.v1.ChatService/Stream" + ChatService_Cancel_FullMethodName = "/gateway.v1.ChatService/Cancel" + ChatService_SetPersona_FullMethodName = "/gateway.v1.ChatService/SetPersona" + ChatService_ApplyTaskAction_FullMethodName = "/gateway.v1.ChatService/ApplyTaskAction" ) // ChatServiceClient is the client API for ChatService service. @@ -41,6 +42,7 @@ type ChatServiceClient interface { Stream(ctx context.Context, in *StreamRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[StreamResponse], error) Cancel(ctx context.Context, in *CancelRequest, opts ...grpc.CallOption) (*CancelResponse, error) SetPersona(ctx context.Context, in *SetPersonaRequest, opts ...grpc.CallOption) (*SetPersonaResponse, error) + ApplyTaskAction(ctx context.Context, in *ApplyTaskActionRequest, opts ...grpc.CallOption) (*ApplyTaskActionResponse, error) } type chatServiceClient struct { @@ -140,6 +142,16 @@ func (c *chatServiceClient) SetPersona(ctx context.Context, in *SetPersonaReques return out, nil } +func (c *chatServiceClient) ApplyTaskAction(ctx context.Context, in *ApplyTaskActionRequest, opts ...grpc.CallOption) (*ApplyTaskActionResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(ApplyTaskActionResponse) + err := c.cc.Invoke(ctx, ChatService_ApplyTaskAction_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + // ChatServiceServer is the server API for ChatService service. // All implementations must embed UnimplementedChatServiceServer // for forward compatibility. @@ -152,6 +164,7 @@ type ChatServiceServer interface { Stream(*StreamRequest, grpc.ServerStreamingServer[StreamResponse]) error Cancel(context.Context, *CancelRequest) (*CancelResponse, error) SetPersona(context.Context, *SetPersonaRequest) (*SetPersonaResponse, error) + ApplyTaskAction(context.Context, *ApplyTaskActionRequest) (*ApplyTaskActionResponse, error) mustEmbedUnimplementedChatServiceServer() } @@ -186,6 +199,9 @@ func (UnimplementedChatServiceServer) Cancel(context.Context, *CancelRequest) (* func (UnimplementedChatServiceServer) SetPersona(context.Context, *SetPersonaRequest) (*SetPersonaResponse, error) { return nil, status.Error(codes.Unimplemented, "method SetPersona not implemented") } +func (UnimplementedChatServiceServer) ApplyTaskAction(context.Context, *ApplyTaskActionRequest) (*ApplyTaskActionResponse, error) { + return nil, status.Error(codes.Unimplemented, "method ApplyTaskAction not implemented") +} func (UnimplementedChatServiceServer) mustEmbedUnimplementedChatServiceServer() {} func (UnimplementedChatServiceServer) testEmbeddedByValue() {} @@ -344,6 +360,24 @@ func _ChatService_SetPersona_Handler(srv interface{}, ctx context.Context, dec f return interceptor(ctx, in, info, handler) } +func _ChatService_ApplyTaskAction_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ApplyTaskActionRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ChatServiceServer).ApplyTaskAction(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: ChatService_ApplyTaskAction_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ChatServiceServer).ApplyTaskAction(ctx, req.(*ApplyTaskActionRequest)) + } + return interceptor(ctx, in, info, handler) +} + // ChatService_ServiceDesc is the grpc.ServiceDesc for ChatService service. // It's only intended for direct use with grpc.RegisterService, // and not to be introspected or modified (even as a copy) @@ -379,6 +413,10 @@ var ChatService_ServiceDesc = grpc.ServiceDesc{ MethodName: "SetPersona", Handler: _ChatService_SetPersona_Handler, }, + { + MethodName: "ApplyTaskAction", + Handler: _ChatService_ApplyTaskAction_Handler, + }, }, Streams: []grpc.StreamDesc{ { diff --git a/internal/gateway/chat_contract.go b/internal/gateway/chat_contract.go index 3bccb0eb0..a8dcd0880 100644 --- a/internal/gateway/chat_contract.go +++ b/internal/gateway/chat_contract.go @@ -1,10 +1,14 @@ package gateway -import "context" +import ( + "context" + + "github.com/samcharles93/archie-core/internal/taskstate" +) // ChatContract is the conversational boundary consumed by channel frontends. // Results are snapshots: callers must not rely on shared object identity. -type ChatContract interface { +type ChatContract interface { //nolint:interfacebloat // wire contract intentionally covers the complete Gateway facade Snapshot(context.Context) (ChatSnapshot, error) GetSession(context.Context, string) (SessionContext, bool, error) RecentMessages(context.Context, string, int) ([]Message, error) @@ -15,6 +19,13 @@ type ChatContract interface { Stream(context.Context, Message) (<-chan ChatEvent, error) Cancel(context.Context, string) (ChatCancellation, error) SetPersona(context.Context, string, string) (bool, error) + ChatTaskActionContract +} + +// ChatTaskActionContract is the operator task mutation capability exposed by +// the Gateway. It is separate so read/turn consumers do not need to model it. +type ChatTaskActionContract interface { + ApplyTaskAction(context.Context, string, int64, taskstate.Action) (TaskActionResult, error) } type ChatSnapshot struct { diff --git a/internal/gateway/chat_local.go b/internal/gateway/chat_local.go index 492d84b40..914b30d54 100644 --- a/internal/gateway/chat_local.go +++ b/internal/gateway/chat_local.go @@ -5,17 +5,20 @@ import ( "errors" "slices" "strings" + + "github.com/samcharles93/archie-core/internal/taskstate" ) // LocalChatAdapter connects the chat boundary to the existing gateway owners. // Composition configures the Router, including updates and dangerous actions, // before publishing this adapter to consumers. type LocalChatAdapter struct { - Router *Router - Sessions SessionStore - Turns *Turns - Models ModelManager - Personas *PersonaRegistry + Router *Router + Sessions SessionStore + Turns *Turns + Models ModelManager + Personas *PersonaRegistry + TaskActor ChatTaskActor } var _ ChatContract = (*LocalChatAdapter)(nil) @@ -105,6 +108,13 @@ func (a *LocalChatAdapter) SetPersona(ctx context.Context, id, name string) (boo return a.Personas.SetActive(id, strings.ToLower(name)), nil } +func (a *LocalChatAdapter) ApplyTaskAction(ctx context.Context, identity string, taskID int64, action taskstate.Action) (TaskActionResult, error) { + if a.TaskActor == nil { + return TaskActionResult{}, ErrChatCapabilityUnavailable + } + return a.TaskActor.ApplyChatTaskAction(ctx, identity, taskID, action) +} + func (a *LocalChatAdapter) Stream(ctx context.Context, msg Message) (<-chan ChatEvent, error) { if err := ctx.Err(); err != nil { return nil, err diff --git a/internal/infrastructure/gatewayrpc/client.go b/internal/infrastructure/gatewayrpc/client.go index 5826ad16c..d5a165909 100644 --- a/internal/infrastructure/gatewayrpc/client.go +++ b/internal/infrastructure/gatewayrpc/client.go @@ -10,6 +10,7 @@ import ( pb "github.com/samcharles93/archie-core/internal/contracts/gateway/v1" "github.com/samcharles93/archie-core/internal/gateway" + "github.com/samcharles93/archie-core/internal/taskstate" ) var _ gateway.ChatContract = (*Client)(nil) @@ -76,6 +77,14 @@ func (c *Client) SetPersona(ctx context.Context, id, name string) (bool, error) return v.Found, nil } +func (c *Client) ApplyTaskAction(ctx context.Context, identity string, taskID int64, action taskstate.Action) (gateway.TaskActionResult, error) { + v, err := c.client.ApplyTaskAction(ctx, &pb.ApplyTaskActionRequest{Identity: identity, TaskId: taskID, Action: string(action)}) + if err != nil { + return gateway.TaskActionResult{}, err + } + return gateway.TaskActionResult{TaskID: v.TaskId, Action: v.Action, Message: v.Message}, nil +} + func (c *Client) Stream(ctx context.Context, msg gateway.Message) (<-chan gateway.ChatEvent, error) { stream, err := c.client.Stream(ctx, &pb.StreamRequest{Message: messageProto(msg)}) if err != nil { diff --git a/internal/infrastructure/gatewayrpc/server.go b/internal/infrastructure/gatewayrpc/server.go index 02a7d6c9d..c51a4ab4c 100644 --- a/internal/infrastructure/gatewayrpc/server.go +++ b/internal/infrastructure/gatewayrpc/server.go @@ -7,6 +7,7 @@ import ( pb "github.com/samcharles93/archie-core/internal/contracts/gateway/v1" "github.com/samcharles93/archie-core/internal/gateway" + "github.com/samcharles93/archie-core/internal/taskstate" ) type server struct { @@ -74,6 +75,14 @@ func (s *server) SetPersona(ctx context.Context, r *pb.SetPersonaRequest) (*pb.S return &pb.SetPersonaResponse{Found: v}, nil } +func (s *server) ApplyTaskAction(ctx context.Context, r *pb.ApplyTaskActionRequest) (*pb.ApplyTaskActionResponse, error) { + v, err := s.chat.ApplyTaskAction(ctx, r.Identity, r.TaskId, taskstate.Action(r.Action)) + if err != nil { + return nil, err + } + return &pb.ApplyTaskActionResponse{TaskId: v.TaskID, Action: v.Action, Message: v.Message}, nil +} + func (s *server) Stream(r *pb.StreamRequest, out grpc.ServerStreamingServer[pb.StreamResponse]) error { events, err := s.chat.Stream(out.Context(), messageValue(r.Message)) if err != nil { diff --git a/internal/webui/chat_test_helpers_test.go b/internal/webui/chat_test_helpers_test.go index 991cda755..0c64f3827 100644 --- a/internal/webui/chat_test_helpers_test.go +++ b/internal/webui/chat_test_helpers_test.go @@ -9,5 +9,9 @@ func testChatService(router *gateway.Router, sessions gateway.SessionStore, turn } func testLocalChat(service *ChatService) *gateway.LocalChatAdapter { - return service.Contract.(*gateway.LocalChatAdapter) + local, ok := service.Contract.(*gateway.LocalChatAdapter) + if !ok { + panic("test chat contract is not local") + } + return local } diff --git a/proto/gateway/v1/chat.proto b/proto/gateway/v1/chat.proto index 5cff6009d..5657a5a81 100644 --- a/proto/gateway/v1/chat.proto +++ b/proto/gateway/v1/chat.proto @@ -13,6 +13,7 @@ service ChatService { rpc Stream(StreamRequest) returns (stream StreamResponse); rpc Cancel(CancelRequest) returns (CancelResponse); rpc SetPersona(SetPersonaRequest) returns (SetPersonaResponse); + rpc ApplyTaskAction(ApplyTaskActionRequest) returns (ApplyTaskActionResponse); } message Session { @@ -108,3 +109,5 @@ message CancelRequest { string session_id = 1; } message CancelResponse { bool cancelled = 1; int64 dropped = 2; } message SetPersonaRequest { string session_id = 1; string name = 2; } message SetPersonaResponse { bool found = 1; } +message ApplyTaskActionRequest { string identity = 1; int64 task_id = 2; string action = 3; } +message ApplyTaskActionResponse { int64 task_id = 1; string action = 2; string message = 3; } From 8e41bb9a661dc5816a7fbfe3ffc1fc168a940e34 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sun, 6 Sep 2026 01:35:15 +1000 Subject: [PATCH 4/6] feat(gateway): consolidate task actions and repair daemon default path Phase 1 (extract the Gateway Service), first stage. Repairs the half-migrated working tree so the default (inproc) daemon path works again while keeping the WIP's direction: - chatTaskActorAdapter is contract-only (no HTTP detour); nil contract returns ErrChatCapabilityUnavailable instead of panicking. - openStores opens the conversation store for both processes again; the standalone gateway no longer owns it exclusively. Phase 1 keeps the daemon's Telegram/email routers and session-memory curator reading the same SQLite file; remote conversations arrive when a process that cannot open the file needs them. - setupLLMAndChat composes the local gateway (setupGatewayChat) in default mode and a remote gRPC client in mode=remote; the returned contract is never nil, and Run handles the error. - taskactions.Service is now the single task-mutation implementation shared by the dashboard (webui TaskActionService), the daemon's local gateway actor, and the NATS responder. The daemon registers taskactions.Register so the standalone Gateway's client can forward actions; transport follows the repo's natsrpc pattern. - uncommitted sessions.proto / SessionStoreService gRPC contract deferred: it has no wired consumers (scope creep for this stage). - task_action_adapter_test.go rewritten against the contract chain. task check passes; archied and archie-gateway both build. --- cmd/archie-gateway/main.go | 28 +- internal/app/archied/bootstrap.go | 159 +++------- internal/app/archied/chat_service.go | 9 - internal/app/archied/gateway.go | 153 +++++----- internal/app/archied/gateway_runtime.go | 77 +++++ internal/app/archied/main.go | 117 +------ .../app/archied/task_action_adapter_test.go | 88 ++---- internal/app/archied/task_actions.go | 78 +++++ internal/domain/taskactions/service.go | 201 ++++++++++++ internal/infrastructure/taskactions/rpc.go | 77 +++++ .../infrastructure/taskactions/service.go | 32 ++ internal/infrastructure/taskactions/store.go | 35 +++ internal/webui/api_tasks.go | 286 +++--------------- 13 files changed, 732 insertions(+), 608 deletions(-) create mode 100644 internal/app/archied/gateway_runtime.go create mode 100644 internal/app/archied/task_actions.go create mode 100644 internal/domain/taskactions/service.go create mode 100644 internal/infrastructure/taskactions/rpc.go create mode 100644 internal/infrastructure/taskactions/service.go create mode 100644 internal/infrastructure/taskactions/store.go diff --git a/cmd/archie-gateway/main.go b/cmd/archie-gateway/main.go index c409f8542..521c26b3a 100644 --- a/cmd/archie-gateway/main.go +++ b/cmd/archie-gateway/main.go @@ -2,9 +2,35 @@ package main import ( + "context" + "flag" + "fmt" "os" + "os/signal" + "path/filepath" + "syscall" "github.com/samcharles93/archie-core/internal/app/archied" ) -func main() { os.Exit(archied.RunGateway()) } +func main() { os.Exit(run()) } + +func run() int { + base, err := os.UserConfigDir() + if err != nil { + fmt.Fprintln(os.Stderr, err) + return 1 + } + var options archied.GatewayOptions + flag.StringVar(&options.Config, "config", filepath.Join(base, "archie", "config.toml"), "configuration file or directory") + flag.StringVar(&options.Overlay, "config-overlay", "", "configuration overlay file or directory") + flag.StringVar(&options.Listen, "listen", "127.0.0.1:8585", "gateway gRPC listen address") + flag.Parse() + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + if err := archied.RunGateway(ctx, options); err != nil { + fmt.Fprintln(os.Stderr, err) + return 1 + } + return 0 +} diff --git a/internal/app/archied/bootstrap.go b/internal/app/archied/bootstrap.go index 7cd8c07fd..f30476e2e 100644 --- a/internal/app/archied/bootstrap.go +++ b/internal/app/archied/bootstrap.go @@ -23,7 +23,6 @@ import ( "github.com/samcharles93/ai-sdk/runtime" - "github.com/samcharles93/archie-core/internal/agentexec" channelruntime "github.com/samcharles93/archie-core/internal/channels" "github.com/samcharles93/archie-core/internal/channels/email" "github.com/samcharles93/archie-core/internal/channels/webhook" @@ -48,6 +47,7 @@ import ( "github.com/samcharles93/archie-core/internal/infrastructure/modelcatalog" "github.com/samcharles93/archie-core/internal/infrastructure/sessioncurator" "github.com/samcharles93/archie-core/internal/infrastructure/skillcurator" + "github.com/samcharles93/archie-core/internal/infrastructure/taskactions" "github.com/samcharles93/archie-core/internal/logging" "github.com/samcharles93/archie-core/internal/memory" "github.com/samcharles93/archie-core/internal/plugin" @@ -128,7 +128,6 @@ type boot struct { chatController *gateway.StoreTaskController defaultChatIdentity string updateService *releaseupdate.Service - webRouter *gateway.Router startGateways []func() capabilityHost *plugin.Host @@ -273,6 +272,12 @@ func (b *boot) openStores(ctx context.Context) error { log.Error("close store", "err", err) } }) + // The conversation store is Gateway-owned data, but Phase 1 keeps the + // daemon's own Telegram/email routers and the session-memory curator + // reading the same SQLite file directly (Messaging extraction is + // Phase 4). Both processes opening the same file is the accepted + // Phase 1 shape; remote consumers of the conversation store arrive + // when a process that cannot open the file needs it. chatSessionStore, err := makeTelegramSessionStore(cfg) //nolint:contextcheck // the session store opener takes no context by design; its schema init must complete at boot regardless of cancellation if err != nil { log.Error("open conversation store", "path", conversationDBPath(cfg.DBPath), "err", err) @@ -481,114 +486,37 @@ func (b *boot) setupContainers(ctx context.Context) func() { // setupLLMAndChat wires the runtime, tool registry, model management, // personas and the dashboard's chat service. -func (b *boot) setupLLMAndChat(ctx context.Context) { //nolint:funlen // composition root keeps the Gateway wiring in one lifecycle phase - cfg, log := b.cfg, b.log +func (b *boot) setupLLMAndChat(ctx context.Context) error { + cfg := b.cfg - // ── LLM runtime ────────────────────────────────────────────────── - // Created before gateways so the LLMResponder can be wired into the - // Telegram router for non-command message processing. - providers := executionProviders(cfg) - b.llm = agentexec.NewRuntime(providers) - b.toolReg = tools.NewRegistry() - chatModels := newChatModelManager(cfg.Models, cfg.Chat.Models, b.catalogModels) - chatModels.ApplyModelCatalog(b.catalog) - b.chatModels = chatModels - - // ── Persona registry ───────────────────────────────────────────── - b.personas = gateway.NewPersonaRegistry(gateway.DefaultPersonas()) - - profiles, defaultChatIdentity := chatTaskProfiles(cfg) - var chatTasks gateway.TaskCreator - if len(profiles) > 0 { - chatTasks = gateway.NewStoreTaskCreatorForProfiles( - chatTaskWriterAdapter{enqueue: b.st.EnqueueChatTask}, - profiles, - ) + // The daemon owns the local gateway in default mode: the modular + // monolith keeps serving the ChatContract in-process, with the + // standalone archie-gateway binary prepared as a remote alternative + // (mode = "remote"). The local and remote adapters both satisfy + // gateway.ChatContract; composition picks the transport. + var local gateway.ChatContract + if cfg.Services.Gateway.Mode != "remote" { + // Full local contract: router, sessions, models, personas, task + // commands and the LLM responder. The in-process task-actions + // actor applies mutations directly to the store the daemon owns + // -- no HTTP detour through webui, no NATS hop. + local = b.setupGatewayChat(ctx, taskActionsActor{b}) + } else { + // The daemon still runs its own Telegram/email routers in Phase 1, + // so the runtime objects survive even though the webui chat goes + // over gRPC to the standalone Gateway. + b.setupChatRuntime(cfg) } - b.chatTasks = chatTasks - b.defaultChatIdentity = defaultChatIdentity - chatController := gateway.NewStoreTaskController(chatTaskControllerAdapter{ - taskByID: b.st.TaskByID, - requeue: b.st.Requeue, - transition: b.st.Transition, - }) - b.chatController = chatController - b.updateService = makeUpdateService(telegramSetup{Cfg: config.NewHolder(cfg)}) + + contract, cleanup, err := composeChatContract(cfg.Services.Gateway, local) + if err != nil { + return err + } + b.addCleanup(cleanup) + b.web.Chat = &webui.ChatService{Contract: contract, Updates: b.updateService} b.web.WorkRequests = b.chatTasks - if cfg.Services.Gateway.Mode == "remote" { - // The daemon is a Gateway consumer in this mode. The Gateway Service - // owns Router, session SQLite, model selection and persona state; keep - // those implementation objects out of the daemon's web composition. - contract, closeContract := b.chatContract(cfg.Services.Gateway, nil) - b.addCleanup(closeContract) - b.web.Chat = &webui.ChatService{Contract: contract} - if b.updateService != nil { - b.web.Chat.Updates = b.updateService - } - b.setupReadinessProbes() - return - } - - // The dashboard is another gateway, not a second chat implementation. It - // shares the router, session history, model selection, personas and LLM - // responder with Telegram while using a stable browser channel id. - b.webRouter = gateway.NewRouter(b.st, nil, "web") - b.webRouter.Version = fmt.Sprintf("Archie\nGateway: %s\nRuntime: %s", gatewayVersion, runtimeVersion) - if cfg.Chat.Telegram.Token != (secret.SecretRef{}) || cfg.Chat.Telegram.TokenEnv != "" { - b.webRouter.Restart = func(context.Context) error { - if b.restartTelegram == nil { - return fmt.Errorf("telegram gateway is not ready") - } - return b.restartTelegram() - } - } - b.webRouter.Models = b.chatModels - if b.updateService != nil { - b.webRouter.Updates = b.updateService - } - b.webRouter.Personas = b.personas - b.webRouter.InitSessions(b.chatSessionStore) - configureTaskCommands(b.webRouter, b.chatTasks, b.chatController, chatTaskListerAdapter{tasks: b.st.Tasks}, b.defaultChatIdentity) - webSetup := telegramSetup{ - Cfg: config.NewHolder(cfg), St: b.st, LLM: b.llm, ChatModels: b.chatModels, ToolReg: b.toolReg, - Personas: b.personas, ChatTasks: b.chatTasks, ChatController: b.chatController, - ChatTaskLister: chatTaskListerAdapter{tasks: b.st.Tasks}, - ChatTaskLogs: chatTaskLogReaderAdapter{ - tasks: b.st.TaskByID, - taskLogs: b.taskLogs, - }, - ChatTaskActor: chatTaskActorAdapter{ - tasks: b.st.TaskByID, - contract: func() gateway.ChatContract { - if b.cfg.Services.Gateway.Mode == "remote" && b.web != nil && b.web.Chat != nil { - return b.web.Chat.Contract - } - return nil - }(), - token: func() string { return b.web.Token }, - }, - DefaultChatIdentity: b.defaultChatIdentity, SessionStore: b.chatSessionStore, - Bus: b.bus, Log: log, Secrets: b.secrets, - } - b.webRouter.LLM, b.webRouter.LLMStream = makeChatLLMResponder(ctx, "web", webSetup, b.chatSessionStore, b.webRouter) - b.webRouter.Titles = newChatTitleGenerator(webSetup) - b.webRouter.Log = log - localChat := &gateway.LocalChatAdapter{ - Router: b.webRouter, Sessions: b.chatSessionStore, - Turns: gateway.NewTurns(log), - Models: b.chatModels, Personas: b.personas, - TaskActor: chatTaskActorAdapter{tasks: b.st.TaskByID, apply: applyGatewayTaskAction(b.st)}, - } - 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 - } - - // Operator readiness probes: wired once the chat surface exists so the - // gateway probe can read the real session store and model manager. b.setupReadinessProbes() + return nil } // setupGateways assembles the Telegram, email and webhook gateways. It @@ -608,14 +536,12 @@ func (b *boot) setupGateways(ctx context.Context, cfgPath, overlayPath string) b taskLogs: b.taskLogs, }, ChatTaskActor: chatTaskActorAdapter{ - tasks: b.st.TaskByID, contract: func() gateway.ChatContract { - if b.cfg.Services.Gateway.Mode == "remote" && b.web != nil && b.web.Chat != nil { + if b.web != nil && b.web.Chat != nil { return b.web.Chat.Contract } return nil }(), - token: func() string { return b.web.Token }, }, DefaultChatIdentity: b.defaultChatIdentity, SessionStore: b.chatSessionStore, Updates: b.updateService, Secrets: b.secrets, @@ -915,6 +841,17 @@ func (b *boot) registerNATSRPC() error { return err } b.addCleanup(unsubscribeAgentEvents) + + // The standalone Gateway forwards operator task actions to the daemon + // over NATS. The daemon owns execution cancellation, retry policy, + // forge closure and event persistence; the responder applies the same + // taskactions.Service the dashboard uses. + unsubscribeTaskActions, err := taskactions.Register(coreConn, b.taskActions(), log) + if err != nil { + log.Error("gateway task action register failed", "err", err) + return err + } + b.addCleanup(unsubscribeTaskActions) return nil } @@ -941,7 +878,9 @@ func (b *boot) setupMemory() error { b.memManager = memManager // The dashboard is built before memory exists, so it is wired in here // rather than at construction. - b.web.Memory = memManager + if b.web != nil { + b.web.Memory = memManager + } if err := memManager.Initialize("daemon"); err != nil { log.Warn("memory manager initialize", "err", err) diff --git a/internal/app/archied/chat_service.go b/internal/app/archied/chat_service.go index 0ff5cc390..981e9b7a2 100644 --- a/internal/app/archied/chat_service.go +++ b/internal/app/archied/chat_service.go @@ -39,12 +39,3 @@ func composeChatContract(settings config.ServiceConnection, local gateway.ChatCo 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/gateway.go b/internal/app/archied/gateway.go index afaccc67c..fff023eaf 100644 --- a/internal/app/archied/gateway.go +++ b/internal/app/archied/gateway.go @@ -2,102 +2,111 @@ package archied import ( "context" - "flag" "fmt" "net" "os" - "os/signal" - "syscall" + "time" + natsio "github.com/nats-io/nats.go" "google.golang.org/grpc" + "github.com/samcharles93/archie-core/internal/events" + "github.com/samcharles93/archie-core/internal/gateway" "github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc" + "github.com/samcharles93/archie-core/internal/infrastructure/taskactions" + "github.com/samcharles93/archie-core/internal/plugin" ) -// RunGateway starts the standalone Gateway Service. The service owns the -// conversation store and the Gateway composition; the daemon reaches it only -// through the generated ChatContract RPC. -func RunGateway() int { - args := gatewayArgs() - if args.version { - fmt.Printf("archie-gateway %s\n", gatewayVersion) - return 0 - } - - root, cancel := context.WithCancel(context.Background()) - defer cancel() - ctx, stop := signal.NotifyContext(root, os.Interrupt, syscall.SIGTERM) - defer stop() +// GatewayOptions contains process inputs for the standalone Gateway. +type GatewayOptions struct { + Config string + Overlay string + Listen string +} +// RunGateway owns conversation persistence, model runtime and tool-provider +// lifecycles. Task-store adapters continue to access the existing task database +// until the State Store Service extraction; no task data is relocated. +func RunGateway(ctx context.Context, options GatewayOptions) error { b := newBootstrap() - if err := b.loadConfig(ctx, args.config, args.overlay, false); err != nil { - return 1 - } defer b.cleanup() + if err := b.loadConfig(ctx, options.Config, options.Overlay, false); err != nil { + return err + } + b.log = b.log.With("component", "gateway") if err := b.openStores(ctx); err != nil { - return 1 + return err } - b.loadCatalog(ctx, args.config) - // setupLLMAndChat also wires the task adapters used by Gateway tools. It - // normally publishes a dashboard contract, but the standalone service - // publishes that same local adapter over gRPC below. - b.setupObservability() - b.cfg.Services.Gateway.Mode = "inproc" - b.cfg.Services.Gateway.Target = "" - b.setupLLMAndChat(ctx) - if b.web == nil || b.web.Chat == nil || b.web.Chat.Contract == nil { - b.log.Error("gateway contract was not composed") - return 1 + b.loadCatalog(ctx, options.Config) + if b.cfg.NATS.URL == "" { + return fmt.Errorf("archie-gateway requires nats.url pointing to the daemon's shared NATS server") } - - listener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", args.listen) + token, err := configuredNATSToken(b.cfg.NATS, os.Getenv) if err != nil { - b.log.Error("listen for gateway", "addr", args.listen, "err", err) - return 1 + return err + } + nc, err := natsio.Connect(b.cfg.NATS.URL, natsio.Token(token)) + if err != nil { + return fmt.Errorf("connect gateway task actions: %w", err) + } + b.addCleanup(nc.Close) + contract, err := b.startGatewayRuntime(ctx, taskactions.Client{Conn: nc, Timeout: 30 * time.Second}) + if err != nil { + return err + } + host, _, err := net.SplitHostPort(options.Listen) + if err != nil || !net.ParseIP(host).IsLoopback() { + return fmt.Errorf("gateway listen address must use a loopback IP; use a secured tunnel for remote access") + } + listener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", options.Listen) + if err != nil { + return fmt.Errorf("listen for gateway: %w", err) } defer listener.Close() + b.log.Info("archie-gateway running", "addr", listener.Addr().String()) + return serveGateway(ctx, listener, contract) +} + +func (b *boot) startGatewayRuntime(ctx context.Context, actor gateway.ChatTaskActor) (gateway.ChatContract, error) { + b.bus = events.NewBus() + b.addCleanup(b.bus.Close) + b.capabilityHost = plugin.NewHost() + contract := b.setupGatewayChat(ctx, actor) + // Memory is opened with its own long-lived context inside (matching the + // daemon path via setupMemoryAll): shutdown of the file-backed provider + // outlives the boot context by design, so the legacy manager wires itself + // with a background context rather than the gateway's boot ctx. + if err := b.setupMemory(); err != nil { //nolint:contextcheck // setupMemory owns its lifecycle contexts, matching the daemon's setupMemoryAll + return nil, err + } + if err := b.registerTools(); err != nil { + return nil, err + } + b.registerStandaloneTools() + b.addCleanup(shutdownCapabilityHost(b.capabilityHost, b.log)) + if err := b.capabilityHost.Start(ctx); err != nil { + return nil, fmt.Errorf("start gateway tool providers: %w", err) + } + for _, skipped := range b.providerRegistry.Skipped() { + b.log.Warn("gateway tool provider unavailable", "provider", skipped.ID, "err", skipped.Err) + } + return contract, nil +} + +func serveGateway(ctx context.Context, listener net.Listener, contract gateway.ChatContract) error { server := grpc.NewServer() - gatewayrpc.RegisterServer(server, b.web.Chat.Contract) + gatewayrpc.RegisterServer(server, contract) serveErr := make(chan error, 1) go func() { serveErr <- server.Serve(listener) }() - b.log.Info("archie-gateway running", "addr", listener.Addr().String()) - select { case <-ctx.Done(): + // A client can keep a streaming RPC open indefinitely. Allow draining, + // then force cancellation before closing the session store and tools. + timer := time.AfterFunc(10*time.Second, server.Stop) server.GracefulStop() - return 0 + timer.Stop() + return nil case err := <-serveErr: - if err != nil { - b.log.Error("gateway server stopped", "err", err) - return 1 - } - return 0 + return err } } - -type gatewayRunArgs struct { - config string - overlay string - listen string - version bool -} - -func gatewayArgs() gatewayRunArgs { - args := gatewayRunArgs{config: filepathConfigHome()} - flag.StringVar(&args.config, "config", args.config, "path to a TOML/YAML config file or configuration directory") - flag.StringVar(&args.overlay, "config-overlay", "", "path to a TOML/YAML overlay file or configuration directory") - flag.StringVar(&args.listen, "listen", "127.0.0.1:8585", "gateway gRPC listen address") - flag.BoolVar(&args.version, "version", false, "print the Gateway Service version and exit") - flag.Parse() - return args -} - -func filepathConfigHome() string { - base := os.Getenv("XDG_CONFIG_HOME") - if base == "" { - if home, err := os.UserHomeDir(); err == nil { - base = home + "/.config" - } - } - return base + "/archie/config.toml" -} diff --git a/internal/app/archied/gateway_runtime.go b/internal/app/archied/gateway_runtime.go new file mode 100644 index 000000000..bc591687c --- /dev/null +++ b/internal/app/archied/gateway_runtime.go @@ -0,0 +1,77 @@ +package archied + +import ( + "context" + "fmt" + + "github.com/samcharles93/archie-core/internal/agentexec" + "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/gateway" + "github.com/samcharles93/archie-core/internal/tools" +) + +// setupChatRuntime wires the model runtime, tool registry, persona registry, +// chat task creator/controller, default chat identity and the release-update +// service. Both the daemon (its own Telegram/email routers) and the standalone +// Gateway (the web router) build through this one constructor so the two +// processes cannot diverge. +func (b *boot) setupChatRuntime(cfg config.Config) { + // ── LLM runtime ────────────────────────────────────────────────── + // Created before gateways so the LLMResponder can be wired into the + // Telegram router for non-command message processing. + providers := executionProviders(cfg) + b.llm = agentexec.NewRuntime(providers) + b.toolReg = tools.NewRegistry() + chatModels := newChatModelManager(cfg.Models, cfg.Chat.Models, b.catalogModels) + chatModels.ApplyModelCatalog(b.catalog) + b.chatModels = chatModels + + // ── Persona registry ───────────────────────────────────────────── + b.personas = gateway.NewPersonaRegistry(gateway.DefaultPersonas()) + + profiles, defaultChatIdentity := chatTaskProfiles(cfg) + var chatTasks gateway.TaskCreator + if len(profiles) > 0 { + chatTasks = gateway.NewStoreTaskCreatorForProfiles( + chatTaskWriterAdapter{enqueue: b.st.EnqueueChatTask}, + profiles, + ) + } + b.chatTasks = chatTasks + b.defaultChatIdentity = defaultChatIdentity + b.chatController = gateway.NewStoreTaskController(chatTaskControllerAdapter{ + taskByID: b.st.TaskByID, + requeue: b.st.Requeue, + transition: b.st.Transition, + }) + b.updateService = makeUpdateService(telegramSetup{Cfg: config.NewHolder(cfg)}) +} + +// setupGatewayChat is the sole production constructor of the local contract. +// Frontends use its gRPC representation; only this service owns the router. +func (b *boot) setupGatewayChat(ctx context.Context, actor gateway.ChatTaskActor) gateway.ChatContract { + b.setupChatRuntime(b.cfg) + cfg := b.cfg + router := gateway.NewRouter(b.st, nil, "web") + router.Version = fmt.Sprintf("Archie\nGateway: %s\nRuntime: %s", gatewayVersion, runtimeVersion) + router.Models = b.chatModels + router.Personas = b.personas + router.Updates = b.updateService + router.InitSessions(b.chatSessionStore) + configureTaskCommands(router, b.chatTasks, b.chatController, chatTaskListerAdapter{tasks: b.st.Tasks}, b.defaultChatIdentity) + setup := telegramSetup{ + Cfg: config.NewHolder(cfg), St: b.st, LLM: b.llm, ChatModels: b.chatModels, ToolReg: b.toolReg, + Personas: b.personas, ChatTasks: b.chatTasks, ChatController: b.chatController, + ChatTaskLister: chatTaskListerAdapter{tasks: b.st.Tasks}, + ChatTaskLogs: chatTaskLogReaderAdapter{tasks: b.st.TaskByID, taskLogs: b.taskLogs}, + ChatTaskActor: actor, DefaultChatIdentity: b.defaultChatIdentity, SessionStore: b.chatSessionStore, + Bus: b.bus, Log: b.log, Secrets: b.secrets, + } + router.LLM, router.LLMStream = makeChatLLMResponder(ctx, "web", setup, b.chatSessionStore, router) + router.Titles = newChatTitleGenerator(setup) + router.Log = b.log + return &gateway.LocalChatAdapter{ + Router: router, Sessions: b.chatSessionStore, Turns: gateway.NewTurns(b.log), + Models: b.chatModels, Personas: b.personas, TaskActor: actor, + } +} diff --git a/internal/app/archied/main.go b/internal/app/archied/main.go index 1ef46337e..7195ceb55 100644 --- a/internal/app/archied/main.go +++ b/internal/app/archied/main.go @@ -5,7 +5,6 @@ package archied import ( - "bytes" "context" "crypto/sha256" "encoding/json" @@ -13,8 +12,6 @@ import ( "fmt" "log/slog" "net" - "net/http" - "net/http/httptest" "os" "os/signal" "path/filepath" @@ -353,7 +350,7 @@ func parseArgs() (runArgs, bool) { return args, false } -func Run() int { +func Run() int { //nolint:cyclop // the composition root's setup sequence is deliberately flat and sequential args, exit := parseArgs() if exit { return 0 @@ -392,7 +389,9 @@ func Run() int { return 1 } - b.setupLLMAndChat(ctx) + if err := b.setupLLMAndChat(ctx); err != nil { + return 1 + } if !b.setupGateways(ctx, args.cfgPath, args.overlayPath) { return 1 } @@ -660,118 +659,18 @@ func (a chatTaskLogReaderAdapter) ReadChatTaskLogs( }, nil } -// chatTaskActorAdapter executes operator actions on a task via the same -// action path the dashboard uses, ensuring chat and webui cannot diverge. -// It enforces identity scoping so an identity cannot mutate another -// identity's tasks. +// chatTaskActorAdapter sends messaging actions through the Gateway boundary. type chatTaskActorAdapter struct { - tasks func(context.Context, int64) (*store.Task, error) - apply func(context.Context, string, int64, taskstate.Action) (gateway.TaskActionResult, error) contract gateway.ChatContract - handler http.Handler - token func() string -} - -func applyGatewayTaskAction(st store.TaskStore) func(context.Context, string, int64, taskstate.Action) (gateway.TaskActionResult, error) { - return func(ctx context.Context, identity string, taskID int64, action taskstate.Action) (gateway.TaskActionResult, error) { - task, err := st.TaskByID(ctx, taskID) - if err != nil { - return gateway.TaskActionResult{}, err - } - if task == nil { - return gateway.TaskActionResult{}, fmt.Errorf("task %d not found", taskID) - } - if task.Identity != identity { - return gateway.TaskActionResult{}, fmt.Errorf("task %d belongs to %q, not %q", taskID, task.Identity, identity) - } - if err := taskstate.CheckAction(task.Status, action); err != nil { - return gateway.TaskActionResult{}, err - } - switch action { - case taskstate.ActionApprove: - err = st.Requeue(ctx, taskID, store.StatusWaitingHuman, "implement") - case taskstate.ActionRetry: - err = st.RetryTask(ctx, taskID, store.StatusParked, task.Workflow) - case taskstate.ActionCancel, taskstate.ActionReject: - err = st.Transition(ctx, taskID, task.Status, store.StatusClosedWontDo, "declined by "+identity) - case taskstate.ActionAbandon: - err = st.Transition(ctx, taskID, store.StatusParked, store.StatusClosedWontDo, "abandoned by "+identity) - case taskstate.ActionStop: - return gateway.TaskActionResult{}, fmt.Errorf("stopping running tasks is unavailable in the Gateway Service") - case taskstate.ActionArchive: - _, err = st.ArchiveTask(ctx, taskID, task.Status, events.Event{Kind: events.KindTaskArchiveRequested, TaskID: taskID}) - default: - return gateway.TaskActionResult{}, fmt.Errorf("unsupported task action %q", action) - } - if err != nil { - return gateway.TaskActionResult{}, err - } - return gateway.TaskActionResult{TaskID: taskID, Action: string(action), Message: fmt.Sprintf("Applied %s to task %d.", action, taskID)}, nil - } } func (a chatTaskActorAdapter) ApplyChatTaskAction( ctx context.Context, identity string, taskID int64, action taskstate.Action, ) (gateway.TaskActionResult, error) { - if a.contract != nil { - return a.contract.ApplyTaskAction(ctx, identity, taskID, action) + if a.contract == nil { + return gateway.TaskActionResult{}, gateway.ErrChatCapabilityUnavailable } - if a.apply != nil { - return a.apply(ctx, identity, taskID, action) - } - if a.tasks == nil || a.handler == nil { - return gateway.TaskActionResult{}, fmt.Errorf("task actions are not configured") - } - task, err := a.tasks(ctx, taskID) - if err != nil { - return gateway.TaskActionResult{}, err - } - if task == nil { - return gateway.TaskActionResult{}, fmt.Errorf("task %d not found", taskID) - } - // Match the filter chatTaskListerAdapter and chatTaskLogReaderAdapter apply: - // a model bound to one identity must not mutate another identity's tasks, - // and tasks with no identity (forge-sourced) are not actionable through a - // chat tool at all — they belong to the daemon, not a particular identity. - if task.Identity != identity { - return gateway.TaskActionResult{}, fmt.Errorf("task %d belongs to %q, not %q", taskID, task.Identity, identity) - } - if err := taskstate.CheckAction(task.Status, action); err != nil { - return gateway.TaskActionResult{}, err - } - - body, err := json.Marshal(map[string]any{"action": string(action)}) - if err != nil { - return gateway.TaskActionResult{}, fmt.Errorf("marshal action request: %w", err) - } - req := httptest.NewRequestWithContext( - ctx, http.MethodPost, - fmt.Sprintf("/api/tasks/%d/action", taskID), - bytes.NewReader(body), - ) - req.Header.Set("Content-Type", "application/json") - req.Header.Set("X-Archie-CSRF", "1") - if a.token != nil { - if tok := a.token(); tok != "" { - req.Header.Set("Authorization", "Bearer "+tok) - } - } - rec := httptest.NewRecorder() - a.handler.ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - errMsg := strings.TrimSpace(rec.Body.String()) - if errMsg == "" { - errMsg = fmt.Sprintf("HTTP %d", rec.Code) - } - return gateway.TaskActionResult{}, fmt.Errorf("action %s on task %d failed: %s", action, taskID, errMsg) - } - - return gateway.TaskActionResult{ - TaskID: taskID, - Action: string(action), - Message: fmt.Sprintf("Applied %s to task %d.", action, taskID), - }, nil + return a.contract.ApplyTaskAction(ctx, identity, taskID, action) } func chatTaskProfiles(cfg config.Config) ([]gateway.TaskProfile, string) { diff --git a/internal/app/archied/task_action_adapter_test.go b/internal/app/archied/task_action_adapter_test.go index 4078c73e5..78cd64a31 100644 --- a/internal/app/archied/task_action_adapter_test.go +++ b/internal/app/archied/task_action_adapter_test.go @@ -2,16 +2,30 @@ package archied import ( "context" + "log/slog" "path/filepath" "strings" "testing" "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/gateway" "github.com/samcharles93/archie-core/internal/store" "github.com/samcharles93/archie-core/internal/taskstate" - "github.com/samcharles93/archie-core/internal/webui" ) +// newChatTaskActorForTest wires the same production chain the daemon uses in +// default (in-process) mode: chatTaskActorAdapter → LocalChatAdapter → +// taskActionsActor → taskactions.Service over the given store. +func newChatTaskActorForTest(t *testing.T, st store.TaskStore, cfg config.Config) chatTaskActorAdapter { + t.Helper() + b := &boot{ + st: st, + cfg: cfg, + log: slog.Default(), + } + return chatTaskActorAdapter{contract: &gateway.LocalChatAdapter{TaskActor: taskActionsActor{b}}} +} + func TestChatTaskActorAdapterCrossIdentityRefused(t *testing.T) { ctx := context.Background() st, err := store.Open(ctx, filepath.Join(t.TempDir(), "tasks.db")) @@ -28,12 +42,7 @@ func TestChatTaskActorAdapterCrossIdentityRefused(t *testing.T) { t.Fatal(err) } - srv := &webui.Server{Store: st, Cfg: config.NewHolder(config.Config{})} - adapter := chatTaskActorAdapter{ - tasks: st.TaskByID, - handler: srv.Handler(), - token: func() string { return srv.Token }, - } + adapter := newChatTaskActorForTest(t, st, config.Config{}) tests := []struct { name string @@ -88,12 +97,7 @@ func TestChatTaskActorAdapterRefusesDisallowedStateAction(t *testing.T) { } t.Cleanup(func() { _ = st.Close() }) - srv := &webui.Server{Store: st, Cfg: config.NewHolder(config.Config{})} - adapter := chatTaskActorAdapter{ - tasks: st.TaskByID, - handler: srv.Handler(), - token: func() string { return srv.Token }, - } + adapter := newChatTaskActorForTest(t, st, config.Config{}) tests := []struct { name string @@ -170,12 +174,7 @@ func TestChatTaskActorAdapterTaskNotFound(t *testing.T) { } t.Cleanup(func() { _ = st.Close() }) - srv := &webui.Server{Store: st, Cfg: config.NewHolder(config.Config{})} - adapter := chatTaskActorAdapter{ - tasks: st.TaskByID, - handler: srv.Handler(), - token: func() string { return srv.Token }, - } + adapter := newChatTaskActorForTest(t, st, config.Config{}) _, err = adapter.ApplyChatTaskAction(ctx, "archie", 999999, taskstate.ActionAbandon) if err == nil { @@ -247,12 +246,7 @@ func TestChatTaskActorAdapterAppliesActionsToStore(t *testing.T) { } t.Cleanup(func() { _ = st.Close() }) - srv := &webui.Server{Store: st, Cfg: config.NewHolder(config.Config{MaxRetries: 3})} - adapter := chatTaskActorAdapter{ - tasks: st.TaskByID, - handler: srv.Handler(), - token: func() string { return srv.Token }, - } + adapter := newChatTaskActorForTest(t, st, config.Config{MaxRetries: 3}) task, err := st.EnqueueChatTask(ctx, "acme", "widget", "actionable task", "", "", "archie") if err != nil { @@ -295,46 +289,12 @@ func TestChatTaskActorAdapterAppliesActionsToStore(t *testing.T) { } } -func TestChatTaskActorAdapterWithTokenAuth(t *testing.T) { +func TestChatTaskActorAdapterNilContract(t *testing.T) { ctx := context.Background() - st, err := store.Open(ctx, filepath.Join(t.TempDir(), "tasks.db")) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { _ = st.Close() }) + adapter := chatTaskActorAdapter{contract: nil} - srv := &webui.Server{ - Store: st, - Cfg: config.NewHolder(config.Config{MaxRetries: 3}), - Token: "secret-token-12345", - } - adapter := chatTaskActorAdapter{ - tasks: st.TaskByID, - handler: srv.Handler(), - token: func() string { return srv.Token }, - } - - task, err := st.EnqueueChatTask(ctx, "acme", "widget", "auth task", "", "", "archie") - if err != nil { - t.Fatal(err) - } - if err := st.Transition(ctx, task.ID, store.StatusQueued, store.StatusParked, "park"); err != nil { - t.Fatal(err) - } - - result, err := adapter.ApplyChatTaskAction(ctx, "archie", task.ID, taskstate.ActionAbandon) - if err != nil { - t.Fatalf("ApplyChatTaskAction with token auth failed: %v", err) - } - if result.TaskID != task.ID { - t.Errorf("result.TaskID = %d, want %d", result.TaskID, task.ID) - } - - current, err := st.TaskByID(ctx, task.ID) - if err != nil || current == nil { - t.Fatalf("TaskByID = (%+v, %v)", current, err) - } - if current.Status != store.StatusClosedWontDo { - t.Errorf("status = %q, want %q", current.Status, store.StatusClosedWontDo) + _, err := adapter.ApplyChatTaskAction(ctx, "archie", 1, taskstate.ActionAbandon) + if err == nil { + t.Fatal("expected error for nil contract, got nil") } } diff --git a/internal/app/archied/task_actions.go b/internal/app/archied/task_actions.go new file mode 100644 index 000000000..fe4e55ee0 --- /dev/null +++ b/internal/app/archied/task_actions.go @@ -0,0 +1,78 @@ +package archied + +import ( + "context" + "fmt" + + "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/domain/taskactions" + "github.com/samcharles93/archie-core/internal/events" + "github.com/samcharles93/archie-core/internal/gateway" + taskactionstore "github.com/samcharles93/archie-core/internal/infrastructure/taskactions" + "github.com/samcharles93/archie-core/internal/taskstate" +) + +// taskActionsActor applies operator actions in-process for the daemon's own +// local gateway. It is the identity-scoping implementation behind the +// ChatContract's ApplyTaskAction when the daemon is the Gateway (default +// mode). The standalone Gateway instead forwards over NATS with +// taskactions.Client; both paths converge on the one taskactions.Service. +type taskActionsActor struct { + b *boot +} + +func (a taskActionsActor) ApplyChatTaskAction( + ctx context.Context, identity string, taskID int64, action taskstate.Action, +) (gateway.TaskActionResult, error) { + if err := a.b.taskActions().Apply(ctx, &identity, taskID, action); err != nil { + return gateway.TaskActionResult{}, err + } + return gateway.TaskActionResult{ + TaskID: taskID, + Action: string(action), + Message: fmt.Sprintf("Applied %s to task %d.", action, taskID), + }, nil +} + +// taskActions assembles the daemon-owned operator action service. The daemon +// retains execution cancellation, retry policy, forge closure and event +// ownership; the dashboard's webui service and the NATS responder both build +// through the same constructor so the surfaces cannot diverge. +func (b *boot) taskActions() taskactions.Service { + return taskactionstore.NewService( + taskactionstore.Store{TaskStore: b.st}, + taskactionstore.MaxRetries(config.NewHolder(b.cfg)), + b.cancelTask, + b.closeIssue, + b.removeTaskLogs, + b.publishEvent, + b.log.Warn, + ) +} + +func (b *boot) cancelTask(id int64) bool { + if b.d == nil { + return false + } + return b.d.CancelTask(id) +} + +func (b *boot) closeIssue(ctx context.Context, owner, repo string, number int, comment string) error { + if b.forgeClient == nil { + return fmt.Errorf("forge is not configured") + } + return b.forgeClient.CloseIssue(ctx, owner, repo, number, comment) +} + +func (b *boot) removeTaskLogs(id int64) error { + if b.taskLogs == nil { + return nil + } + return b.taskLogs.Remove(id) +} + +func (b *boot) publishEvent(e events.Event) { + if b.bus != nil { + b.bus.Publish(e) + } +} diff --git a/internal/domain/taskactions/service.go b/internal/domain/taskactions/service.go new file mode 100644 index 000000000..c28113228 --- /dev/null +++ b/internal/domain/taskactions/service.go @@ -0,0 +1,201 @@ +// Package taskactions owns operator task mutations shared by chat and dashboard. +package taskactions + +import ( + "context" + "errors" + "fmt" + + "github.com/samcharles93/archie-core/internal/events" + "github.com/samcharles93/archie-core/internal/taskstate" +) + +var ( + ErrNotFound = errors.New("task not found") + ErrConflict = errors.New("task action conflict") + ErrUnavailable = errors.New("runtime task control is unavailable") +) + +// Task is the state needed to authorize and apply an operator action. +type Task struct { + ID int64 + Owner, Repo, Identity, Status, Stage, ParkReason string + IssueNumber, RetryCount int + ForgeBacked bool +} + +type Store interface { + TaskByID(context.Context, int64) (*Task, error) + Transition(context.Context, int64, string, string, string) error + Requeue(context.Context, int64, string, string) error + RetryTask(context.Context, int64, string, string) error + ArchiveTask(context.Context, int64, string, events.Event) (int64, error) + InsertEvent(context.Context, events.Event) (int64, error) +} + +// Service runs in the daemon, which owns execution cancellation and events. +type Service struct { + Store Store + MaxRetries func(*Task) int + CancelTask func(int64) bool + CloseIssue func(context.Context, string, string, int, string) error + RemoveLogs func(int64) error + Publish func(events.Event) + Warn func(string, ...any) +} + +// Apply scopes chat requests to an identity. A nil identity denotes an +// authenticated dashboard operator, who may act across identities. +func (s Service) Apply(ctx context.Context, identity *string, id int64, action taskstate.Action) error { + task, err := s.Store.TaskByID(ctx, id) + if err != nil { + return err + } + if task == nil { + return fmt.Errorf("task %d: %w", id, ErrNotFound) + } + if identity != nil && task.Identity != *identity { + return fmt.Errorf("task %d belongs to %q, not %q", id, task.Identity, *identity) + } + if err := taskstate.CheckAction(task.Status, action); err != nil { + return fmt.Errorf("%w: %w", ErrConflict, err) + } + mutation, err := s.apply(ctx, task, identity, action) + if err != nil { + return err + } + if mutation.verb != "" && task.ForgeBacked { + s.closeRejectedIssue(ctx, task, identity, mutation.verb) + } + s.emit(ctx, mutation.event) + return nil +} + +type outcome struct { + event events.Event + verb string +} + +// apply performs the store mutation for one action and returns the event to +// record alongside it. Errors from the store are returned unwrapped: the +// caller maps them to a response, and the rules-level errors (ErrConflict) +// were already checked above. +func (s Service) apply(ctx context.Context, task *Task, identity *string, action taskstate.Action) (outcome, error) { + source := "the dashboard" + if identity != nil { + source = "chat" + } + o := outcome{event: events.Event{TaskID: task.ID, Repo: task.Owner + "/" + task.Repo, Issue: task.IssueNumber}} + switch action { + case taskstate.ActionApprove: + err := s.Store.Requeue(ctx, task.ID, "waiting_human", "implement") + o.event.Kind, o.event.Detail = events.KindHumanApproved, "approved via "+source + return o, err + case taskstate.ActionRetry: + return s.applyRetry(ctx, task, source, o) + case taskstate.ActionStop: + return s.applyStop(ctx, task, source, o) + case taskstate.ActionReject: + o.event.Kind, o.event.Detail, o.verb = events.KindHumanRejected, "rejected via "+source, "rejected" + if task.Status == "running" && s.CancelTask != nil { + s.CancelTask(task.ID) + } + return o, s.Store.Transition(ctx, task.ID, task.Status, "closed_wont_do", "declined from "+source) + case taskstate.ActionCancel, taskstate.ActionAbandon: + return s.applyCancelOrAbandon(ctx, task, action, source, o) + case taskstate.ActionArchive: + return s.applyArchive(ctx, task, source, o) + default: + return o, fmt.Errorf("unsupported task action %q", action) + } +} + +func (s Service) applyRetry(ctx context.Context, task *Task, source string, o outcome) (outcome, error) { + limit := 0 + if s.MaxRetries != nil { + limit = s.MaxRetries(task) + } + if limit > 0 && task.RetryCount >= limit { + reason := fmt.Sprintf("max retries reached (%d/%d)", task.RetryCount, limit) + if err := s.Store.Transition(ctx, task.ID, "parked", "dead", reason); err != nil { + s.warn("transition to dead failed", "task", task.ID, "err", err) + } else { + o.event.Kind, o.event.Detail = events.KindTaskDead, reason + s.emit(ctx, o.event) + } + return o, fmt.Errorf("%w: %s", ErrConflict, reason) + } + err := s.Store.RetryTask(ctx, task.ID, "parked", "") + o.event.Kind, o.event.Detail = events.KindTaskRetried, "retried via "+source + o.event.Data = map[string]any{"retry_count": task.RetryCount + 1, "previous_stage": task.Stage, "previous_reason": task.ParkReason} + return o, err +} + +func (s Service) applyStop(ctx context.Context, task *Task, source string, o outcome) (outcome, error) { + if s.CancelTask == nil { + return o, ErrUnavailable + } + o.event.Kind, o.event.Detail = events.KindTaskStopped, "stopped via "+source+"; recoverable work remains parked" + if !s.CancelTask(task.ID) { + o.event.Detail = "no active execution was found; recoverable work was parked via " + source + } + return o, s.Store.Transition(ctx, task.ID, "running", "parked", o.event.Detail) +} + +func (s Service) applyCancelOrAbandon(ctx context.Context, task *Task, action taskstate.Action, source string, o outcome) (outcome, error) { + from, kind, verb := "queued", events.KindTaskCancelled, "cancelled" + if action == taskstate.ActionAbandon { + from, kind, verb = "parked", events.KindTaskAbandoned, "abandoned" + } + o.event.Kind, o.event.Detail, o.verb = kind, verb+" via "+source, verb + return o, s.Store.Transition(ctx, task.ID, from, "closed_wont_do", o.event.Detail) +} + +func (s Service) applyArchive(ctx context.Context, task *Task, source string, o outcome) (outcome, error) { + o.event.Kind, o.event.Detail = events.KindTaskArchiveRequested, "archive requested via "+source + id, err := s.Store.ArchiveTask(ctx, task.ID, task.Status, o.event) + if err != nil { + return o, err + } + o.event.ID = id + if s.RemoveLogs != nil { + if cleanupErr := s.RemoveLogs(task.ID); cleanupErr != nil { + s.warn("task log cleanup failed", "task", task.ID, "err", cleanupErr) + } + } + return o, nil +} + +func (s Service) closeRejectedIssue(ctx context.Context, task *Task, identity *string, verb string) { + if s.CloseIssue == nil { + s.warn("task rejected but no forge is wired; the issue stays open and will be re-polled", "task", task.ID) + return + } + comment := fmt.Sprintf("Closing: this task was %s from the archie %s. Reopen the issue to have archie pick it up again.", verb, "dashboard") + if identity != nil { + comment = fmt.Sprintf("Closing: this task was %s from archie chat. Reopen the issue to have archie pick it up again.", verb) + } + if err := s.CloseIssue(ctx, task.Owner, task.Repo, task.IssueNumber, comment); err != nil { + s.warn("closing rejected issue failed; it stays open and will be re-polled", "task", task.ID, "err", err) + } +} + +func (s Service) emit(ctx context.Context, e events.Event) { + if e.ID == 0 { + id, err := s.Store.InsertEvent(ctx, e) + if err != nil { + s.warn("operator activity persistence failed", "kind", e.Kind, "task", e.TaskID, "err", err) + } else { + e.ID = id + } + } + if s.Publish != nil { + s.Publish(e) + } +} + +func (s Service) warn(msg string, args ...any) { + if s.Warn != nil { + s.Warn(msg, args...) + } +} diff --git a/internal/infrastructure/taskactions/rpc.go b/internal/infrastructure/taskactions/rpc.go new file mode 100644 index 000000000..b4208be42 --- /dev/null +++ b/internal/infrastructure/taskactions/rpc.go @@ -0,0 +1,77 @@ +package taskactions + +import ( + "context" + "encoding/json" + "fmt" + "log/slog" + "time" + + "github.com/nats-io/nats.go" + + "github.com/samcharles93/archie-core/internal/domain/taskactions" + "github.com/samcharles93/archie-core/internal/gateway" + "github.com/samcharles93/archie-core/internal/natsrpc" + "github.com/samcharles93/archie-core/internal/taskstate" +) + +// actionSubject is the request/reply subject the Gateway's ChatTaskActor +// client issues and the daemon's responder serves. The daemon owns task +// execution; the standalone Gateway never mutates the task store directly. +const actionSubject = "archie.gateway.task-action" + +type actionRequest struct { + Identity string `json:"identity"` + TaskID int64 `json:"task_id"` + Action taskstate.Action `json:"action"` +} + +type actionResponse struct { + natsrpc.Envelope +} + +// Register exposes only identity-scoped operator actions on the daemon. The +// daemon retains execution cancellation, retry policy, forge closure and event +// ownership; the Gateway's client reaches this responder over NATS. +// Handlers run with context.Background() (the storerpc convention): the +// daemon's lifecycle ctx is not request-scoped, and a cancelled boot ctx must +// not poison later requests. +func Register(nc *nats.Conn, service taskactions.Service, log *slog.Logger) (func(), error) { + return natsrpc.RegisterAll(nc, []natsrpc.Registration{{ + Subject: actionSubject, + Handler: func(msg *nats.Msg) { + var req actionRequest + if err := json.Unmarshal(msg.Data, &req); err != nil { + natsrpc.Respond(msg, log, "taskactions", actionResponse{Envelope: natsrpc.NewEnvelope(err)}) + return + } + err := service.Apply(context.Background(), &req.Identity, req.TaskID, req.Action) + natsrpc.Respond(msg, log, "taskactions", actionResponse{Envelope: natsrpc.NewEnvelope(err)}) + }, + }}) +} + +// Client forwards Gateway task actions to their daemon owner over NATS. +type Client struct { + Conn *nats.Conn + Timeout time.Duration // bounds each call when ctx has no deadline +} + +func (c Client) rpc() *natsrpc.Client { + return &natsrpc.Client{Conn: c.Conn, Timeout: c.Timeout} +} + +// ApplyChatTaskAction sends an operator action to the daemon's responder. +func (c Client) ApplyChatTaskAction(ctx context.Context, identity string, id int64, action taskstate.Action) (gateway.TaskActionResult, error) { + if c.Conn == nil { + return gateway.TaskActionResult{}, fmt.Errorf("task action connection is unavailable") + } + resp, err := natsrpc.Call[actionResponse](ctx, c.rpc(), actionSubject, actionRequest{Identity: identity, TaskID: id, Action: action}) + if err != nil { + return gateway.TaskActionResult{}, err + } + if err := resp.Err(); err != nil { + return gateway.TaskActionResult{}, err + } + return gateway.TaskActionResult{TaskID: id, Action: string(action), Message: fmt.Sprintf("Applied %s to task %d.", action, id)}, nil +} diff --git a/internal/infrastructure/taskactions/service.go b/internal/infrastructure/taskactions/service.go new file mode 100644 index 000000000..e9e387456 --- /dev/null +++ b/internal/infrastructure/taskactions/service.go @@ -0,0 +1,32 @@ +package taskactions + +import ( + "context" + + "github.com/samcharles93/archie-core/internal/domain/taskactions" + "github.com/samcharles93/archie-core/internal/events" +) + +// NewService assembles the operator task-action service from its production +// dependencies. Both the dashboard's in-process service (webui) and the +// daemon's NATS responder build through this one constructor so the two +// surfaces cannot diverge. +func NewService( + store taskactions.Store, + maxRetries func(*taskactions.Task) int, + cancel func(int64) bool, + closeIssue func(context.Context, string, string, int, string) error, + removeLogs func(int64) error, + publish func(events.Event), + warn func(string, ...any), +) taskactions.Service { + return taskactions.Service{ + Store: store, + MaxRetries: maxRetries, + CancelTask: cancel, + CloseIssue: closeIssue, + RemoveLogs: removeLogs, + Publish: publish, + Warn: warn, + } +} diff --git a/internal/infrastructure/taskactions/store.go b/internal/infrastructure/taskactions/store.go new file mode 100644 index 000000000..77b8afa8a --- /dev/null +++ b/internal/infrastructure/taskactions/store.go @@ -0,0 +1,35 @@ +// Package taskactions adapts legacy task persistence to operator actions. +package taskactions + +import ( + "context" + + "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/domain/taskactions" + "github.com/samcharles93/archie-core/internal/store" +) + +type Store struct{ store.TaskStore } + +func (s Store) TaskByID(ctx context.Context, id int64) (*taskactions.Task, error) { + t, err := s.TaskStore.TaskByID(ctx, id) + if err != nil || t == nil { + return nil, err + } + return &taskactions.Task{ID: t.ID, Owner: t.Owner, Repo: t.Repo, Identity: t.Identity, Status: t.Status, Stage: t.Stage, ParkReason: t.ParkReason, IssueNumber: t.IssueNumber, RetryCount: t.RetryCount, ForgeBacked: t.IsForgeBacked()}, nil +} + +func MaxRetries(cfg *config.Holder) func(*taskactions.Task) int { + return func(t *taskactions.Task) int { + if cfg == nil { + return 0 + } + c := cfg.Get() + for _, repo := range c.Repos { + if repo.Owner == t.Owner && repo.Name == t.Repo { + return repo.EffectiveMaxRetries(c.MaxRetries) + } + } + return c.MaxRetries + } +} diff --git a/internal/webui/api_tasks.go b/internal/webui/api_tasks.go index b45bb8f38..e11e5fb73 100644 --- a/internal/webui/api_tasks.go +++ b/internal/webui/api_tasks.go @@ -4,7 +4,6 @@ import ( "context" "encoding/json" "errors" - "fmt" "io" "mime" "net/http" @@ -13,7 +12,9 @@ import ( "strings" "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/domain/taskactions" "github.com/samcharles93/archie-core/internal/events" + taskactionstore "github.com/samcharles93/archie-core/internal/infrastructure/taskactions" "github.com/samcharles93/archie-core/internal/store" "github.com/samcharles93/archie-core/internal/taskstate" ) @@ -146,36 +147,20 @@ func (s *Server) handleTaskAction(w http.ResponseWriter, r *http.Request) { if !ok { return } - task, err := s.Store.TaskByID(r.Context(), id) - if err != nil { - s.logf("task action lookup failed", "task", id, "err", err) - http.Error(w, "task action failed", http.StatusInternalServerError) + if err := s.TaskActionService().Apply(r.Context(), nil, id, action); err != nil { + switch { + case errors.Is(err, taskactions.ErrNotFound): + http.Error(w, "task not found", http.StatusNotFound) + case errors.Is(err, taskactions.ErrConflict), errors.Is(err, store.ErrStaleTransition): + http.Error(w, err.Error(), http.StatusConflict) + case errors.Is(err, taskactions.ErrUnavailable): + http.Error(w, err.Error(), http.StatusServiceUnavailable) + default: + s.logf("task action failed", "task", id, "err", err) + http.Error(w, "task action failed", http.StatusInternalServerError) + } return } - if task == nil { - http.Error(w, "task not found", http.StatusNotFound) - return - } - if err := taskstate.CheckAction(task.Status, action); err != nil { - http.Error(w, err.Error(), http.StatusConflict) - return - } - - // Each action reports the event to record, or writes its own error - // response and returns nothing. Keeping the dispatch flat here and the - // rules in one function each is what stops this growing back into a - // single branch nobody can read. - outcome := s.applyTaskAction(r.Context(), w, task, action) - if outcome == nil { - return - } - - s.emit(r.Context(), events.Event{ - ID: outcome.eventID, - Kind: outcome.kind, TaskID: task.ID, - Repo: task.Owner + "/" + task.Repo, Issue: task.IssueNumber, - Detail: outcome.detail, Data: outcome.data, - }) writeJSON(w, map[string]any{"ok": true, "action": action, "task_id": id}) } @@ -204,32 +189,6 @@ func decodeTaskAction(w http.ResponseWriter, r *http.Request) (taskstate.Action, return action, true } -func (s *Server) applyTaskAction( - ctx context.Context, - w http.ResponseWriter, - task *store.Task, - action taskstate.Action, -) *actionOutcome { - switch action { - case taskstate.ActionCancel: - return s.declineTask(ctx, w, task, store.StatusQueued, events.KindTaskCancelled, "cancelled") - case taskstate.ActionStop: - return s.stopTask(ctx, w, task) - case taskstate.ActionApprove: - return s.approveTask(ctx, w, task) - case taskstate.ActionRetry: - return s.retryTask(ctx, w, task) - case taskstate.ActionReject: - return s.rejectTask(ctx, w, task) - case taskstate.ActionAbandon: - return s.declineTask(ctx, w, task, store.StatusParked, events.KindTaskAbandoned, "abandoned") - case taskstate.ActionArchive: - return s.archiveTask(ctx, w, task) - default: - return nil - } -} - func taskMutation(action taskstate.Action) bool { switch action { case taskstate.ActionCancel, taskstate.ActionStop, taskstate.ActionApprove, @@ -315,205 +274,46 @@ func validOrigin(u *url.URL, wantScheme, wantHost string) bool { return strings.EqualFold(u.Scheme, wantScheme) && strings.EqualFold(u.Host, wantHost) } -// actionOutcome is what a completed operator action should record. -type actionOutcome struct { - kind string - detail string - data map[string]any - eventID int64 +// TaskActionService supplies the same operator action implementation used by +// the daemon's task-control endpoint. +func (s *Server) TaskActionService() taskactions.Service { + return taskactionstore.NewService( + taskactionstore.Store{TaskStore: s.Store}, + taskactionstore.MaxRetries(s.Cfg), + s.taskStopper(), + s.issueCloser(), + s.logRemover(), + s.eventPublisher(), + s.logf, + ) } -// storeFailed writes the response for a failed store write and reports -// whether it did. A store write that fails is not the caller's fault; -// answering 409 made the UI say "conflict" for a broken database. -func (s *Server) storeFailed(w http.ResponseWriter, err error) bool { - if err == nil { - return false - } - if errors.Is(err, store.ErrStaleTransition) { - http.Error(w, "task changed state; refresh and try again", http.StatusConflict) - return true - } - s.logf("task action store write failed", "err", err) - http.Error(w, "task action failed", http.StatusInternalServerError) - return true -} - -func (s *Server) declineTask( - ctx context.Context, - w http.ResponseWriter, - task *store.Task, - from, kind, verb string, -) *actionOutcome { - detail := verb + " via the dashboard" - if s.storeFailed(w, s.Store.Transition(ctx, task.ID, from, store.StatusClosedWontDo, detail)) { - return nil - } - s.closeDeclinedIssue(ctx, task, verb) - return &actionOutcome{kind: kind, detail: detail} -} - -func (s *Server) stopTask(ctx context.Context, w http.ResponseWriter, task *store.Task) *actionOutcome { +func (s *Server) taskStopper() func(int64) bool { if s.TaskStopper == nil { - http.Error(w, "runtime task control is unavailable", http.StatusServiceUnavailable) return nil } - cancelled := s.TaskStopper.CancelTask(task.ID) - detail := "stopped via the dashboard; recoverable work remains parked" - if !cancelled { - // A running row without a runtime entry is stale work from a crashed or - // migrated process. Nothing is executing, but parking the guarded row - // still gives the operator the promised recoverable state. - detail = "no active execution was found; recoverable work was parked via the dashboard" - } - if s.storeFailed(w, s.Store.Transition(ctx, task.ID, store.StatusRunning, store.StatusParked, detail)) { - return nil - } - return &actionOutcome{kind: events.KindTaskStopped, detail: detail} + return s.TaskStopper.CancelTask } -func (s *Server) archiveTask(ctx context.Context, w http.ResponseWriter, task *store.Task) *actionOutcome { - detail := "archive requested via the dashboard" - eventID, err := s.Store.ArchiveTask(ctx, task.ID, task.Status, events.Event{ - Kind: events.KindTaskArchiveRequested, TaskID: task.ID, - Repo: task.Owner + "/" + task.Repo, Issue: task.IssueNumber, - Detail: detail, - }) - if s.storeFailed(w, err) { - return nil - } - // Best-effort: an archived task's log files not getting cleaned up is - // far less costly than the archive action itself failing over it, so - // this never blocks the response the way s.storeFailed above does. - // - // Known, accepted gap: a task reaches a terminal status (satisfying - // ArchiveTask's precondition) partway through Daemon.process, but its - // TaskLogs sink isn't closed until process() itself returns -- which can - // be later, if teardown after the terminal transition takes any time at - // all. A system-log message landing in that window races this Remove - // with an open Write to the same directory. Not corrupting (the write - // lands on a soon-to-be-unlinked inode and is discarded) and not worth - // closing here: doing so would mean tying TaskLogs.Close to the store - // transition instead of to process()'s return, a larger change than - // this call site should make unilaterally. - if err := s.TaskLogs.Remove(task.ID); err != nil { - s.Log.Warn("task log cleanup failed", "task", task.ID, "err", err) - } - return &actionOutcome{kind: events.KindTaskArchiveRequested, detail: detail, eventID: eventID} -} - -func (s *Server) approveTask(ctx context.Context, w http.ResponseWriter, task *store.Task) *actionOutcome { - if err := taskstate.CheckApprove(task.Status); err != nil { - http.Error(w, err.Error(), http.StatusConflict) - return nil - } - if s.storeFailed(w, s.Store.Requeue(ctx, task.ID, store.StatusWaitingHuman, "implement")) { - return nil - } - return &actionOutcome{kind: events.KindHumanApproved, detail: "approved via the dashboard"} -} - -// retryTask requeues a parked task, or retires it once max_retries is spent. -// -// max_retries was configured, defaulted and reported by /api/config while -// nothing enforced it: retry_count climbed forever, so a task that fails -// every time could be retried without limit. At the cap the task belongs in -// dead, which is what the setting exists to say. -func (s *Server) retryTask(ctx context.Context, w http.ResponseWriter, task *store.Task) *actionOutcome { - if err := taskstate.CheckRetry(task.Status); err != nil { - http.Error(w, err.Error(), http.StatusConflict) - return nil - } - if limit := s.maxRetriesFor(task); limit > 0 && task.RetryCount >= limit { - s.retireTask(ctx, task, fmt.Sprintf("max retries reached (%d/%d)", task.RetryCount, limit)) - http.Error(w, fmt.Sprintf("max retries reached (%d/%d)", task.RetryCount, limit), http.StatusConflict) - return nil - } - if s.storeFailed(w, s.Store.RetryTask(ctx, task.ID, store.StatusParked, "")) { - return nil - } - return &actionOutcome{ - kind: events.KindTaskRetried, - detail: "retried via the dashboard", - data: map[string]any{ - "retry_count": task.RetryCount + 1, - "previous_stage": task.Stage, - "previous_reason": task.ParkReason, - }, - } -} - -// retireTask moves a spent task to dead. Failure is logged, not returned: -// the caller is already answering with the reason it refused the retry. -func (s *Server) retireTask(ctx context.Context, task *store.Task, reason string) { - if err := s.Store.Transition(ctx, task.ID, store.StatusParked, store.StatusDead, reason); err != nil { - s.logf("transition to dead failed", "task", task.ID, "err", err) - return - } - s.emit(ctx, events.Event{ - Kind: events.KindTaskDead, TaskID: task.ID, - Repo: task.Owner + "/" + task.Repo, Issue: task.IssueNumber, Detail: reason, - }) -} - -func (s *Server) rejectTask(ctx context.Context, w http.ResponseWriter, task *store.Task) *actionOutcome { - // Reject is available from any non-terminal lifecycle state: work the - // operator refuses belongs in the terminal Declined state regardless of - // where it currently sits. Running work is interrupted first so nothing - // keeps executing against a task that is being closed out. - if task.Status == store.StatusRunning && s.TaskStopper != nil { - s.TaskStopper.CancelTask(task.ID) - } - err := s.Store.Transition(ctx, task.ID, task.Status, store.StatusClosedWontDo, "declined from the dashboard") - if s.storeFailed(w, err) { - return nil - } - s.closeDeclinedIssue(ctx, task, "rejected") - return &actionOutcome{kind: events.KindHumanRejected, detail: "rejected via the dashboard"} -} - -// maxRetriesFor resolves the retry cap for a task, honouring a per-repo -// override. Zero means unlimited. -func (s *Server) maxRetriesFor(task *store.Task) int { - if s.Cfg == nil { - return 0 - } - cfg := s.Cfg.Get() - for _, repo := range cfg.Repos { - if repo.Owner == task.Owner && repo.Name == task.Repo { - return repo.EffectiveMaxRetries(cfg.MaxRetries) - } - } - return cfg.MaxRetries -} - -// closeRejectedIssue closes the forge issue behind a task the operator has -// declined. -// -// Without this the issue stays open, labelled and assigned, so the next poll -// re-enqueues it -- and once the operator uses Clear, which deletes the task -// row, that is a second implementation and a second PR for work already -// refused. Approve and retry deliberately leave the issue open: the task is -// going back to work. -// -// Failure is logged, not returned. The operator's decision is already -// recorded, and reporting an error would invite them to click again. -func (s *Server) closeDeclinedIssue(ctx context.Context, task *store.Task, verb string) { +func (s *Server) issueCloser() func(context.Context, string, string, int, string) error { if s.Issues == nil { - s.logf("task rejected but no forge is wired; the issue stays open and will be re-polled", - "task", task.ID, "issue", task.IssueNumber) - return + return nil } - // A chat task's issue number is synthetic and matches no forge issue. - if !task.IsForgeBacked() { - return + return s.Issues.CloseIssue +} + +func (s *Server) logRemover() func(int64) error { + if s.TaskLogs == nil { + return nil } - comment := fmt.Sprintf("Closing: this task was %s from the archie dashboard. "+ - "Reopen the issue to have archie pick it up again.", verb) - if err := s.Issues.CloseIssue(ctx, task.Owner, task.Repo, task.IssueNumber, comment); err != nil { - s.logf("closing rejected issue failed; it stays open and will be re-polled", - "task", task.ID, "issue", task.IssueNumber, "err", err) + return s.TaskLogs.Remove +} + +func (s *Server) eventPublisher() func(events.Event) { + if s.Events == nil { + return nil } + return s.Events.Publish } // emit publishes an operator action so it reaches the task timeline and the From b319d77c56bf35d85db5f3a5700c1ee3fc491404 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sun, 6 Sep 2026 02:07:02 +1000 Subject: [PATCH 5/6] feat(gateway): delete in-process ChatContract path, make remote the only mode archie-gateway is now the sole owner of ChatContract; the daemon always dials it over gRPC for webui chat, no in-process fallback left. Telegram and email keep their own in-process routers unchanged (their streaming responder is a callback that can't cross the wire-safe contract). - composeChatContract only accepts mode="remote"; config defaults Services.Gateway to remote + 127.0.0.1:8585 when unset - deleted taskActionsActor (dead code once the local branch is gone) - task dev now launches archie-gateway alongside archied + Vite Verified end-to-end: archie-gateway + archied booted against a shared NATS/store, webui's /api/chat/sessions round-tripped through the gRPC hop. --- Taskfile.yml | 21 ++++++---- go.sum | 31 ++++++++++++++ internal/app/archied/bootstrap.go | 26 +++--------- internal/app/archied/chat_service.go | 42 ++++++++----------- internal/app/archied/chat_service_test.go | 28 ++----------- internal/app/archied/main.go | 2 +- .../app/archied/task_action_adapter_test.go | 25 +++++++++-- internal/app/archied/task_actions.go | 24 ----------- .../infrastructure/configuration/defaults.go | 3 +- .../configuration/services_test.go | 20 ++++----- .../infrastructure/configuration/validate.go | 6 +-- .../configuration/validate_test.go | 3 ++ 12 files changed, 108 insertions(+), 123 deletions(-) diff --git a/Taskfile.yml b/Taskfile.yml index 45a6bb9e6..b22de46fb 100644 --- a/Taskfile.yml +++ b/Taskfile.yml @@ -89,25 +89,32 @@ tasks: - npm test dev: - desc: "Develop: archied live-reload + Vite HMR together. Open http://localhost:5173" + desc: "Develop: archied live-reload + archie-gateway + Vite HMR together. Open http://localhost:5173" summary: | - Runs both halves of the dev loop in one terminal: + Runs the dev loop in one terminal: - * air rebuilds and restarts archied on Go changes - * vite serves the dashboard with hot reload on :5173, - proxying /api and /events through to archied on :8484 + * air rebuilds and restarts archied on Go changes + * archie-gateway serves ChatContract on 127.0.0.1:8585 (archied + dials it for chat; it does not embed a gateway) + * vite serves the dashboard with hot reload on :5173, + proxying /api and /events through to archied on :8484 Open http://localhost:5173 -- not :8484. The Vite server is the one with hot reload; :8484 serves the last built dist/ and will look stale. - Ctrl-C stops both. - deps: [dev:daemon, dev:ui] + Ctrl-C stops all three. + deps: [dev:daemon, dev:gateway, dev:ui] dev:daemon: desc: archied only, live-reloading via air (prefer `task dev`) cmds: - air + dev:gateway: + desc: archie-gateway only, no live-reload (prefer `task dev`) + cmds: + - go run ./cmd/archie-gateway + dev:ui: desc: Vite dev server only, expects archied already running (prefer `task dev`) dir: ui diff --git a/go.sum b/go.sum index fcf604c64..9bcd555ab 100644 --- a/go.sum +++ b/go.sum @@ -2,16 +2,21 @@ 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.3 h1:A2jO8jwOugrrovveCWfj0KEZOfqiLgAcwjpHPhzIGw0= cel.dev/expr v0.25.3/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= +cloud.google.com/go/auth v0.18.2/go.mod h1:xD+oY7gcahcu7G2SG2DsBerfFxgPAJz17zz2joOFF3M= +cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10= code.gitea.io/sdk/gitea v0.25.1 h1:yywxWwoV+SdjHtbC6unBiXojWdZOtoHuGhEazEXeWuE= code.gitea.io/sdk/gitea v0.25.1/go.mod h1:uDFWYBU8dgZsgOHwe6C/6olxvf8FHguNB3wW1i83fgg= github.com/42wim/httpsig v1.2.4 h1:mI5bH0nm4xn7K18fo1K3okNDRq8CCJ0KbBYWyA6r8lU= github.com/42wim/httpsig v1.2.4/go.mod h1:yKsYfSyTBEohkPik224QPFylmzEBtda/kjyIAJjh3ps= +github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk= github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.33.0/go.mod h1:pJTkW8hEUIIi3Pf65lPZOnn4Y81yCllX6IWk2jNXdkM= github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= github.com/ProtonMail/go-crypto v1.4.1 h1:9RfcZHqEQUvP8RzecWEUafnZVtEvrBVL9BiF67IQOfM= github.com/ProtonMail/go-crypto v1.4.1/go.mod h1:e1OaTyu5SYVrO9gKOEhTc+5UcXtTUa+P3uLudwcgPqo= +github.com/a-h/templ v0.3.1020/go.mod h1:A2DlK61v+K+NRoGnhmYbNYVmtYHcFO5/AisMvBdDxTM= github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8= github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be/go.mod h1:ySMOLuWl6zY27l47sB3qLNK6tF2fkHG55UZxx8oIVo4= github.com/antithesishq/antithesis-sdk-go v0.8.0 h1:bVV5ZAuwaREn4klRSJusYaA+A7NXq8Qi9C/knCaQ2N4= @@ -20,14 +25,18 @@ github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYW github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= +github.com/bwesterb/go-ristretto v1.2.4/go.mod h1:fUIoIZaG73pV5biE2Blr2xEzDoMj7NFEuV9ekS419A0= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/cloudflare/circl v1.6.5 h1:O64F26HEqNhznd/hrC5KZXVKYuKM2rx4deZDTc4ihQA= github.com/cloudflare/circl v1.6.5/go.mod h1:h5LNyxAc5nTue9DS5jT+48en2PSDYt3zdGnz5OstK6c= +github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2/go.mod h1:qwXFYgsP6T7XnJtbKlf1HP8AjxZZyzxMmc+Lq5GjlU4= github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI= github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M= github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE= github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk= +github.com/containerd/typeurl/v2 v2.2.0/go.mod h1:8XOOxnyatxSWuG8OfsZXVnAF4iZfedjS/8UHSPJnX4g= +github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davidmz/go-pageant v1.0.2 h1:bPblRCh5jGU+Uptpz6LgMZGD5hJoOt7otgT454WvHn0= @@ -42,6 +51,10 @@ github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkp github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc= github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ= +github.com/envoyproxy/go-control-plane v0.14.0/go.mod h1:NcS5X47pLl/hfqxU70yPwL9ZMkUlwlKxtAohpi2wBEU= +github.com/envoyproxy/go-control-plane/envoy v1.37.0/go.mod h1:DReE9MMrmecPy+YvQOAOHNYMALuowAnbjjEMkkWOi6A= +github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJPzVVHnPgRKdUdwW/KdbRt94AzgRee4= +github.com/envoyproxy/protoc-gen-validate v1.3.3/go.mod h1:TsndJ/ngyIdQRhMcVVGDDHINPLWB7C82oDArY51KfB0= github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc= github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE= github.com/gliderlabs/ssh v0.3.8 h1:a4YXD1V7xMF9g5nTkdfnja3Sxy1PVDCj1Zg4Wb8vY6c= @@ -56,13 +69,17 @@ github.com/go-git/go-git-fixtures/v6 v6.0.0-alpha.1 h1:gmqi2jvsreu0s8JMLylYDFq4s github.com/go-git/go-git-fixtures/v6 v6.0.0-alpha.1/go.mod h1:ECf1MqJlBdYpKggBrOXjo/0EnvRZx6D++I86UYjPgAQ= github.com/go-git/go-git/v6 v6.0.0-alpha.5 h1:sE+OlkHgYWNMVmN1s9sR7uyFgsWLtxcNWse/vBYKxRE= github.com/go-git/go-git/v6 v6.0.0-alpha.5/go.mod h1:3IjhiZnM+uBmUrOGSeqrJpsmi4Vd0H2NZO/uK2a7d0s= +github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8= github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/go-quicktest/qt v1.101.0/go.mod h1:14Bz/f7NwaXPtdYEgzsx46kqSxVwTbzVZsDC26tQJow= github.com/go-telegram/bot v1.25.0 h1:C072msZtr+GjJiQsX/UJLirz+jzSNZVWkckxWufR7Ww= github.com/go-telegram/bot v1.25.0/go.mod h1:i2TRs7fXWIeaceF3z7KzsMt/he0TwkVC680mvdTFYeM= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= +github.com/golang/glog v1.2.5/go.mod h1:6AhwSGph0fcJtXVM/PEHPqZlFeoLxhs7/t5UDAwmO+w= 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= @@ -76,10 +93,14 @@ github.com/google/go-querystring v1.2.0 h1:yhqkPbu2/OH+V9BfpCVPZkNmUXhb2gBxJArfh github.com/google/go-querystring v1.2.0/go.mod h1:8IFJqpSRITyJ8QhQ13bmbeMBDfmeEJZD5A0egEOmkqU= github.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo= github.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY= +github.com/google/go-tpm-tools v0.3.13-0.20230620182252-4639ecce2aba/go.mod h1:EFYHy8/1y2KfgTAsx7Luu7NGhoxtuVHnNo8jE7FikKc= github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo= github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk= +github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/googleapis/enterprise-certificate-proxy v0.3.11/go.mod h1:RFV7MUdlb7AgEq2v7FmMCfeSMCllAzWxFgRdusoGks8= +github.com/googleapis/gax-go/v2 v2.17.0/go.mod h1:mzaqghpQp4JDh3HvADwrat+6M3MOIDp5YKHhb9PAgDY= github.com/hashicorp/go-version v1.9.0 h1:CeOIz6k+LoN3qX9Z0tyQrPtiB1DFYRPfCIBtaXPSCnA= github.com/hashicorp/go-version v1.9.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= @@ -107,6 +128,7 @@ 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.6.0 h1:AJjEB21QPbXSXjDsZorFBoDZPhMrfbpaPLgSMAW9Bgs= github.com/moby/moby/client v0.6.0/go.mod h1:OCo00wNRyA3m4lmJ228W3JbyCN4ZNNYjpOXiJydBdcQ= +github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc= github.com/nats-io/jwt/v2 v2.8.2 h1:XXRgB60MSTnqsRwejQurVDs/hcv2dkt+86GjI+I/bMc= github.com/nats-io/jwt/v2 v2.8.2/go.mod h1:Ag/56sq9OblL4JgdYufDd16Egb17Kr/8WwwuO/forVc= github.com/nats-io/nats-server/v2 v2.14.6 h1:dHjEHa49lUTxIb5jrsk5kz/AmOyOQ4T9ti8djcBumDQ= @@ -127,15 +149,20 @@ github.com/pjbgf/sha1cd v0.6.0 h1:3WJ8Wz8gvDz29quX1OcEmkAlUg9diU4GxJHqs0/XiwU= github.com/pjbgf/sha1cd v0.6.0/go.mod h1:lhpGlyHLpQZoxMv8HcgXvZEhcGs0PG/vsZnEJ7H0iCM= github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= +github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= +github.com/russross/blackfriday v1.6.0/go.mod h1:ti0ldHuxg49ri4ksnFxlkCfN+hvslNlmVHqNRXXJNAY= github.com/samcharles93/ai-sdk v0.1.32 h1:rfBpWUOADuRTaq2kyCnMjdhtlFfaqUbsyL5DbIluqmA= github.com/samcharles93/ai-sdk v0.1.32/go.mod h1:u4zrQ9/Q58L5mNEut4bNQ1ks+RCKq71LN5EDz2N/0Zk= +github.com/santhosh-tekuri/jsonschema/v5 v5.3.1/go.mod h1:uToXkOrWAZ6/Oc07xWQrPOhJotwFIyu2bBVN41fcDUY= github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw= github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4= +github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= +github.com/spiffe/go-spiffe/v2 v2.7.0/go.mod h1:47Q0Q9/AqGha8QLHp+kxpH4Wca7X7EnOtlIJy3mxZ3U= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= @@ -144,6 +171,7 @@ github.com/traefik/yaegi v0.16.1 h1:f1De3DVJqIDKmnasUF6MwmWv1dSEEat0wcpXhD2On3E= github.com/traefik/yaegi v0.16.1/go.mod h1:4eVhbPb3LnD2VigQjhYbEJ69vDRFdT2HQNrXx8eEwUY= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= +go.opentelemetry.io/contrib/detectors/gcp v1.44.0/go.mod h1:tNAsgd8avTGke1+MndXlU5Cru4PQ9Ai/cCNWQv/ZJ/s= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0 h1:3g7B90UzBltIDKq1/5mrTGxTnOFDV0ICOhLoxiZ8jlg= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0/go.mod h1:Ef8SuTh59BT7+ofpDxN9z+yOlc4t2GjLmKDgYNJL/NU= go.opentelemetry.io/otel v1.46.0 h1:FHt5/CDyVxi/8IM1CH7VE/rRgq3kLHa2mSTVMO8AWyc= @@ -171,6 +199,7 @@ golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To= golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU= +golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -192,6 +221,8 @@ 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.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI= golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo= +golang.org/x/tools/go/expect v0.1.1-deprecated/go.mod h1:eihoPOH+FgIqa3FpoTwguz/bVUSGBlGQU67vpBeOrBY= +golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated/go.mod h1:RVAQXBGNv1ib0J382/DPCRS/BPnsGebyM1Gj5VSDpG8= 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= diff --git a/internal/app/archied/bootstrap.go b/internal/app/archied/bootstrap.go index f30476e2e..5795dabd1 100644 --- a/internal/app/archied/bootstrap.go +++ b/internal/app/archied/bootstrap.go @@ -486,29 +486,15 @@ func (b *boot) setupContainers(ctx context.Context) func() { // setupLLMAndChat wires the runtime, tool registry, model management, // personas and the dashboard's chat service. -func (b *boot) setupLLMAndChat(ctx context.Context) error { +func (b *boot) setupLLMAndChat() error { cfg := b.cfg - // The daemon owns the local gateway in default mode: the modular - // monolith keeps serving the ChatContract in-process, with the - // standalone archie-gateway binary prepared as a remote alternative - // (mode = "remote"). The local and remote adapters both satisfy - // gateway.ChatContract; composition picks the transport. - var local gateway.ChatContract - if cfg.Services.Gateway.Mode != "remote" { - // Full local contract: router, sessions, models, personas, task - // commands and the LLM responder. The in-process task-actions - // actor applies mutations directly to the store the daemon owns - // -- no HTTP detour through webui, no NATS hop. - local = b.setupGatewayChat(ctx, taskActionsActor{b}) - } else { - // The daemon still runs its own Telegram/email routers in Phase 1, - // so the runtime objects survive even though the webui chat goes - // over gRPC to the standalone Gateway. - b.setupChatRuntime(cfg) - } + // Telegram/email keep their own in-process routers rather than going + // through ChatContract: their streaming responder is a callback, and + // ChatContract's wire-safe interface can't carry one. + b.setupChatRuntime(cfg) - contract, cleanup, err := composeChatContract(cfg.Services.Gateway, local) + contract, cleanup, err := composeChatContract(cfg.Services.Gateway) if err != nil { return err } diff --git a/internal/app/archied/chat_service.go b/internal/app/archied/chat_service.go index 981e9b7a2..86231ecae 100644 --- a/internal/app/archied/chat_service.go +++ b/internal/app/archied/chat_service.go @@ -12,30 +12,22 @@ import ( "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") - } - // The first extraction uses a loopback gRPC hop. Deployments that put - // the Gateway on a separate trust boundary supply their own transport - // credentials through options; the local process split must be usable - // without manufacturing a certificate in the config loader. - opts := append([]grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}, options...) - conn, err := grpc.NewClient(settings.Target, opts...) - if err != nil { - return nil, nil, fmt.Errorf("create gateway client: %w", err) - } - return gatewayrpc.NewClient(conn), func() { _ = conn.Close() }, nil - default: - return nil, nil, fmt.Errorf("unknown gateway service mode %q", settings.Mode) +// composeChatContract dials the standalone archie-gateway, the sole owner of +// ChatContract. +func composeChatContract(settings config.ServiceConnection, options ...grpc.DialOption) (gateway.ChatContract, func(), error) { + if settings.Mode != "remote" { + return nil, nil, fmt.Errorf("unsupported gateway service mode %q; archie-gateway is required, see deployments/README.md", settings.Mode) } + if strings.TrimSpace(settings.Target) == "" { + return nil, nil, fmt.Errorf("remote gateway requires a target") + } + // Deployments that put the Gateway on a separate trust boundary supply + // their own transport credentials through options; the default must be + // usable without manufacturing a certificate in the config loader. + opts := append([]grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}, options...) + conn, err := grpc.NewClient(settings.Target, opts...) + if err != nil { + return nil, nil, fmt.Errorf("create gateway client: %w", err) + } + return gatewayrpc.NewClient(conn), func() { _ = conn.Close() }, nil } diff --git a/internal/app/archied/chat_service_test.go b/internal/app/archied/chat_service_test.go index 28ff5be78..6a25b46b6 100644 --- a/internal/app/archied/chat_service_test.go +++ b/internal/app/archied/chat_service_test.go @@ -17,38 +17,19 @@ import ( "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: "default mode", settings: config.ServiceConnection{Target: "localhost:1234"}}, + {name: "inproc removed", 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{}) + chat, cleanup, err := composeChatContract(tt.settings) if cleanup != nil { t.Cleanup(cleanup) } @@ -76,9 +57,8 @@ func TestComposeChatContractRemoteAndCleanup(t *testing.T) { } }) - local := compositionChat{snapshot: gateway.ChatSnapshot{ActiveModel: "local-model"}} chat, cleanup, err := composeChatContract( - config.ServiceConnection{Mode: "remote", Target: "passthrough:///chat"}, local, + config.ServiceConnection{Mode: "remote", Target: "passthrough:///chat"}, grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return listener.DialContext(ctx) }), diff --git a/internal/app/archied/main.go b/internal/app/archied/main.go index 7195ceb55..78651d8e6 100644 --- a/internal/app/archied/main.go +++ b/internal/app/archied/main.go @@ -389,7 +389,7 @@ func Run() int { //nolint:cyclop // the composition root's setup sequence is del return 1 } - if err := b.setupLLMAndChat(ctx); err != nil { + if err := b.setupLLMAndChat(); err != nil { return 1 } if !b.setupGateways(ctx, args.cfgPath, args.overlayPath) { diff --git a/internal/app/archied/task_action_adapter_test.go b/internal/app/archied/task_action_adapter_test.go index 78cd64a31..0fa5b35cf 100644 --- a/internal/app/archied/task_action_adapter_test.go +++ b/internal/app/archied/task_action_adapter_test.go @@ -2,6 +2,7 @@ package archied import ( "context" + "fmt" "log/slog" "path/filepath" "strings" @@ -13,9 +14,25 @@ import ( "github.com/samcharles93/archie-core/internal/taskstate" ) -// newChatTaskActorForTest wires the same production chain the daemon uses in -// default (in-process) mode: chatTaskActorAdapter → LocalChatAdapter → -// taskActionsActor → taskactions.Service over the given store. +// testTaskActor formats taskactions.Service's result the same way the real +// NATS actor (infrastructure/taskactions.Client) does, so this test exercises +// the shared service through the same chatTaskActorAdapter → LocalChatAdapter +// → ChatTaskActor chain production traffic uses. +type testTaskActor struct{ b *boot } + +func (a testTaskActor) ApplyChatTaskAction( + ctx context.Context, identity string, taskID int64, action taskstate.Action, +) (gateway.TaskActionResult, error) { + if err := a.b.taskActions().Apply(ctx, &identity, taskID, action); err != nil { + return gateway.TaskActionResult{}, err + } + return gateway.TaskActionResult{ + TaskID: taskID, + Action: string(action), + Message: fmt.Sprintf("Applied %s to task %d.", action, taskID), + }, nil +} + func newChatTaskActorForTest(t *testing.T, st store.TaskStore, cfg config.Config) chatTaskActorAdapter { t.Helper() b := &boot{ @@ -23,7 +40,7 @@ func newChatTaskActorForTest(t *testing.T, st store.TaskStore, cfg config.Config cfg: cfg, log: slog.Default(), } - return chatTaskActorAdapter{contract: &gateway.LocalChatAdapter{TaskActor: taskActionsActor{b}}} + return chatTaskActorAdapter{contract: &gateway.LocalChatAdapter{TaskActor: testTaskActor{b}}} } func TestChatTaskActorAdapterCrossIdentityRefused(t *testing.T) { diff --git a/internal/app/archied/task_actions.go b/internal/app/archied/task_actions.go index fe4e55ee0..32646d11f 100644 --- a/internal/app/archied/task_actions.go +++ b/internal/app/archied/task_actions.go @@ -7,33 +7,9 @@ import ( "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/domain/taskactions" "github.com/samcharles93/archie-core/internal/events" - "github.com/samcharles93/archie-core/internal/gateway" taskactionstore "github.com/samcharles93/archie-core/internal/infrastructure/taskactions" - "github.com/samcharles93/archie-core/internal/taskstate" ) -// taskActionsActor applies operator actions in-process for the daemon's own -// local gateway. It is the identity-scoping implementation behind the -// ChatContract's ApplyTaskAction when the daemon is the Gateway (default -// mode). The standalone Gateway instead forwards over NATS with -// taskactions.Client; both paths converge on the one taskactions.Service. -type taskActionsActor struct { - b *boot -} - -func (a taskActionsActor) ApplyChatTaskAction( - ctx context.Context, identity string, taskID int64, action taskstate.Action, -) (gateway.TaskActionResult, error) { - if err := a.b.taskActions().Apply(ctx, &identity, taskID, action); err != nil { - return gateway.TaskActionResult{}, err - } - return gateway.TaskActionResult{ - TaskID: taskID, - Action: string(action), - Message: fmt.Sprintf("Applied %s to task %d.", action, taskID), - }, nil -} - // taskActions assembles the daemon-owned operator action service. The daemon // retains execution cancellation, retry policy, forge closure and event // ownership; the dashboard's webui service and the NATS responder both build diff --git a/internal/infrastructure/configuration/defaults.go b/internal/infrastructure/configuration/defaults.go index c9fd8ecaf..6d6fa9e5f 100644 --- a/internal/infrastructure/configuration/defaults.go +++ b/internal/infrastructure/configuration/defaults.go @@ -60,7 +60,8 @@ const ( // 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" + cfg.Services.Gateway.Mode = "remote" + cfg.Services.Gateway.Target = "127.0.0.1:8585" } l.applyGeneralDefaults(cfg) applyForgeDefaults(cfg) diff --git a/internal/infrastructure/configuration/services_test.go b/internal/infrastructure/configuration/services_test.go index f5a7e4051..58af72c9a 100644 --- a/internal/infrastructure/configuration/services_test.go +++ b/internal/infrastructure/configuration/services_test.go @@ -10,13 +10,13 @@ func TestLoadGatewayServiceMode(t *testing.T) { for _, tt := range []struct { name, section string wantError bool + wantTarget string }{ - {name: "default"}, - {name: "local", section: "[services.gateway]\nmode = 'inproc'"}, - {name: "remote", section: "[services.gateway]\nmode = 'remote'\ntarget = 'dns:///gateway:8443'"}, + {name: "default", wantTarget: "127.0.0.1:8585"}, + {name: "remote", section: "[services.gateway]\nmode = 'remote'\ntarget = 'dns:///gateway:8443'", wantTarget: "dns:///gateway:8443"}, {name: "invalid mode", section: "[services.gateway]\nmode = 'typo'", wantError: true}, + {name: "inproc removed", section: "[services.gateway]\nmode = 'inproc'", 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") @@ -28,15 +28,11 @@ func TestLoadGatewayServiceMode(t *testing.T) { 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 != "remote" { + t.Fatalf("mode = %q, want %q", cfg.Services.Gateway.Mode, "remote") } - if cfg.Services.Gateway.Mode != want { - t.Fatalf("mode = %q, want %q", cfg.Services.Gateway.Mode, want) + if cfg.Services.Gateway.Target != tt.wantTarget { + t.Fatalf("target = %q, want %q", cfg.Services.Gateway.Target, tt.wantTarget) } } }) diff --git a/internal/infrastructure/configuration/validate.go b/internal/infrastructure/configuration/validate.go index 8cb9eecfb..574b92cec 100644 --- a/internal/infrastructure/configuration/validate.go +++ b/internal/infrastructure/configuration/validate.go @@ -98,16 +98,12 @@ func validate(cfg *config.Config) error { 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 fmt.Errorf("%w: services.gateway.mode must be remote", ErrInvalidInput) } return nil } diff --git a/internal/infrastructure/configuration/validate_test.go b/internal/infrastructure/configuration/validate_test.go index e9739aafc..8db946071 100644 --- a/internal/infrastructure/configuration/validate_test.go +++ b/internal/infrastructure/configuration/validate_test.go @@ -26,6 +26,9 @@ func minimalValidConfig() config.Config { Containers: config.ContainerConfig{ Image: "ghcr.io/samcharles93/archie-agent:latest", }, + Services: config.Services{ + Gateway: config.ServiceConnection{Mode: "remote", Target: "127.0.0.1:8585"}, + }, } } From 14e5b542bfd3ccc3642fc25ce7b258091a70935e Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sun, 6 Sep 2026 02:13:03 +1000 Subject: [PATCH 6/6] fix(gateway): drop services.gateway.mode, remote is the only transport Mode had exactly one legal value after the previous commit deleted the in-process path, which made it dead config surface that could only confuse an operator into thinking there was still a real choice. ServiceConnection is now just a target address; composeChatContract only checks it's non-blank, defaulting to 127.0.0.1:8585. --- deployments/docker-nats-stack.toml | 1 - deployments/local-ollama-standalone.toml | 1 - deployments/multi-forge-github-gitea.toml | 1 - deployments/single-forge-github.toml | 1 - internal/app/archied/chat_service.go | 5 +--- internal/app/archied/chat_service_test.go | 9 +++---- internal/config/services.go | 3 +-- .../infrastructure/configuration/defaults.go | 3 +-- .../configuration/services_test.go | 24 ++++++------------- .../infrastructure/configuration/validate.go | 15 ------------ .../configuration/validate_test.go | 2 +- 11 files changed, 14 insertions(+), 51 deletions(-) diff --git a/deployments/docker-nats-stack.toml b/deployments/docker-nats-stack.toml index 3da07a826..fd8f39432 100644 --- a/deployments/docker-nats-stack.toml +++ b/deployments/docker-nats-stack.toml @@ -18,7 +18,6 @@ work_dir = "~/.local/share/archie/work" db_path = "~/.local/share/archie/archie.db" [services.gateway] -mode = "remote" target = "127.0.0.1:8585" [forge] diff --git a/deployments/local-ollama-standalone.toml b/deployments/local-ollama-standalone.toml index bbb4e7e6b..185fcf878 100644 --- a/deployments/local-ollama-standalone.toml +++ b/deployments/local-ollama-standalone.toml @@ -9,7 +9,6 @@ work_dir = "~/.local/share/archie/work" db_path = "~/.local/share/archie/archie.db" [services.gateway] -mode = "remote" target = "127.0.0.1:8585" poll_interval = "60s" diff --git a/deployments/multi-forge-github-gitea.toml b/deployments/multi-forge-github-gitea.toml index 06fedf91f..a2ab04335 100644 --- a/deployments/multi-forge-github-gitea.toml +++ b/deployments/multi-forge-github-gitea.toml @@ -10,7 +10,6 @@ work_dir = "~/.local/share/archie/work" db_path = "~/.local/share/archie/archie.db" [services.gateway] -mode = "remote" target = "127.0.0.1:8585" poll_interval = "60s" diff --git a/deployments/single-forge-github.toml b/deployments/single-forge-github.toml index 4ddec6ca6..19337dc83 100644 --- a/deployments/single-forge-github.toml +++ b/deployments/single-forge-github.toml @@ -16,7 +16,6 @@ diff_cap_lines = 400 # The Gateway Service owns conversational state and serves ChatContract over # gRPC. Run archie-gateway alongside archied with this address. [services.gateway] -mode = "remote" target = "127.0.0.1:8585" [forge] diff --git a/internal/app/archied/chat_service.go b/internal/app/archied/chat_service.go index 86231ecae..20ca3af5a 100644 --- a/internal/app/archied/chat_service.go +++ b/internal/app/archied/chat_service.go @@ -15,11 +15,8 @@ import ( // composeChatContract dials the standalone archie-gateway, the sole owner of // ChatContract. func composeChatContract(settings config.ServiceConnection, options ...grpc.DialOption) (gateway.ChatContract, func(), error) { - if settings.Mode != "remote" { - return nil, nil, fmt.Errorf("unsupported gateway service mode %q; archie-gateway is required, see deployments/README.md", settings.Mode) - } if strings.TrimSpace(settings.Target) == "" { - return nil, nil, fmt.Errorf("remote gateway requires a target") + return nil, nil, fmt.Errorf("services.gateway.target is required") } // Deployments that put the Gateway on a separate trust boundary supply // their own transport credentials through options; the default must be diff --git a/internal/app/archied/chat_service_test.go b/internal/app/archied/chat_service_test.go index 6a25b46b6..8d52dbaa1 100644 --- a/internal/app/archied/chat_service_test.go +++ b/internal/app/archied/chat_service_test.go @@ -22,11 +22,8 @@ func TestComposeChatContractRejectsInvalidSettings(t *testing.T) { name string settings config.ServiceConnection }{ - {name: "unknown mode", settings: config.ServiceConnection{Mode: "automatic"}}, - {name: "default mode", settings: config.ServiceConnection{Target: "localhost:1234"}}, - {name: "inproc removed", 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"}}, + {name: "missing target", settings: config.ServiceConnection{}}, + {name: "blank target", settings: config.ServiceConnection{Target: " \t\n"}}, } { t.Run(tt.name, func(t *testing.T) { chat, cleanup, err := composeChatContract(tt.settings) @@ -58,7 +55,7 @@ func TestComposeChatContractRemoteAndCleanup(t *testing.T) { }) chat, cleanup, err := composeChatContract( - config.ServiceConnection{Mode: "remote", Target: "passthrough:///chat"}, + config.ServiceConnection{Target: "passthrough:///chat"}, grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return listener.DialContext(ctx) }), diff --git a/internal/config/services.go b/internal/config/services.go index 3fda055ee..b8334323b 100644 --- a/internal/config/services.go +++ b/internal/config/services.go @@ -5,9 +5,8 @@ type Services struct { Gateway ServiceConnection `toml:"gateway" yaml:"gateway"` } -// ServiceConnection selects local calls or a TLS gRPC target. It does not +// ServiceConnection is the archie-gateway process's gRPC address. It does not // register services or start listeners. Changes require a daemon restart. type ServiceConnection struct { - Mode string `toml:"mode" yaml:"mode"` Target string `toml:"target" yaml:"target"` } diff --git a/internal/infrastructure/configuration/defaults.go b/internal/infrastructure/configuration/defaults.go index 6d6fa9e5f..a9eb507a5 100644 --- a/internal/infrastructure/configuration/defaults.go +++ b/internal/infrastructure/configuration/defaults.go @@ -59,8 +59,7 @@ 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 = "remote" + if cfg.Services.Gateway.Target == "" { cfg.Services.Gateway.Target = "127.0.0.1:8585" } l.applyGeneralDefaults(cfg) diff --git a/internal/infrastructure/configuration/services_test.go b/internal/infrastructure/configuration/services_test.go index 58af72c9a..faa2c161b 100644 --- a/internal/infrastructure/configuration/services_test.go +++ b/internal/infrastructure/configuration/services_test.go @@ -6,17 +6,12 @@ import ( "testing" ) -func TestLoadGatewayServiceMode(t *testing.T) { +func TestLoadGatewayServiceTarget(t *testing.T) { for _, tt := range []struct { - name, section string - wantError bool - wantTarget string + name, section, wantTarget string }{ {name: "default", wantTarget: "127.0.0.1:8585"}, - {name: "remote", section: "[services.gateway]\nmode = 'remote'\ntarget = 'dns:///gateway:8443'", wantTarget: "dns:///gateway:8443"}, - {name: "invalid mode", section: "[services.gateway]\nmode = 'typo'", wantError: true}, - {name: "inproc removed", section: "[services.gateway]\nmode = 'inproc'", wantError: true}, - {name: "remote without target", section: "[services.gateway]\nmode = 'remote'", wantError: true}, + {name: "explicit target", section: "[services.gateway]\ntarget = 'dns:///gateway:8443'", wantTarget: "dns:///gateway:8443"}, } { t.Run(tt.name, func(t *testing.T) { path := filepath.Join(t.TempDir(), "config.toml") @@ -24,16 +19,11 @@ func TestLoadGatewayServiceMode(t *testing.T) { 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 { + t.Fatal(err) } - if err == nil { - if cfg.Services.Gateway.Mode != "remote" { - t.Fatalf("mode = %q, want %q", cfg.Services.Gateway.Mode, "remote") - } - if cfg.Services.Gateway.Target != tt.wantTarget { - t.Fatalf("target = %q, want %q", cfg.Services.Gateway.Target, tt.wantTarget) - } + if cfg.Services.Gateway.Target != tt.wantTarget { + t.Fatalf("target = %q, want %q", cfg.Services.Gateway.Target, tt.wantTarget) } }) } diff --git a/internal/infrastructure/configuration/validate.go b/internal/infrastructure/configuration/validate.go index 574b92cec..e47e8cf15 100644 --- a/internal/infrastructure/configuration/validate.go +++ b/internal/infrastructure/configuration/validate.go @@ -59,9 +59,6 @@ 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 } @@ -96,18 +93,6 @@ func validate(cfg *config.Config) error { return validateCapture(cfg) } -func validateGatewayService(service config.ServiceConnection) error { - switch service.Mode { - 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 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/configuration/validate_test.go b/internal/infrastructure/configuration/validate_test.go index 8db946071..993e71dd9 100644 --- a/internal/infrastructure/configuration/validate_test.go +++ b/internal/infrastructure/configuration/validate_test.go @@ -27,7 +27,7 @@ func minimalValidConfig() config.Config { Image: "ghcr.io/samcharles93/archie-agent:latest", }, Services: config.Services{ - Gateway: config.ServiceConnection{Mode: "remote", Target: "127.0.0.1:8585"}, + Gateway: config.ServiceConnection{Target: "127.0.0.1:8585"}, }, } }