diff --git a/go.mod b/go.mod index b17283f1c..4b55e6911 100644 --- a/go.mod +++ b/go.mod @@ -46,13 +46,10 @@ require ( github.com/philhofer/fwd v1.2.1 // indirect github.com/pjbgf/sha1cd v0.7.0 // indirect github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect - github.com/segmentio/asm v1.2.1 // indirect - github.com/segmentio/encoding v0.5.4 // indirect github.com/sergi/go-diff v1.4.0 // indirect github.com/sethvargo/go-retry v0.5.0 // indirect github.com/tinylib/msgp v1.6.5 // indirect github.com/x448/float16 v0.8.4 // indirect - github.com/yosida95/uritemplate/v3 v3.0.2 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect go.opentelemetry.io/otel/log v1.47.0 // indirect go.opentelemetry.io/otel/metric v1.47.0 // indirect @@ -85,7 +82,6 @@ require ( github.com/klauspost/compress v1.20.4 github.com/moby/moby/api v1.56.1 github.com/moby/moby/client v0.6.2 - github.com/modelcontextprotocol/go-sdk v1.8.0 github.com/nats-io/nats-server/v2 v2.15.3 github.com/nats-io/nats.go v1.55.0 github.com/opencontainers/go-digest v1.0.0 diff --git a/go.sum b/go.sum index ef97177cd..83646efcd 100644 --- a/go.sum +++ b/go.sum @@ -139,8 +139,6 @@ github.com/moby/moby/api v1.56.1 h1:PpWkvVPB7Fr/No8w+TfyJ/I6rWZ2YPZhT3JorIg+06c= github.com/moby/moby/api v1.56.1/go.mod h1:sZ+THbVWkjOmBPPfbnzdD/G1LuIexWhqlSHHPTDQ1Uk= github.com/moby/moby/client v0.6.2 h1:ekSPlMccrZGcw6Scb8T9D39qE0mB+XupU/yS0zNw9N4= github.com/moby/moby/client v0.6.2/go.mod h1:DGcnO7qmPJrqobx/ggQgQ/AUk+2wgVdQv7uxB0/mEsc= -github.com/modelcontextprotocol/go-sdk v1.8.0 h1:KIvahhYqwtbeniWVPs3TcXEA7b8jEtwfBpOTAI+Urx4= -github.com/modelcontextprotocol/go-sdk v1.8.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts= github.com/nats-io/jwt/v2 v2.8.3 h1:pqImTmlqH2zPHKNdRXO0YRyWif2diGRlrtLFJ2RxM2I= github.com/nats-io/jwt/v2 v2.8.3/go.mod h1:OOY2rP/UU8tcfoqhbHmBKcNdpFMKvmxIkmFFa16M4wI= github.com/nats-io/nats-server/v2 v2.15.3 h1:IgHIKL4DYN9mEfwtPcdM39muvXG8v9FBADQn0f4Whs0= @@ -174,10 +172,6 @@ github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0t github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/samcharles93/ai-sdk v0.6.0 h1:ANHutwvl/K233Dkflc2vKT48qsXRT1iRwjL5S1Dm+jY= github.com/samcharles93/ai-sdk v0.6.0/go.mod h1:NNkiUZ2qfezDHhmF8zHibKsPgpU8b5jphDQ0n2t1KL0= -github.com/segmentio/asm v1.2.1 h1:DTNbBqs57ioxAD4PrArqftgypG4/qNpXoJx8TVXxPR0= -github.com/segmentio/asm v1.2.1/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs= -github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0= -github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0= 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/sethvargo/go-retry v0.5.0 h1:JYfFKmVJ8ER06GReN1efzc5cm52BrVsFVzmcHiKJwfY= @@ -193,8 +187,6 @@ github.com/tinylib/msgp v1.6.5 h1:iAH6XTP7BpzErjBZlujJQXxA+GmRi2YWs6M4KdLtNbE= github.com/tinylib/msgp v1.6.5/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA= github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= -github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4= -github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4= 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/instrumentation/google.golang.org/grpc/otelgrpc v0.72.0 h1:Tq+E65HaNbZTeqcLw6QUhsV+/EIWdkfUH2CQzcrlE5M= @@ -254,8 +246,6 @@ golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo= golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY= golang.org/x/time v0.16.0 h1:vMb6ptszcQMkcwiRTAuNNU50gom6++Q/6gY2hDM6VDE= golang.org/x/time v0.16.0/go.mod h1:rVKOqvZeKvrDKTQiAHJ7wmwP0RzleSphoEA9RcdLA0s= -golang.org/x/tools v0.52.1-0.20261106145633-d407941a339a h1:Yqozs0FNPRoPGS4hNGlrNwRENWr5H5nVG9sN/f+5640= -golang.org/x/tools v0.52.1-0.20261106145633-d407941a339a/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs= 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-20261110000943-09e21b237f2c h1:ofk4SEqvpf6M5VWh88xRp42IYgdVOh7gffebnDj3OqU= diff --git a/internal/app/archiegateway/task_tool_result.go b/internal/app/archiegateway/task_tool_result.go deleted file mode 100644 index 8bb34ee36..000000000 --- a/internal/app/archiegateway/task_tool_result.go +++ /dev/null @@ -1,94 +0,0 @@ -package archiegateway - -import ( - "context" - "encoding/json" - "fmt" - "mime" - "os" - "path/filepath" - - "github.com/modelcontextprotocol/go-sdk/mcp" - - "github.com/samcharles93/archie-core/internal/agentexec" - "github.com/samcharles93/archie-core/internal/domain/agentrun" - "github.com/samcharles93/archie-core/internal/tools" -) - -func executeTaskTool(ctx context.Context, entry tools.ToolEntry, input json.RawMessage, limit int) (result *mcp.CallToolResult, err error) { - defer func() { - if recover() != nil { - result = nil - err = fmt.Errorf("tool execution failed") - } - }() - if !entry.Available() { - return nil, fmt.Errorf("tool is unavailable") - } - schema, err := json.Marshal(taskToolSchema(entry)) - if err != nil { - return nil, fmt.Errorf("tool schema unavailable") - } - if len(input) == 0 { - input = json.RawMessage(`{}`) - } - if reason, ok := agentexec.ValidateCaptureArgs(agentrun.CaptureTool{Name: entry.Name, Parameters: schema}, input); !ok { - return nil, fmt.Errorf("%s", reason) - } - var args map[string]any - if err := json.Unmarshal(input, &args); err != nil { - return nil, fmt.Errorf("arguments must be an object") - } - out, err := entry.Handler(ctx, args) - if err != nil { - return &mcp.CallToolResult{IsError: true, Content: []mcp.Content{&mcp.TextContent{Text: "tool execution failed"}}}, nil - } - if entry.MaxResultSizeChars != 0 { - limit = entry.MaxResultSizeChars - } - if media, ok := out.(tools.MultimodalResult); ok { - return taskToolMedia(entry.Name, media, limit) - } - raw, err := json.Marshal(out) - if err != nil { - return nil, fmt.Errorf("encode tool result") - } - return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: tools.CapPayload(entry.Name, string(raw), limit, "")}}}, nil -} - -func taskToolMedia(name string, media tools.MultimodalResult, limit int) (*mcp.CallToolResult, error) { - result := &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: tools.CapPayload(name, media.Summary, limit, "")}}} - root, err := os.OpenRoot(media.SubdirHint) - if err != nil { - return nil, fmt.Errorf("tool media unavailable") - } - defer root.Close() - for _, file := range media.Files { - relative, err := filepath.Rel(media.SubdirHint, file) - if err != nil || !filepath.IsLocal(relative) { - return nil, fmt.Errorf("tool media outside provider directory") - } - raw, err := root.ReadFile(relative) - if err != nil { - return nil, fmt.Errorf("read tool media") - } - mimeType := mime.TypeByExtension(filepath.Ext(file)) - switch mimeType { - case "image/png", "image/jpeg", "image/gif", "image/webp": - result.Content = append(result.Content, &mcp.ImageContent{Data: raw, MIMEType: mimeType}) - case "audio/wav", "audio/mpeg": - result.Content = append(result.Content, &mcp.AudioContent{Data: raw, MIMEType: mimeType}) - default: - result.Content = append(result.Content, &mcp.EmbeddedResource{Resource: &mcp.ResourceContents{URI: "archie-media:///" + filepath.Base(file), MIMEType: mimeType, Blob: raw}}) - } - } - return result, nil -} - -func taskToolSchema(entry tools.ToolEntry) tools.JSONSchema { - schema := entry.ResolvedSchema() - if schema == nil { - return tools.JSONSchema{"type": "object", "properties": map[string]any{}} - } - return schema -} diff --git a/internal/app/archiegateway/task_tool_result_test.go b/internal/app/archiegateway/task_tool_result_test.go deleted file mode 100644 index bf4f7b7f2..000000000 --- a/internal/app/archiegateway/task_tool_result_test.go +++ /dev/null @@ -1,76 +0,0 @@ -package archiegateway - -import ( - "context" - "encoding/json" - "os" - "path/filepath" - "strings" - "testing" - - "github.com/modelcontextprotocol/go-sdk/mcp" - - "github.com/samcharles93/archie-core/internal/tools" -) - -func TestTaskToolResults(t *testing.T) { - for _, tt := range []struct { - name, input string - output any - limit int - badPath bool - wantErr bool - }{ - {name: "text limit", input: `{"value":"valid"}`, output: strings.Repeat("a", 200), limit: 40}, - {name: "schema enforced", input: `{"value":true}`, wantErr: true}, - {name: "media", input: `{"value":"valid"}`}, - {name: "media cannot escape", input: `{"value":"valid"}`, badPath: true, wantErr: true}, - } { - t.Run(tt.name, func(t *testing.T) { - root := t.TempDir() - file := filepath.Join(root, "image.png") - if tt.badPath { - file = filepath.Join(t.TempDir(), "outside.png") - } - if err := os.WriteFile(file, []byte("image-data"), 0o600); err != nil { - t.Fatal(err) - } - output := tt.output - if output == nil { - output = tools.MultimodalResult{Summary: "image", SubdirHint: root, Files: []string{file}} - } - called := false - entry := tools.ToolEntry{Name: "tool", Schema: tools.JSONSchema{"type": "object", "properties": map[string]any{"value": map[string]any{"type": "string"}}, "required": []string{"value"}}, Handler: func(context.Context, map[string]any) (any, error) { called = true; return output, nil }} - result, err := executeTaskTool(t.Context(), entry, json.RawMessage(tt.input), tt.limit) - if (err != nil) != tt.wantErr { - t.Fatalf("error %v, want error %v", err, tt.wantErr) - } - if tt.name == "schema enforced" && called { - t.Fatal("invalid arguments executed") - } - if err != nil { - return - } - raw, err := json.Marshal(result) - if err != nil { - t.Fatal(err) - } - if strings.Contains(string(raw), root) { - t.Fatal("host media path escaped") - } - if tt.name == "media" { - image, ok := result.Content[1].(*mcp.ImageContent) - if !ok || string(image.Data) != "image-data" { - t.Fatalf("media result %s", raw) - } - } - text, ok := result.Content[0].(*mcp.TextContent) - if !ok { - t.Fatal("missing text content") - } - if tt.limit > 0 && strings.Contains(text.Text, strings.Repeat("a", 200)) { - t.Fatal("tool result limit was ignored") - } - }) - } -} diff --git a/internal/app/archiemessaging/compose.go b/internal/app/archiemessaging/compose.go index dfbff7519..c34a1d887 100644 --- a/internal/app/archiemessaging/compose.go +++ b/internal/app/archiemessaging/compose.go @@ -56,9 +56,8 @@ type channelInstance struct { // kind is the channel name a delivery or chat addresses, and owner the org // whose channel it is. The instance's built-in and extension channels belong // to the system org. - kind string - owner string - rebuild func(ResolvedConfig) (channels.Channel, error) + kind string + owner string // chat, when set, is the contract this channel speaks to the Gateway // through; an org's channel acts as its agent. Nil uses the service's. chat messaging.ChatContract diff --git a/internal/app/archiemessaging/enablement_test.go b/internal/app/archiemessaging/enablement_test.go index 9980bc9bb..0dbf618ca 100644 --- a/internal/app/archiemessaging/enablement_test.go +++ b/internal/app/archiemessaging/enablement_test.go @@ -9,7 +9,6 @@ import ( "time" "github.com/samcharles93/archie-core/internal/channels" - "github.com/samcharles93/archie-core/internal/channels/status" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/domain/messaging" ) @@ -73,8 +72,7 @@ func startTestService(t *testing.T, ch *servingChannel) *Service { } inst := &channelInstance{ name: "test", kind: "test", - rebuild: func(ResolvedConfig) (channels.Channel, error) { return ch, nil }, - notify: make(chan struct{}, 1), + notify: make(chan struct{}, 1), } srv.retry = channelRetryPolicy{attempts: 3, backoff: time.Millisecond, maxBackoff: time.Millisecond} @@ -103,7 +101,7 @@ func waitSupervised(t *testing.T, srv *Service, id string) { t.Helper() deadline := time.Now().Add(5 * time.Second) for time.Now().Before(deadline) { - inst := srv.instanceByID(id) + inst := instanceByID(srv, id) inst.mu.Lock() supervised := inst.supervised inst.mu.Unlock() @@ -115,17 +113,6 @@ func waitSupervised(t *testing.T, srv *Service, id string) { t.Fatalf("channel %q was never supervised", id) } -func channelByID(t *testing.T, srv *Service, id string) status.Status { - t.Helper() - for _, st := range srv.ChannelStatus() { - if st.ID == id { - return st - } - } - t.Fatalf("no channel %q in status", id) - return status.Status{} -} - // waitCount blocks until count reaches want, so an async start is observed // rather than slept for. func waitCount(t *testing.T, count func() int, want int) { @@ -140,34 +127,6 @@ func waitCount(t *testing.T, count func() int, want int) { t.Fatalf("channel started %d times, want at least %d", count(), want) } -// TestChannelEnableDisableLive pins that enabling and disabling a channel -// starts and stops it without a service restart, and that its declaration -// follows: a channel that was never configured is not reported as configured, -// and one that enablement stopped is reported stopped and unconfigured. -func TestChannelEnableDisableLive(t *testing.T) { - ch := &servingChannel{} - srv := startTestService(t, ch) - - if before := channelByID(t, srv, "test"); before.Configured || before.State != status.StateStopped { - t.Fatalf("test before enable = %+v, want not configured and stopped", before) - } - - if err := srv.enableChannel("test", ResolvedConfig{}); err != nil { - t.Fatalf("enable: %v", err) - } - waitCount(t, ch.count, 1) - if enabled := channelByID(t, srv, "test"); !enabled.Configured || enabled.State != status.StateRunning { - t.Fatalf("test after enable = %+v, want configured and running", enabled) - } - - if err := srv.disableChannel("test"); err != nil { - t.Fatalf("disable: %v", err) - } - if disabled := channelByID(t, srv, "test"); disabled.Configured || disabled.State != status.StateStopped { - t.Fatalf("test after disable = %+v, want not configured and stopped", disabled) - } -} - // fakeSettings serves a stored chat config at a version, the way the // control-plane client does. type fakeSettings struct { @@ -185,8 +144,8 @@ func (f fakeSettings) RuntimeChatConfig(context.Context, config.ChatConfig) (con func TestReconcileAppliesShowToolCalls(t *testing.T) { ch := &servingChannel{} srv := startTestService(t, ch) - if err := srv.enableChannel("test", ResolvedConfig{}); err != nil { - t.Fatalf("enable: %v", err) + if err := restart(srv, "test", ch); err != nil { + t.Fatalf("start: %v", err) } waitCount(t, ch.count, 1) diff --git a/internal/app/archiemessaging/extension_channels.go b/internal/app/archiemessaging/extension_channels.go index df199a914..1d8cd2d8b 100644 --- a/internal/app/archiemessaging/extension_channels.go +++ b/internal/app/archiemessaging/extension_channels.go @@ -2,7 +2,6 @@ package archiemessaging import ( "context" - "errors" "fmt" "log/slog" "maps" @@ -106,11 +105,7 @@ func openExtensionChannels(ctx context.Context, source extension.Source, secrets if missing := pkg.Descriptor.MissingSettings(setting.Settings); len(missing) > 0 { needs := "Missing " + strings.Join(missing, ", ") log.WarnContext(ctx, "channel extension not started: required settings missing", "channel", pkg.Name, "missing", missing) - instances = append(instances, &channelInstance{ - name: pkg.Name, - needs: needs, - rebuild: func(ResolvedConfig) (channels.Channel, error) { return nil, errors.New(needs) }, - }) + instances = append(instances, &channelInstance{name: pkg.Name, needs: needs}) built[pkg.Name] = true continue } @@ -128,24 +123,14 @@ func openExtensionChannels(ctx context.Context, source extension.Source, secrets continue } built[pkg.Name] = true - instances = append(instances, &channelInstance{ - name: pkg.Name, - channel: ch, - rebuild: func(ResolvedConfig) (channels.Channel, error) { return ch, nil }, - }) + instances = append(instances, &channelInstance{name: pkg.Name, channel: ch}) } if setting := settings[telegramChannel]; setting.Enabled && !slices.ContainsFunc(installed, func(pkg storepkg.Installed) bool { return pkg.Name == telegramChannel }) { // Report it as a channel, so the dashboard shows why the enabled // bot is not running instead of showing nothing. const needs = "The Telegram channel extension is not installed" log.WarnContext(ctx, "telegram is enabled but its channel extension is not installed") - instances = append(instances, &channelInstance{ - name: telegramChannel, - needs: needs, - rebuild: func(ResolvedConfig) (channels.Channel, error) { - return nil, errors.New("telegram channel extension is not installed") - }, - }) + instances = append(instances, &channelInstance{name: telegramChannel, needs: needs}) } go func() { <-ctx.Done() diff --git a/internal/app/archiemessaging/supervise.go b/internal/app/archiemessaging/supervise.go index ccb2f47f6..fa5f181f4 100644 --- a/internal/app/archiemessaging/supervise.go +++ b/internal/app/archiemessaging/supervise.go @@ -7,7 +7,6 @@ import ( "time" "github.com/samcharles93/archie-core/internal/channels" - "github.com/samcharles93/archie-core/internal/channels/status" ) // runChannel supervises one channel for the service's lifetime. It starts the @@ -221,31 +220,9 @@ func (c *channelInstance) supervisorExits() { c.mu.Unlock() } -// restartChannel builds a replacement for channel id from next and starts it in -// place of the running one. A supervisor that is between runs -- backing off a -// failure, or parked after giving up -- is woken to start the replacement; a -// channel with no supervisor (never started, or shut down) is refused. -func (s *Service) restartChannel(id string, next ResolvedConfig) error { - c := s.instanceByID(id) - if c == nil { - return fmt.Errorf("no channel %q", id) - } - if c.rebuild == nil { - return fmt.Errorf("channel %q cannot be rebuilt", id) - } - replacement, err := c.rebuild(next) - if err != nil { - return fmt.Errorf("rebuild %q: %w", id, err) - } - if replacement == nil { - return fmt.Errorf("channel %q has no configuration", id) - } - return s.setChannelState(c, replacement) -} - // setChannelState swaps the channel a supervisor runs; a nil replacement stops // it. It returns once the supervisor has been told, not once the channel is up: -// a caller that needs the observable state awaits it (awaitChannelActive). +// a caller that needs the observable state reads the channel status. func (s *Service) setChannelState(c *channelInstance, replacement channels.Channel) error { c.mu.Lock() if !c.supervised { @@ -275,91 +252,6 @@ func (s *Service) setChannelState(c *channelInstance, replacement channels.Chann return nil } -// enableChannel builds and starts a channel that a settings change turned on, -// and reports only once it is no longer stopped. -func (s *Service) enableChannel(id string, next ResolvedConfig) error { - c := s.instanceByID(id) - if c == nil { - return fmt.Errorf("no channel %q", id) - } - if c.rebuild == nil { - return fmt.Errorf("channel %q cannot be rebuilt", id) - } - replacement, err := c.rebuild(next) - if err != nil { - return fmt.Errorf("build %q: %w", id, err) - } - if replacement == nil { - return fmt.Errorf("channel %q has no configuration", id) - } - if err := s.setChannelState(c, replacement); err != nil { - return err - } - s.status.Declare(id, true, channelReloadable(replacement)) - s.signalPublish() - return s.awaitChannelActive(id, true) -} - -// disableChannel stops a channel that a settings change turned off, and reports -// only once it has stopped. -func (s *Service) disableChannel(id string) error { - c := s.instanceByID(id) - if c == nil || c.current() == nil { - return nil - } - if err := s.setChannelState(c, nil); err != nil { - return err - } - s.status.Declare(id, false, false) - s.signalPublish() - return s.awaitChannelActive(id, false) -} - -// channelApplyTimeout bounds how long reconcile waits for an enable or disable -// to take effect before reporting it unapplied, which leaves the next tick to -// retry it. -const channelApplyTimeout = 5 * time.Second - -// channelApplyPoll is how often that wait re-reads the channel's state. -const channelApplyPoll = 10 * time.Millisecond - -// awaitChannelActive waits, up to channelApplyTimeout, for a channel to leave -// or reach the stopped state, so an enable or disable is reported applied only -// once the channel is actually running (or not) rather than merely queued. A -// failed channel is never active: reporting it so would mark the settings -// version applied and retire a failure the next tick must retry. Only a -// serving state counts, and a failed enable fails fast instead of burning the -// timeout while no restart can succeed without one. -func (s *Service) awaitChannelActive(id string, active bool) error { - deadline := time.Now().Add(channelApplyTimeout) - for { - for _, st := range s.status.Snapshot() { - if st.ID != id { - continue - } - if active && st.State == status.StateFailed { - return fmt.Errorf("channel %q failed to start", id) - } - // Serving counts, impaired or not; anything else is still in - // flight, except a stopped channel answering a disable. - if st.State == status.StateRunning || st.State == status.StateDegraded { - if active { - return nil - } - } else if !active && st.State == status.StateStopped { - return nil - } - } - if time.Now().After(deadline) { - if active { - return fmt.Errorf("channel %q did not start", id) - } - return fmt.Errorf("channel %q did not stop", id) - } - time.Sleep(channelApplyPoll) - } -} - // stopChannel closes one channel's listener with its own bounded context, so a // stop that hangs cannot hold the shutdown past the configured timeout. The // parent context is stripped of its cancellation because this runs on the @@ -376,15 +268,6 @@ func (s *Service) stopChannel(ctx context.Context, name string, ch channels.Chan } } -func (s *Service) instanceByID(id string) *channelInstance { - for _, c := range s.instances() { - if c.name == id { - return c - } - } - return nil -} - func (s *Service) currentConfig() ResolvedConfig { s.mu.Lock() defer s.mu.Unlock() diff --git a/internal/app/archiemessaging/supervise_test.go b/internal/app/archiemessaging/supervise_test.go index 72aec1145..8e41e3530 100644 --- a/internal/app/archiemessaging/supervise_test.go +++ b/internal/app/archiemessaging/supervise_test.go @@ -10,7 +10,6 @@ import ( "time" "github.com/samcharles93/archie-core/internal/channels" - "github.com/samcharles93/archie-core/internal/channels/status" "github.com/samcharles93/archie-core/internal/domain/messaging" ) @@ -57,7 +56,6 @@ func startService(t *testing.T, ch *fakeChannel, retry channelRetryPolicy) *Serv inst := &channelInstance{ name: "fake", channel: ch, - rebuild: func(ResolvedConfig) (channels.Channel, error) { return ch, nil }, } srv, err := compose(context.Background(), deps{Log: slog.Default(), ExtensionChannels: []*channelInstance{inst}}) if err != nil { @@ -93,55 +91,6 @@ func waitStarts(t *testing.T, ch *fakeChannel, want int) { t.Fatalf("channel started %d times, want at least %d", ch.count(), want) } -// TestAwaitChannelActiveStates pins what counts as up: running and degraded -// satisfy an enable, only stopped satisfies a disable, and a failed enable -// fails fast instead of reporting success the next tick would never retry. -func TestAwaitChannelActiveStates(t *testing.T) { - mark := map[string]func(*status.Manager){ - "running": func(m *status.Manager) { m.MarkRunning("fake") }, - "degraded": func(m *status.Manager) { m.MarkDegraded("fake", "slow") }, - "failed": func(m *status.Manager) { m.MarkFailed("fake", "boom") }, - "starting": func(m *status.Manager) { m.MarkStarting("fake") }, - } - // Refusals that wait out the 5s timeout (disable while failed or - // running) are pre-existing behavior, unchanged here, and too slow to - // pin; every case below answers at once. - tests := []struct { - name string - state string - active bool - wantErr bool - }{ - {name: "enable accepts running", state: "running", active: true}, - {name: "enable accepts degraded", state: "degraded", active: true}, - {name: "enable refuses failed", state: "failed", active: true, wantErr: true}, - {name: "disable accepts stopped", state: "", active: false}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - manager := status.NewManager([]status.Descriptor{{ID: "fake"}}) - if tt.state == "" { - manager.MarkStopped("fake", "") - } else { - mark[tt.state](manager) - } - srv := &Service{status: manager} - // Every case above answers at once: success and failed-enable - // refusal never reach the timeout wait. - done := make(chan error, 1) - go func() { done <- srv.awaitChannelActive("fake", tt.active) }() - select { - case err := <-done: - if (err != nil) != tt.wantErr { - t.Fatalf("err = %v, wantErr %v", err, tt.wantErr) - } - case <-time.After(6 * time.Second): - t.Fatal("await did not answer") - } - }) - } -} - // TestChannelSupervisorRetriesAndRestarts pins that a channel that fails on its // own is retried with bounded backoff and, once the budget is spent, parked so // an explicit restart brings it back rather than being refused. @@ -152,7 +101,7 @@ func TestChannelSupervisorRetriesAndRestarts(t *testing.T) { // The supervisor retries the failed run instead of abandoning the channel. waitStarts(t, ch, 3) - if err := srv.restartChannel("fake", ResolvedConfig{}); err != nil { + if err := restart(srv, "fake", ch); err != nil { t.Fatalf("restart after the retry budget was spent: %v", err) } waitStarts(t, ch, 4) @@ -166,7 +115,7 @@ func TestChannelSupervisorRestartReplacesRunningChannel(t *testing.T) { srv := startService(t, ch, channelRetryPolicy{attempts: 3, backoff: time.Hour, maxBackoff: time.Hour}) waitStarts(t, ch, 1) - if err := srv.restartChannel("fake", ResolvedConfig{}); err != nil { + if err := restart(srv, "fake", ch); err != nil { t.Fatalf("restart running channel: %v", err) } waitStarts(t, ch, 2) @@ -180,13 +129,12 @@ func TestChannelRestartRefusedWithoutSupervisor(t *testing.T) { inst := &channelInstance{ name: "fake", channel: ch, - rebuild: func(ResolvedConfig) (channels.Channel, error) { return ch, nil }, } srv, err := compose(context.Background(), deps{Log: slog.Default(), ExtensionChannels: []*channelInstance{inst}}) if err != nil { t.Fatalf("compose: %v", err) } - if err := srv.restartChannel("fake", ResolvedConfig{}); err == nil { + if err := restart(srv, "fake", ch); err == nil { t.Fatal("restart before the service started should be refused") } @@ -203,7 +151,21 @@ func TestChannelRestartRefusedWithoutSupervisor(t *testing.T) { case <-time.After(5 * time.Second): t.Fatal("service did not stop") } - if err := srv.restartChannel("fake", ResolvedConfig{}); err == nil { + if err := restart(srv, "fake", ch); err == nil { t.Fatal("restart after shutdown should be refused") } } + +// restart swaps ch in as the channel id runs, the way a settings change does. +func restart(srv *Service, id string, ch channels.Channel) error { + return srv.setChannelState(instanceByID(srv, id), ch) +} + +func instanceByID(srv *Service, id string) *channelInstance { + for _, c := range srv.instances() { + if c.name == id { + return c + } + } + return nil +} diff --git a/internal/domain/messaging/approval.go b/internal/domain/messaging/approval.go index 366fd2017..d6e704f5d 100644 --- a/internal/domain/messaging/approval.go +++ b/internal/domain/messaging/approval.go @@ -48,13 +48,3 @@ func ApprovalFromContext(ctx context.Context) ApprovalRequester { a, _ := ctx.Value(approvalCtxKey{}).(ApprovalRequester) return a } - -// ApproverOf returns sender's ApprovalRequester when it reports the -// Approval capability and implements the interface. -func ApproverOf(sender any) (ApprovalRequester, bool) { - if !CapabilitiesOf(sender).Approval { - return nil, false - } - approver, ok := sender.(ApprovalRequester) - return approver, ok -} diff --git a/internal/domain/messaging/ephemeral.go b/internal/domain/messaging/ephemeral.go deleted file mode 100644 index b2377bb4d..000000000 --- a/internal/domain/messaging/ephemeral.go +++ /dev/null @@ -1,29 +0,0 @@ -package messaging - -import ( - "context" - "time" -) - -// EphemeralReply is a reply deleted after TTL from a successful send. A -// non-positive TTL is never deleted. -type EphemeralReply struct { - Event MessageEvent - TTL time.Duration -} - -// MessageDeleter deletes a message the sender sent, addressed by the -// MessageEvent the send returned. -type MessageDeleter interface { - DeleteMessage(ctx context.Context, event MessageEvent) error -} - -// DeleterOf returns sender's MessageDeleter when it reports the Delete -// capability and implements the interface. -func DeleterOf(sender any) (MessageDeleter, bool) { - if !CapabilitiesOf(sender).Delete { - return nil, false - } - deleter, ok := sender.(MessageDeleter) - return deleter, ok -} diff --git a/internal/domain/messaging/interactive.go b/internal/domain/messaging/interactive.go index 50aefc9eb..a44ae6b5b 100644 --- a/internal/domain/messaging/interactive.go +++ b/internal/domain/messaging/interactive.go @@ -148,34 +148,8 @@ var ( // string is not an answer to a question, so it must not be mistaken // for one by a caller that only checks err. ErrEmptyReply = errors.New("interactive: reply was empty") - - // ErrTextFallbackNotConfigured is returned when a TextFallback is used - // without both transport halves. It is a construction defect, surfaced - // rather than panicking inside a turn. - ErrTextFallbackNotConfigured = errors.New("interactive: text fallback is missing Send or Reply") ) -// ClarifierOf returns sender's ClarifyRequester when it reports the Clarify -// capability and implements the interface. -func ClarifierOf(sender any) (ClarifyRequester, bool) { - if !CapabilitiesOf(sender).Clarify { - return nil, false - } - clarifier, ok := sender.(ClarifyRequester) - return clarifier, ok -} - -// PickerOf returns sender's PickerRequester only when sender reports the -// Picker capability, with the same capability-over-method-set rule as -// ClarifierOf. -func PickerOf(sender any) (PickerRequester, bool) { - if !CapabilitiesOf(sender).Picker { - return nil, false - } - picker, ok := sender.(PickerRequester) - return picker, ok -} - // Interactive holds the interaction requesters a channel supports for one // turn. The zero value supports none. type Interactive struct { @@ -189,16 +163,6 @@ func (i Interactive) Carries() bool { return i.Clarifier != nil || i.Picker != nil || i.Questioner != nil } -// InteractiveOf resolves sender into the requesters it can carry, trusting the -// capability report over the method set through ClarifierOf and PickerOf. A -// sender that implements a method but denies the capability contributes -// nothing, so a mis-reporting adapter degrades instead of being called. -func InteractiveOf(sender any) Interactive { - clarifier, _ := ClarifierOf(sender) - picker, _ := PickerOf(sender) - return Interactive{Clarifier: clarifier, Picker: picker} -} - type interactiveCtxKey struct{} // WithInteractive stores a channel's interactive requesters on ctx for one @@ -215,21 +179,6 @@ func InteractiveFromContext(ctx context.Context) Interactive { return i } -// FormatClarifyText renders a ClarifyRequest as a plain-text prompt for a -// channel with no native question UI. -func FormatClarifyText(req ClarifyRequest) string { - var b strings.Builder - b.WriteString(strings.TrimSpace(req.Question)) - if len(req.Suggestions) > 0 { - b.WriteString("\n\nSuggestions:") - for i, s := range req.Suggestions { - fmt.Fprintf(&b, "\n%d) %s", i+1, s.Label) - } - } - b.WriteString("\n\nReply with your answer.") - return b.String() -} - // FormatPickerText renders a PickerRequest as a numbered plain-text prompt // for a channel with no native selection UI. func FormatPickerText(req PickerRequest) string { @@ -272,70 +221,3 @@ func ParsePickerReply(req PickerRequest, reply string) (InteractiveChoice, bool) } return InteractiveChoice{}, false } - -// TextFallback asks clarify and picker questions as plain text and reads the -// typed reply. -type TextFallback struct { - Send func(ctx context.Context, text string) error - Reply func(ctx context.Context) (string, error) -} - -// Compile-time guards. -var ( - _ ClarifyRequester = (*TextFallback)(nil) - _ PickerRequester = (*TextFallback)(nil) -) - -// RequestClarification sends the rendered question and returns the user's -// trimmed answer. -func (f *TextFallback) RequestClarification(ctx context.Context, req ClarifyRequest) (string, error) { - if err := f.ready(); err != nil { - return "", err - } - if err := f.Send(ctx, FormatClarifyText(req)); err != nil { - return "", err - } - answer, err := f.Reply(ctx) - if err != nil { - return "", err - } - answer = strings.TrimSpace(answer) - if answer == "" { - return "", ErrEmptyReply - } - return answer, nil -} - -// RequestChoice sends the rendered options and returns the option the user -// selected. A reply that matches no option is an error rather than a -// zero-value guess. -func (f *TextFallback) RequestChoice(ctx context.Context, req PickerRequest) (InteractiveChoice, error) { - if len(req.Options) == 0 { - return InteractiveChoice{}, ErrNoPickerOptions - } - if err := f.ready(); err != nil { - return InteractiveChoice{}, err - } - if err := f.Send(ctx, FormatPickerText(req)); err != nil { - return InteractiveChoice{}, err - } - reply, err := f.Reply(ctx) - if err != nil { - return InteractiveChoice{}, err - } - choice, ok := ParsePickerReply(req, reply) - if !ok { - return InteractiveChoice{}, fmt.Errorf("interactive: reply %q does not match any offered option", strings.TrimSpace(reply)) - } - return choice, nil -} - -// ready reports whether both transport halves are present before any send is -// attempted, so a half-built fallback fails at the call rather than -// mid-interaction. -func (f *TextFallback) ready() error { - if f == nil || f.Send == nil || f.Reply == nil { - return ErrTextFallbackNotConfigured - } - return nil -} diff --git a/internal/domain/messaging/media_sender.go b/internal/domain/messaging/media_sender.go deleted file mode 100644 index cfd26f088..000000000 --- a/internal/domain/messaging/media_sender.go +++ /dev/null @@ -1,51 +0,0 @@ -package messaging - -import "context" - -// SendResult captures the outcome of a platform media delivery. -type SendResult struct { - MessageID string - Success bool - Retryable bool - Error error - ErrorCode string -} - -// AdapterCapabilities reports which optional delivery behaviors a sender -// implements. -type AdapterCapabilities struct { - Media bool - // Delete reports whether the sender can delete messages it sent. - Delete bool - // Clarify reports whether the sender can ask a question and return the - // answer. - Clarify bool - // Picker reports whether the sender can present a single-choice - // selection and carry the chosen option back (PickerRequester), on the - // same native-or-fallback rule as Clarify. - Picker bool - // Approval reports whether the sender renders approval prompts through - // the ApprovalRequester contract, so a caller can know a sender can - // present an approve/deny prompt before a gated action needs one. - Approval bool -} - -// MediaSender delivers a MessageEvent carrying MediaAttachments through a -// platform-specific media API. -type MediaSender interface { - SendMedia(ctx context.Context, event MessageEvent) (SendResult, error) -} - -// CapabilityReporter is the optional interface a sender implements to -// self-report which optional behaviors it supports. -type CapabilityReporter interface { - Capabilities() AdapterCapabilities -} - -// CapabilitiesOf reports which optional behaviors sender supports. -func CapabilitiesOf(sender any) AdapterCapabilities { - if reporter, ok := sender.(CapabilityReporter); ok { - return reporter.Capabilities() - } - return AdapterCapabilities{} -} diff --git a/internal/domain/messaging/message_event.go b/internal/domain/messaging/message_event.go index ad13f40b8..4d65d4e00 100644 --- a/internal/domain/messaging/message_event.go +++ b/internal/domain/messaging/message_event.go @@ -19,35 +19,6 @@ const ( MsgSystem MessageType = "system" ) -// IsMedia reports whether the type carries a media attachment. -func (t MessageType) IsMedia() bool { - switch t { - case MsgImage, MsgVideo, MsgAudio, MsgDocument, MsgSticker: - return true - } - return false -} - -// IsEphemeral reports whether the type is a transient signal. -func (t MessageType) IsEphemeral() bool { - switch t { - case MsgReaction, MsgDeleted: - return true - } - return false -} - -// IsRich reports whether the type requires a MessageEvent with -// structured fields rather than a plain text fallback. -func (t MessageType) IsRich() bool { - switch t { - case MsgText: - return false - default: - return true - } -} - // MessageEvent is the rich message model for gateway channels. type MessageEvent struct { Type MessageType `json:"type"` @@ -67,6 +38,3 @@ type MessageEvent struct { Timestamp int64 `json:"timestamp,omitempty"` Raw map[string]any `json:"raw,omitempty"` } - -// FromID returns the sender identifier. -func (e MessageEvent) FromID() string { return e.SenderID } diff --git a/internal/gateway/adapter_capabilities.go b/internal/gateway/adapter_capabilities.go deleted file mode 100644 index f6f409794..000000000 --- a/internal/gateway/adapter_capabilities.go +++ /dev/null @@ -1,16 +0,0 @@ -package gateway - -import "github.com/samcharles93/archie-core/internal/domain/messaging" - -// SendResult captures the outcome of a platform media delivery. -type SendResult = messaging.SendResult - -// AdapterCapabilities reports which optional delivery behaviors a sender -// implements. -type AdapterCapabilities = messaging.AdapterCapabilities - -// MediaSender delivers a MessageEvent carrying MediaAttachments. -type MediaSender = messaging.MediaSender - -// CapabilityReporter is the optional interface a sender implements. -type CapabilityReporter = messaging.CapabilityReporter diff --git a/internal/gateway/interactive.go b/internal/gateway/interactive.go index 41c0b3413..8f740ce80 100644 --- a/internal/gateway/interactive.go +++ b/internal/gateway/interactive.go @@ -9,47 +9,19 @@ type ( PickerRequest = messaging.PickerRequest ) -// Optional interactive interfaces an adapter may implement. -type ( - ClarifyRequester = messaging.ClarifyRequester - PickerRequester = messaging.PickerRequester -) - // Interactive is the per-turn bundle of requesters a channel adapter can // carry. WithInteractive stores it on a turn's context and // InteractiveFromContext reads it back, so the gateway can offer a question // tool only when the channel can answer it. type Interactive = messaging.Interactive -// InteractiveOf resolves the requesters a channel adapter supports. -// -// WithInteractive / InteractiveFromContext are the context carrier. var ( - InteractiveOf = messaging.InteractiveOf WithInteractive = messaging.WithInteractive InteractiveFromContext = messaging.InteractiveFromContext ) -// TextFallback is the shared text-based degrade. -type TextFallback = messaging.TextFallback - -// Re-exported sentinel errors. -var ( - ErrNoPickerOptions = messaging.ErrNoPickerOptions - ErrEmptyReply = messaging.ErrEmptyReply - ErrTextFallbackNotConfigured = messaging.ErrTextFallbackNotConfigured -) - -// Re-exported capability lookups. -var ( - ClarifierOf = messaging.ClarifierOf - PickerOf = messaging.PickerOf - ApproverOf = messaging.ApproverOf -) - // Re-exported text rendering and parsing helpers. var ( - FormatClarifyText = messaging.FormatClarifyText - FormatPickerText = messaging.FormatPickerText - ParsePickerReply = messaging.ParsePickerReply + FormatPickerText = messaging.FormatPickerText + ParsePickerReply = messaging.ParsePickerReply ) diff --git a/internal/infrastructure/storepkg/catalogue.go b/internal/infrastructure/storepkg/catalogue.go index 92162e421..fce746cad 100644 --- a/internal/infrastructure/storepkg/catalogue.go +++ b/internal/infrastructure/storepkg/catalogue.go @@ -3,12 +3,9 @@ package storepkg import ( "bytes" "context" - "crypto/ed25519" "encoding/json" "fmt" - ocispec "github.com/opencontainers/image-spec/specs-go/v1" - "github.com/samcharles93/archie-core/internal/domain/distribution" domain "github.com/samcharles93/archie-core/internal/domain/storepkg" "github.com/samcharles93/archie-core/internal/infrastructure/signedoci" @@ -51,15 +48,6 @@ func (c OCICatalogue) Fetch(ctx context.Context) (domain.Catalogue, error) { return decodeCatalogue(artifact.Statement) } -// verifyCatalogue checks the layer is the one the manifest names and that the -// key signed it, then decodes it. -func verifyCatalogue(image ocispec.Manifest, layer []byte, key ed25519.PublicKey) (domain.Catalogue, error) { - if err := signedoci.Verify(image, layer, key, SignatureAnnotation); err != nil { - return domain.Catalogue{}, fmt.Errorf("catalogue: %w", err) - } - return decodeCatalogue(layer) -} - // decodeCatalogue decodes a verified catalogue layer. func decodeCatalogue(layer []byte) (domain.Catalogue, error) { decoder := json.NewDecoder(bytes.NewReader(layer)) diff --git a/internal/infrastructure/storepkg/catalogue_test.go b/internal/infrastructure/storepkg/catalogue_test.go index cfa069b18..7eaf52393 100644 --- a/internal/infrastructure/storepkg/catalogue_test.go +++ b/internal/infrastructure/storepkg/catalogue_test.go @@ -5,6 +5,7 @@ import ( "crypto/ed25519" "encoding/base64" "errors" + "fmt" "path/filepath" "testing" @@ -113,3 +114,12 @@ func TestFetchRefusesReplayedCatalogue(t *testing.T) { } const zeros = "0000000000000000000000000000000000000000000000000000000000000000" + +// verifyCatalogue checks, as signedoci.Fetch does, the layer is the one the manifest names and that the +// key signed it, then decodes it. +func verifyCatalogue(image ocispec.Manifest, layer []byte, key ed25519.PublicKey) (domain.Catalogue, error) { + if err := signedoci.Verify(image, layer, key, SignatureAnnotation); err != nil { + return domain.Catalogue{}, fmt.Errorf("catalogue: %w", err) + } + return decodeCatalogue(layer) +} diff --git a/internal/infrastructure/telemetry/telemetry.go b/internal/infrastructure/telemetry/telemetry.go index 6e5f394f9..77bd5fefd 100644 --- a/internal/infrastructure/telemetry/telemetry.go +++ b/internal/infrastructure/telemetry/telemetry.go @@ -158,11 +158,6 @@ func isHealth(path string) bool { return strings.HasPrefix(path, "/health") } -// Transport traces outbound HTTP requests made through base. -func Transport(base http.RoundTripper) http.RoundTripper { - return otelhttp.NewTransport(base) -} - // Routed names the request's server span after the mux pattern that serves // it. Middleware that copies the request hides the pattern from Handler, so // the inner mux reports it itself. diff --git a/internal/releaseupdate/verify.go b/internal/releaseupdate/verify.go index 129e0f460..561706a48 100644 --- a/internal/releaseupdate/verify.go +++ b/internal/releaseupdate/verify.go @@ -76,15 +76,6 @@ func (r Report) Verify(running map[string]string) Verification { return result } -// IsRecordedVersion reports whether version names an actual release rather -// than a placeholder standing in for one. Renderers use it to avoid printing -// a version change like "1.0.0 -> unknown", which reads as a downgrade to a -// release by that name. -func IsRecordedVersion(version string) bool { - _, ok := comparableVersion(version) - return ok -} - // comparableVersion trims whitespace and a leading "v", and reports whether // the version is real. func comparableVersion(version string) (string, bool) { diff --git a/internal/skill/skill.go b/internal/skill/skill.go index bd82389e4..741426260 100644 --- a/internal/skill/skill.go +++ b/internal/skill/skill.go @@ -178,9 +178,6 @@ func SkillForWorkflow(catalog []CatalogEntry, workflow string) *CatalogEntry { const skillsDir = ".agents/skills" -// StoreDir is where root keeps its skills. -func StoreDir(root string) string { return filepath.Join(root, skillsDir) } - // Parse extracts YAML frontmatter and body from SKILL.md content. // The frontmatter is delimited by "---" lines. If no frontmatter is found, // the entire content is returned as the body with a zero Frontmatter. diff --git a/internal/webui/chat_files.go b/internal/webui/chat_files.go index a5dd62af8..826df1e92 100644 --- a/internal/webui/chat_files.go +++ b/internal/webui/chat_files.go @@ -37,9 +37,6 @@ func (c *chatFiles) clock() time.Time { return time.Now() } -// offer registers path and returns the token that downloads it. -func (c *chatFiles) offer(path, name string) string { return c.offerFor(path, name, "") } - func (c *chatFiles) offerFor(path, name, owner string) string { var b [16]byte _, _ = rand.Read(b[:]) diff --git a/internal/webui/chat_files_test.go b/internal/webui/chat_files_test.go index 55b7a7f20..dba14d68c 100644 --- a/internal/webui/chat_files_test.go +++ b/internal/webui/chat_files_test.go @@ -21,7 +21,7 @@ func TestChatFileDownload(t *testing.T) { now := time.Now() srv := newChatAPI(&Server{}) srv.files.now = func() time.Time { return now } - token := srv.files.offer(path, "") + token := srv.files.offerFor(path, "", "") private := srv.files.offerFor(path, "", "alice") tests := []struct {