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; }