merge: task_action chat tool (crew/taskact)

This commit is contained in:
sam committed 2026-08-25 02:05:25 +10:00
commit 901864a9df
8 files changed
+779 -31

No files matched your search

+10
View File
@@ -485,6 +485,11 @@ func (b *boot) setupLLMAndChat(ctx context.Context) {
tasks: b.st.TaskByID,
taskLogs: b.taskLogs,
},
ChatTaskActor: chatTaskActorAdapter{
tasks: b.st.TaskByID,
handler: b.web.Handler(),
token: func() string { return b.web.Token },
},
DefaultChatIdentity: b.defaultChatIdentity, SessionStore: b.chatSessionStore,
Bus: b.bus, Log: log,
}
@@ -517,6 +522,11 @@ func (b *boot) setupGateways(ctx context.Context, cfgPath, overlayPath string) b
tasks: b.st.TaskByID,
taskLogs: b.taskLogs,
},
ChatTaskActor: chatTaskActorAdapter{
tasks: b.st.TaskByID,
handler: b.web.Handler(),
token: func() string { return b.web.Token },
},
DefaultChatIdentity: b.defaultChatIdentity, SessionStore: b.chatSessionStore, Updates: b.updateService,
Bus: b.bus,
RegisterRestart: func(request func() error) { b.restartTelegram = request }, Log: log,
+71
View File
@@ -5,6 +5,7 @@
package main
import (
"bytes"
"context"
"crypto/sha256"
"encoding/json"
@@ -13,6 +14,8 @@ import (
"log/slog"
"maps"
"net"
"net/http"
"net/http/httptest"
"os"
"os/signal"
"path/filepath"
@@ -43,6 +46,7 @@ import (
"github.com/samcharles93/archie-core/internal/storage"
"github.com/samcharles93/archie-core/internal/store"
"github.com/samcharles93/archie-core/internal/storerpc"
"github.com/samcharles93/archie-core/internal/taskstate"
"github.com/samcharles93/archie-core/internal/tools"
"github.com/samcharles93/archie-core/internal/tools/mcp"
toolprovider "github.com/samcharles93/archie-core/internal/tools/provider"
@@ -597,6 +601,73 @@ 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.
type chatTaskActorAdapter struct {
tasks func(context.Context, int64) (*store.Task, error)
handler http.Handler
token func() string
}
func (a chatTaskActorAdapter) ApplyChatTaskAction(
ctx context.Context, identity string, taskID int64, action taskstate.Action,
) (gateway.TaskActionResult, error) {
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
}
func chatTaskProfiles(cfg config.Config) ([]gateway.TaskProfile, string) {
if len(cfg.Identities) > 0 {
profiles := make([]gateway.TaskProfile, 0, len(cfg.Identities))
+340
View File
@@ -0,0 +1,340 @@
package main
import (
"context"
"path/filepath"
"strings"
"testing"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/store"
"github.com/samcharles93/archie-core/internal/taskstate"
"github.com/samcharles93/archie-core/internal/webui"
)
func TestChatTaskActorAdapterCrossIdentityRefused(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() })
task, err := st.EnqueueChatTask(ctx, "acme", "widget", "parked job", "", "", "identity-owner")
if err != nil {
t.Fatal(err)
}
if err := st.Transition(ctx, task.ID, store.StatusQueued, store.StatusParked, "needs help"); err != nil {
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 },
}
tests := []struct {
name string
actorIdentity string
action taskstate.Action
}{
{
name: "different identity cannot abandon",
actorIdentity: "identity-attacker",
action: taskstate.ActionAbandon,
},
{
name: "different identity cannot retry",
actorIdentity: "identity-attacker",
action: taskstate.ActionRetry,
},
{
name: "different identity cannot archive",
actorIdentity: "identity-attacker",
action: taskstate.ActionArchive,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
_, err := adapter.ApplyChatTaskAction(ctx, tc.actorIdentity, task.ID, tc.action)
if err == nil {
t.Fatalf("ApplyChatTaskAction() allowed cross-identity action %s by %q on task owned by %q",
tc.action, tc.actorIdentity, task.Identity)
}
if !strings.Contains(err.Error(), "identity-owner") || !strings.Contains(err.Error(), tc.actorIdentity) {
t.Errorf("error = %q, want mention of both identities", err.Error())
}
// Confirm store state was NOT mutated.
current, err := st.TaskByID(ctx, task.ID)
if err != nil || current == nil {
t.Fatalf("TaskByID = (%+v, %v)", current, err)
}
if current.Status != store.StatusParked {
t.Errorf("task status mutated to %q despite cross-identity refusal", current.Status)
}
})
}
}
func TestChatTaskActorAdapterRefusesDisallowedStateAction(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() })
srv := &webui.Server{Store: st, Cfg: config.NewHolder(config.Config{})}
adapter := chatTaskActorAdapter{
tasks: st.TaskByID,
handler: srv.Handler(),
token: func() string { return srv.Token },
}
tests := []struct {
name string
initialStatus string
attemptAction taskstate.Action
}{
{
name: "cannot abandon running task",
initialStatus: store.StatusRunning,
attemptAction: taskstate.ActionAbandon,
},
{
name: "cannot archive parked task",
initialStatus: store.StatusParked,
attemptAction: taskstate.ActionArchive,
},
{
name: "cannot retry queued task",
initialStatus: store.StatusQueued,
attemptAction: taskstate.ActionRetry,
},
{
name: "cannot approve running task",
initialStatus: store.StatusRunning,
attemptAction: taskstate.ActionApprove,
},
{
name: "cannot reject queued task",
initialStatus: store.StatusQueued,
attemptAction: taskstate.ActionReject,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
task, err := st.EnqueueChatTask(ctx, "acme", "widget", "test task", "", "", "archie")
if err != nil {
t.Fatal(err)
}
if tc.initialStatus != store.StatusQueued {
if err := st.Transition(ctx, task.ID, store.StatusQueued, tc.initialStatus, "setup"); err != nil {
t.Fatal(err)
}
}
_, err = adapter.ApplyChatTaskAction(ctx, "archie", task.ID, tc.attemptAction)
if err == nil {
t.Fatalf("expected error attempting %s on %s task, got nil", tc.attemptAction, tc.initialStatus)
}
// Assert error matches taskstate rules.
wantErr := taskstate.CheckAction(tc.initialStatus, tc.attemptAction)
if wantErr != nil && !strings.Contains(err.Error(), wantErr.Error()) {
t.Errorf("error = %q, want substring %q", err.Error(), wantErr.Error())
}
// Ensure task status did not change.
current, err := st.TaskByID(ctx, task.ID)
if err != nil || current == nil {
t.Fatalf("TaskByID = (%+v, %v)", current, err)
}
if current.Status != tc.initialStatus {
t.Errorf("task status changed to %q, want %q", current.Status, tc.initialStatus)
}
})
}
}
func TestChatTaskActorAdapterTaskNotFound(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() })
srv := &webui.Server{Store: st, Cfg: config.NewHolder(config.Config{})}
adapter := chatTaskActorAdapter{
tasks: st.TaskByID,
handler: srv.Handler(),
token: func() string { return srv.Token },
}
_, err = adapter.ApplyChatTaskAction(ctx, "archie", 999999, taskstate.ActionAbandon)
if err == nil {
t.Fatal("expected error for non-existent task, got nil")
}
if !strings.Contains(err.Error(), "not found") {
t.Errorf("error = %q, want 'not found'", err.Error())
}
}
func TestChatTaskActorAdapterAppliesActionsToStore(t *testing.T) {
tests := []struct {
name string
initialStatus string
action taskstate.Action
wantStatus string
wantArchived bool
}{
{
name: "abandon parked task closes it won't do",
initialStatus: store.StatusParked,
action: taskstate.ActionAbandon,
wantStatus: store.StatusClosedWontDo,
},
{
name: "retry parked task requeues it",
initialStatus: store.StatusParked,
action: taskstate.ActionRetry,
wantStatus: store.StatusQueued,
},
{
name: "cancel queued task closes it",
initialStatus: store.StatusQueued,
action: taskstate.ActionCancel,
wantStatus: store.StatusClosedWontDo,
},
{
name: "approve waiting_human task queues it",
initialStatus: store.StatusWaitingHuman,
action: taskstate.ActionApprove,
wantStatus: store.StatusQueued,
},
{
name: "reject waiting_human task closes it",
initialStatus: store.StatusWaitingHuman,
action: taskstate.ActionReject,
wantStatus: store.StatusClosedWontDo,
},
{
name: "archive dead task removes it from store",
initialStatus: store.StatusDead,
action: taskstate.ActionArchive,
wantArchived: true,
},
{
name: "archive closed_wont_do task removes it from store",
initialStatus: store.StatusClosedWontDo,
action: taskstate.ActionArchive,
wantArchived: true,
},
}
for _, tc := range tests {
t.Run(tc.name, func(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() })
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 },
}
task, err := st.EnqueueChatTask(ctx, "acme", "widget", "actionable task", "", "", "archie")
if err != nil {
t.Fatal(err)
}
if tc.initialStatus != store.StatusQueued {
if err := st.Transition(ctx, task.ID, store.StatusQueued, tc.initialStatus, "setup"); err != nil {
t.Fatal(err)
}
}
result, err := adapter.ApplyChatTaskAction(ctx, "archie", task.ID, tc.action)
if err != nil {
t.Fatalf("ApplyChatTaskAction(%s) error = %v", tc.action, err)
}
if result.TaskID != task.ID {
t.Errorf("result.TaskID = %d, want %d", result.TaskID, task.ID)
}
if result.Action != string(tc.action) {
t.Errorf("result.Action = %q, want %q", result.Action, tc.action)
}
current, err := st.TaskByID(ctx, task.ID)
if err != nil {
t.Fatal(err)
}
if tc.wantArchived {
if current != nil {
t.Errorf("task %d still exists in store after archive: %+v", task.ID, current)
}
} else {
if current == nil {
t.Fatalf("task %d not found in store", task.ID)
}
if current.Status != tc.wantStatus {
t.Errorf("task status = %q, want %q", current.Status, tc.wantStatus)
}
}
})
}
}
func TestChatTaskActorAdapterWithTokenAuth(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() })
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)
}
}
+2
View File
@@ -46,6 +46,7 @@ type telegramSetup struct {
ChatController gateway.TaskController
ChatTaskLister gateway.ChatTaskLister
ChatTaskLogs gateway.ChatTaskLogReader
ChatTaskActor gateway.ChatTaskActor
DefaultChatIdentity string
SessionStore gateway.SessionStore
Updates telegram.UpdateService
@@ -301,6 +302,7 @@ func newChatTurnRunner(
TaskLister: s.ChatTaskLister,
Tasks: s.ChatTasks,
TaskLogs: s.ChatTaskLogs,
TaskActor: s.ChatTaskActor,
TaskIdentity: s.DefaultChatIdentity,
Bus: s.Bus,
BotUser: cfg.BotUser,
+265
View File
@@ -0,0 +1,265 @@
package gateway
import (
"context"
"errors"
"fmt"
"strings"
"testing"
"github.com/samcharles93/archie-core/internal/taskstate"
"github.com/samcharles93/archie-core/internal/tools"
)
type fakeActor struct {
result TaskActionResult
err error
gotIdentity string
gotTaskID int64
gotAction taskstate.Action
}
func (f *fakeActor) ApplyChatTaskAction(_ context.Context, identity string, taskID int64, action taskstate.Action) (TaskActionResult, error) {
f.gotIdentity = identity
f.gotTaskID = taskID
f.gotAction = action
return f.result, f.err
}
func TestTaskActionToolProperties(t *testing.T) {
actor := &fakeActor{}
entry := toolNamed(t, TaskTools(nil, nil, nil, actor, "archie"), "task_action")
if err := entry.Validate(); err != nil {
t.Fatalf("entry.Validate() = %v", err)
}
if entry.Name != "task_action" {
t.Errorf("Name = %q, want task_action", entry.Name)
}
if entry.Toolset != "tasks" {
t.Errorf("Toolset = %q, want tasks", entry.Toolset)
}
wantClass := tools.ClassMutating | tools.RequiresApproval
if entry.Classification != wantClass {
t.Errorf("Classification = %v, want %v", entry.Classification, wantClass)
}
if entry.BuildApprovalDescription == nil {
t.Fatal("BuildApprovalDescription is nil, want a description builder for confirmation")
}
}
func TestTaskActionOmittedWhenActorIsNil(t *testing.T) {
entries := TaskTools(&fakeLister{}, &fakeCreator{}, &fakeLogReader{}, nil, "archie")
for _, e := range entries {
if e.Name == "task_action" {
t.Fatal("task_action is present when actor is nil -- a tool that cannot run must not be advertised")
}
}
}
func TestTaskActionAppearsWhenActorIsNonNil(t *testing.T) {
entries := TaskTools(nil, nil, nil, &fakeActor{}, "archie")
toolNamed(t, entries, "task_action") // fails if absent
}
func TestTaskActionUsesBoundIdentity(t *testing.T) {
actor := &fakeActor{result: TaskActionResult{TaskID: 42, Action: "abandon", Message: "abandoned"}}
entry := toolNamed(t, TaskTools(nil, nil, nil, actor, "archie"), "task_action")
_, err := entry.Handler(context.Background(), map[string]any{
"task_id": float64(42),
"action": "abandon",
"identity": "other-identity",
})
if err != nil {
t.Fatal(err)
}
if actor.gotIdentity != "archie" {
t.Errorf("identity = %q, want bound %q", actor.gotIdentity, "archie")
}
}
func TestTaskActionInputValidation(t *testing.T) {
tests := []struct {
name string
input map[string]any
actor *fakeActor
wantErr bool
wantTaskID int64
wantAction taskstate.Action
}{
{
name: "valid float64 task_id",
input: map[string]any{"task_id": float64(10), "action": "abandon"},
actor: &fakeActor{result: TaskActionResult{TaskID: 10, Action: "abandon"}},
wantTaskID: 10,
wantAction: taskstate.ActionAbandon,
},
{
name: "valid int task_id",
input: map[string]any{"task_id": 11, "action": "archive"},
actor: &fakeActor{result: TaskActionResult{TaskID: 11, Action: "archive"}},
wantTaskID: 11,
wantAction: taskstate.ActionArchive,
},
{
name: "valid int64 task_id",
input: map[string]any{"task_id": int64(12), "action": "retry"},
actor: &fakeActor{result: TaskActionResult{TaskID: 12, Action: "retry"}},
wantTaskID: 12,
wantAction: taskstate.ActionRetry,
},
{
name: "normalizes action casing and whitespace",
input: map[string]any{"task_id": float64(13), "action": " ABANDON "},
actor: &fakeActor{result: TaskActionResult{TaskID: 13, Action: "abandon"}},
wantTaskID: 13,
wantAction: taskstate.ActionAbandon,
},
{
name: "missing task_id",
input: map[string]any{"action": "abandon"},
actor: &fakeActor{},
wantErr: true,
},
{
name: "invalid task_id type",
input: map[string]any{"task_id": "not-a-number", "action": "abandon"},
actor: &fakeActor{},
wantErr: true,
},
{
name: "missing action",
input: map[string]any{"task_id": float64(10)},
actor: &fakeActor{},
wantErr: true,
},
{
name: "blank action",
input: map[string]any{"task_id": float64(10), "action": " "},
actor: &fakeActor{},
wantErr: true,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
entry := toolNamed(t, TaskTools(nil, nil, nil, tc.actor, "archie"), "task_action")
out, err := entry.Handler(context.Background(), tc.input)
if tc.wantErr {
if err == nil {
t.Fatalf("Handler(%v) = nil error, want error", tc.input)
}
return
}
if err != nil {
t.Fatalf("Handler(%v) = %v, want nil error", tc.input, err)
}
if tc.actor.gotTaskID != tc.wantTaskID {
t.Errorf("task_id = %d, want %d", tc.actor.gotTaskID, tc.wantTaskID)
}
if tc.actor.gotAction != tc.wantAction {
t.Errorf("action = %q, want %q", tc.actor.gotAction, tc.wantAction)
}
res, ok := out.(TaskActionResult)
if !ok {
t.Fatalf("Handler output = %T, want TaskActionResult", out)
}
if res.TaskID != tc.wantTaskID {
t.Errorf("res.TaskID = %d, want %d", res.TaskID, tc.wantTaskID)
}
})
}
}
func TestTaskActionAllActions(t *testing.T) {
actions := []struct {
action taskstate.Action
input string
}{
{action: taskstate.ActionAbandon, input: "abandon"},
{action: taskstate.ActionArchive, input: "archive"},
{action: taskstate.ActionRetry, input: "retry"},
{action: taskstate.ActionStop, input: "stop"},
{action: taskstate.ActionCancel, input: "cancel"},
{action: taskstate.ActionApprove, input: "approve"},
{action: taskstate.ActionReject, input: "reject"},
}
for _, tc := range actions {
t.Run(string(tc.action), func(t *testing.T) {
actor := &fakeActor{result: TaskActionResult{
TaskID: 99,
Action: string(tc.action),
Message: fmt.Sprintf("Applied %s to task 99.", tc.action),
}}
entry := toolNamed(t, TaskTools(nil, nil, nil, actor, "archie"), "task_action")
out, err := entry.Handler(context.Background(), map[string]any{
"task_id": float64(99),
"action": tc.input,
})
if err != nil {
t.Fatalf("Handler(%s) error = %v", tc.input, err)
}
res, ok := out.(TaskActionResult)
if !ok {
t.Fatalf("Handler output = %T, want TaskActionResult", out)
}
if res.Action != string(tc.action) {
t.Errorf("res.Action = %q, want %q", res.Action, tc.action)
}
})
}
}
func TestTaskActionPropagatesActorError(t *testing.T) {
actor := &fakeActor{err: errors.New("action not available while task is running")}
entry := toolNamed(t, TaskTools(nil, nil, nil, actor, "archie"), "task_action")
_, err := entry.Handler(context.Background(), map[string]any{
"task_id": float64(42),
"action": "abandon",
})
if err == nil {
t.Fatal("expected error, got nil")
}
if !strings.Contains(err.Error(), "action not available while task is running") {
t.Errorf("error = %v, want substring %q", err, "action not available while task is running")
}
}
func TestTaskActionBuildApprovalDescription(t *testing.T) {
tests := []struct {
name string
input map[string]any
want string
}{
{
name: "abandon parked task",
input: map[string]any{"task_id": float64(42), "action": "abandon"},
want: "Apply action \"abandon\" to task 42.",
},
{
name: "archive dead task",
input: map[string]any{"task_id": int64(101), "action": "archive"},
want: "Apply action \"archive\" to task 101.",
},
{
name: "missing fields fallback cleanly",
input: map[string]any{},
want: "Apply action \"\" to task 0.",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
actor := &fakeActor{}
entry := toolNamed(t, TaskTools(nil, nil, nil, actor, "archie"), "task_action")
got := entry.BuildApprovalDescription(tc.input)
if got != tc.want {
t.Errorf("BuildApprovalDescription(%v) = %q, want %q", tc.input, got, tc.want)
}
})
}
}
+71 -12
View File
@@ -6,6 +6,7 @@ import (
"strings"
"time"
"github.com/samcharles93/archie-core/internal/taskstate"
"github.com/samcharles93/archie-core/internal/tools"
)
@@ -55,6 +56,22 @@ type TaskSpawnResult struct {
Message string `json:"message"`
}
// TaskActionResult is what task_action returns.
type TaskActionResult struct {
TaskID int64 `json:"task_id"`
Action string `json:"action"`
Message string `json:"message"`
}
// ChatTaskActor is the mutation surface task_action needs. It mirrors the
// ChatTaskLister pattern: gateway states what it needs and the daemon
// supplies an adapter over the store and runtime, so this package keeps its
// independence from internal/store.
type ChatTaskActor interface {
// ApplyChatTaskAction executes action on taskID, scoped to identity's own tasks.
ApplyChatTaskAction(ctx context.Context, identity string, taskID int64, action taskstate.Action) (TaskActionResult, error)
}
// ChatTaskLogEntry is one log line as task_logs returns it. It mirrors
// internal/logging.Entry's shape without importing that package: gateway
// keeps its independence from internal/logging the same way it already does
@@ -98,24 +115,17 @@ type ChatTaskLogReader interface {
ReadChatTaskLogs(ctx context.Context, identity string, taskID int64, attempt int, q ChatTaskLogQuery) (ChatTaskLogResult, error)
}
// TaskTools builds the chat tools that let Archie see and add to its own work
// TaskTools builds the chat tools that let Archie see, add to, and manage its own work
// queue. Until these existed, /spawn and the task list were slash commands only
// a human could type, so "what are you working on?" had no tool path at all.
//
// Both tools are bound to identity at construction. The model never supplies
// it: a model that could name an identity could read or file work belonging to
// another instance on the same host.
// All tools are bound to identity at construction. The model never supplies
// it: a model that could name an identity could read, mutate or file work
// belonging to another instance on the same host.
//
// A nil backend omits its tool rather than registering one that always fails,
// so a daemon without chat task support advertises nothing.
//
// Deliberately absent: task_approve and task_cancel. waiting_human is the one
// point in the task lifecycle where a person must act, and /approve is that
// gate. The text reaching a chat turn is untrusted -- a forge issue body or an
// inbound email can be quoted into it -- so a tool that approves Archie's own
// work would remove the only human checkpoint in the lifecycle. Cancel is
// destructive on the same untrusted path. Both remain slash commands.
func TaskTools(lister ChatTaskLister, creator TaskCreator, logs ChatTaskLogReader, identity string) []tools.ToolEntry {
func TaskTools(lister ChatTaskLister, creator TaskCreator, logs ChatTaskLogReader, actor ChatTaskActor, identity string) []tools.ToolEntry {
var entries []tools.ToolEntry
if lister != nil {
entries = append(entries, taskListTool(lister, identity))
@@ -126,6 +136,9 @@ func TaskTools(lister ChatTaskLister, creator TaskCreator, logs ChatTaskLogReade
if logs != nil {
entries = append(entries, taskLogsTool(logs, identity))
}
if actor != nil {
entries = append(entries, taskActionTool(actor, identity))
}
return entries
}
@@ -228,6 +241,52 @@ func taskSpawnTool(creator TaskCreator, identity string) tools.ToolEntry {
}
}
func taskActionTool(actor ChatTaskActor, identity string) tools.ToolEntry {
return tools.ToolEntry{
Name: "task_action",
Toolset: "tasks",
Description: "Perform an operator action on a task (e.g. abandon, archive, retry, stop, cancel, approve, reject). " +
"Use it when the user asks to close, abandon, archive, retry, stop or approve a task.",
Classification: tools.ClassMutating | tools.RequiresApproval,
BuildApprovalDescription: func(input map[string]any) string {
action := strings.TrimSpace(asString(input["action"]))
taskID, _ := asInt64(input["task_id"])
return fmt.Sprintf("Apply action %q to task %d.", action, taskID)
},
Schema: tools.JSONSchema{
"type": "object",
"properties": map[string]any{
"task_id": map[string]any{
"type": "integer",
"description": "ID of the task to act on.",
},
"action": map[string]any{
"type": "string",
"description": "The action to perform: abandon, archive, retry, stop, cancel, approve, reject.",
},
},
"required": []any{"task_id", "action"},
},
Handler: func(ctx context.Context, input map[string]any) (any, error) {
taskID, ok := asInt64(input["task_id"])
if !ok {
return nil, fmt.Errorf("task_action: task_id is required")
}
actionStr := strings.TrimSpace(strings.ToLower(asString(input["action"])))
if actionStr == "" {
return nil, fmt.Errorf("task_action: action is required")
}
// The bound identity, never input["identity"].
result, err := actor.ApplyChatTaskAction(ctx, identity, taskID, taskstate.Action(actionStr))
if err != nil {
return nil, fmt.Errorf("task_action: %w", err)
}
return result, nil
},
}
}
func taskLogsTool(reader ChatTaskLogReader, identity string) tools.ToolEntry {
return tools.ToolEntry{
Name: "task_logs",
+18 -18
View File
@@ -48,7 +48,7 @@ func toolNamed(t *testing.T, entries []tools.ToolEntry, name string) tools.ToolE
}
func TestTaskToolsValidate(t *testing.T) {
entries := TaskTools(&fakeLister{}, &fakeCreator{}, nil, "archie")
entries := TaskTools(&fakeLister{}, &fakeCreator{}, nil, nil, "archie")
if len(entries) == 0 {
t.Fatal("TaskTools() returned nothing")
}
@@ -76,7 +76,7 @@ func TestTaskToolsOmitNilBackends(t *testing.T) {
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
entries := TaskTools(tc.lister, tc.creator, nil, "archie")
entries := TaskTools(tc.lister, tc.creator, nil, nil, "archie")
var got []string
for _, e := range entries {
got = append(got, e.Name)
@@ -93,7 +93,7 @@ func TestTaskToolsOmitNilBackends(t *testing.T) {
// that could name an identity could read another instance's work.
func TestTaskListUsesBoundIdentity(t *testing.T) {
lister := &fakeLister{tasks: []ChatTaskSummary{{ID: 7, Title: "wire the thing", Status: "running"}}}
entry := toolNamed(t, TaskTools(lister, nil, nil, "archie"), "task_list")
entry := toolNamed(t, TaskTools(lister, nil, nil, nil, "archie"), "task_list")
// The model supplies an identity; it must be ignored.
if _, err := entry.Handler(context.Background(), map[string]any{"identity": "someone-else"}); err != nil {
@@ -120,7 +120,7 @@ func TestTaskListLimit(t *testing.T) {
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
lister := &fakeLister{}
entry := toolNamed(t, TaskTools(lister, nil, nil, "archie"), "task_list")
entry := toolNamed(t, TaskTools(lister, nil, nil, nil, "archie"), "task_list")
if _, err := entry.Handler(context.Background(), tc.input); err != nil {
t.Fatal(err)
}
@@ -137,7 +137,7 @@ func TestTaskListFiltersByStatus(t *testing.T) {
{ID: 2, Status: "queued"},
{ID: 3, Status: "running"},
}}
entry := toolNamed(t, TaskTools(lister, nil, nil, "archie"), "task_list")
entry := toolNamed(t, TaskTools(lister, nil, nil, nil, "archie"), "task_list")
out, err := entry.Handler(context.Background(), map[string]any{"status": "running"})
if err != nil {
@@ -160,7 +160,7 @@ func TestTaskListFiltersByStatus(t *testing.T) {
// TestTaskListEmptyIsNotAnError guards against the model reading an empty
// queue as a broken tool and retrying.
func TestTaskListEmptyIsNotAnError(t *testing.T) {
entry := toolNamed(t, TaskTools(&fakeLister{}, nil, nil, "archie"), "task_list")
entry := toolNamed(t, TaskTools(&fakeLister{}, nil, nil, nil, "archie"), "task_list")
out, err := entry.Handler(context.Background(), map[string]any{})
if err != nil {
@@ -177,7 +177,7 @@ func TestTaskListEmptyIsNotAnError(t *testing.T) {
func TestTaskListPropagatesStoreError(t *testing.T) {
lister := &fakeLister{err: errors.New("database is gone")}
entry := toolNamed(t, TaskTools(lister, nil, nil, "archie"), "task_list")
entry := toolNamed(t, TaskTools(lister, nil, nil, nil, "archie"), "task_list")
if _, err := entry.Handler(context.Background(), map[string]any{}); err == nil {
t.Fatal("handler error = nil, want the store failure surfaced")
@@ -228,7 +228,7 @@ func TestTaskSpawn(t *testing.T) {
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
entry := toolNamed(t, TaskTools(nil, tc.creator, nil, "archie"), "task_spawn")
entry := toolNamed(t, TaskTools(nil, tc.creator, nil, nil, "archie"), "task_spawn")
out, err := entry.Handler(context.Background(), tc.input)
if tc.wantErr {
if err == nil {
@@ -264,7 +264,7 @@ func TestTaskSpawn(t *testing.T) {
// model must not be able to file work under another instance's identity.
func TestTaskSpawnIgnoresModelIdentity(t *testing.T) {
creator := &fakeCreator{id: 1}
entry := toolNamed(t, TaskTools(nil, creator, nil, "archie"), "task_spawn")
entry := toolNamed(t, TaskTools(nil, creator, nil, nil, "archie"), "task_spawn")
if _, err := entry.Handler(context.Background(), map[string]any{
"title": "sneaky",
@@ -282,7 +282,7 @@ func TestTaskSpawnIgnoresModelIdentity(t *testing.T) {
// an untrusted input path. If these are ever added they must be a considered
// decision, not an accident.
func TestTaskToolsExcludeApprovalTools(t *testing.T) {
entries := TaskTools(&fakeLister{}, &fakeCreator{}, nil, "archie")
entries := TaskTools(&fakeLister{}, &fakeCreator{}, nil, nil, "archie")
for _, e := range entries {
switch e.Name {
case "task_approve", "task_cancel":
@@ -313,7 +313,7 @@ func (f *fakeLogReader) ReadChatTaskLogs(_ context.Context, identity string, tas
func TestTaskLogsUsesBoundIdentity(t *testing.T) {
reader := &fakeLogReader{result: ChatTaskLogResult{Attempt: 1}}
entry := toolNamed(t, TaskTools(nil, nil, reader, "archie"), "task_logs")
entry := toolNamed(t, TaskTools(nil, nil, reader, nil, "archie"), "task_logs")
if _, err := entry.Handler(context.Background(), map[string]any{
"task_id": float64(7), "identity": "someone-else",
@@ -327,7 +327,7 @@ func TestTaskLogsUsesBoundIdentity(t *testing.T) {
func TestTaskLogsRequiresTaskID(t *testing.T) {
reader := &fakeLogReader{}
entry := toolNamed(t, TaskTools(nil, nil, reader, "archie"), "task_logs")
entry := toolNamed(t, TaskTools(nil, nil, reader, nil, "archie"), "task_logs")
if _, err := entry.Handler(context.Background(), map[string]any{}); err == nil {
t.Error("expected error for missing task_id, got nil")
@@ -336,7 +336,7 @@ func TestTaskLogsRequiresTaskID(t *testing.T) {
func TestTaskLogsDefaultsAttemptToZero(t *testing.T) {
reader := &fakeLogReader{result: ChatTaskLogResult{Attempt: 0}}
entry := toolNamed(t, TaskTools(nil, nil, reader, "archie"), "task_logs")
entry := toolNamed(t, TaskTools(nil, nil, reader, nil, "archie"), "task_logs")
if _, err := entry.Handler(context.Background(), map[string]any{
"task_id": float64(7),
@@ -350,7 +350,7 @@ func TestTaskLogsDefaultsAttemptToZero(t *testing.T) {
func TestTaskLogsHonoursExplicitAttempt(t *testing.T) {
reader := &fakeLogReader{result: ChatTaskLogResult{Attempt: 2}}
entry := toolNamed(t, TaskTools(nil, nil, reader, "archie"), "task_logs")
entry := toolNamed(t, TaskTools(nil, nil, reader, nil, "archie"), "task_logs")
if _, err := entry.Handler(context.Background(), map[string]any{
"task_id": float64(7), "attempt": float64(2),
@@ -377,7 +377,7 @@ func TestTaskLogsLimit(t *testing.T) {
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
reader := &fakeLogReader{result: ChatTaskLogResult{}}
entry := toolNamed(t, TaskTools(nil, nil, reader, "archie"), "task_logs")
entry := toolNamed(t, TaskTools(nil, nil, reader, nil, "archie"), "task_logs")
if _, err := entry.Handler(context.Background(), tc.input); err != nil {
t.Fatal(err)
}
@@ -390,7 +390,7 @@ func TestTaskLogsLimit(t *testing.T) {
func TestTaskLogsForwardsComponentAndContains(t *testing.T) {
reader := &fakeLogReader{result: ChatTaskLogResult{}}
entry := toolNamed(t, TaskTools(nil, nil, reader, "archie"), "task_logs")
entry := toolNamed(t, TaskTools(nil, nil, reader, nil, "archie"), "task_logs")
if _, err := entry.Handler(context.Background(), map[string]any{
"task_id": float64(7), "component": "gate", "q": "build failed",
@@ -406,7 +406,7 @@ func TestTaskLogsForwardsComponentAndContains(t *testing.T) {
}
func TestTaskLogsOmittedWhenReaderIsNil(t *testing.T) {
entries := TaskTools(&fakeLister{}, &fakeCreator{}, nil, "archie")
entries := TaskTools(&fakeLister{}, &fakeCreator{}, nil, nil, "archie")
for _, e := range entries {
if e.Name == "task_logs" {
t.Fatal("task_logs is in the tool set when reader is nil -- a tool that always fails must not be advertised")
@@ -415,6 +415,6 @@ func TestTaskLogsOmittedWhenReaderIsNil(t *testing.T) {
}
func TestTaskLogsAppearsWhenReaderIsNonNil(t *testing.T) {
entries := TaskTools(nil, nil, &fakeLogReader{}, "archie")
entries := TaskTools(nil, nil, &fakeLogReader{}, nil, "archie")
toolNamed(t, entries, "task_logs") // fails the test if absent
}
+2 -1
View File
@@ -75,6 +75,7 @@ type TurnRunnerConfig struct {
TaskLister ChatTaskLister
Tasks TaskCreator
TaskLogs ChatTaskLogReader
TaskActor ChatTaskActor
TaskIdentity string
Bus TurnEventPublisher
BotUser string
@@ -247,7 +248,7 @@ func (r *TurnRunner) Run(ctx context.Context, msg Message, stream TurnStream) (s
compressed := compressTurnHistory(history, r.BotUser)
extraTools := append(
TaskTools(r.TaskLister, r.Tasks, r.TaskLogs, r.TaskIdentity),
TaskTools(r.TaskLister, r.Tasks, r.TaskLogs, r.TaskActor, r.TaskIdentity),
SessionTools(r.Sessions, r.Router.SessionTracker(), r.Channel, msg)...,
)
modelName := r.Models.ActiveModel()