feat(telegram): /stop stops the chat agent, else the tasks it created, or one task; delete the dead approval actions
This commit is contained in:
1 parent
399098329b
commit
b0f1ad7cdc
52 files changed
+2385
-2781
No files matched your search
@@ -255,6 +255,6 @@ func (b *server) setupGatewayChat(ctx context.Context, actor gateway.ChatTaskAct
|
||||
router.Log = b.log
|
||||
return &gateway.LocalChatAdapter{
|
||||
Router: router, Sessions: b.chatSessionStore, Turns: gateway.NewTurns(b.log),
|
||||
Models: b.chatModels, Personas: b.personas, TaskActor: actor,
|
||||
Models: b.chatModels, Personas: b.personas, TaskActor: actor, Tasks: b.stateStore,
|
||||
}, nil
|
||||
}
|
||||
@@ -15,17 +15,17 @@ import (
|
||||
type Writer struct {
|
||||
Enqueue func(
|
||||
ctx context.Context,
|
||||
owner, repo, title, body, workflow, identity string,
|
||||
owner, repo, title, body, workflow, identity, origin string,
|
||||
inputs map[string]any,
|
||||
) (*workflow.Task, error)
|
||||
}
|
||||
|
||||
func (a Writer) EnqueueChatTask(
|
||||
ctx context.Context,
|
||||
owner, repo, title, body, workflow, identity string,
|
||||
owner, repo, title, body, workflow, identity, origin string,
|
||||
inputs map[string]any,
|
||||
) (int64, error) {
|
||||
task, err := a.Enqueue(ctx, owner, repo, title, body, workflow, identity, inputs)
|
||||
task, err := a.Enqueue(ctx, owner, repo, title, body, workflow, identity, origin, inputs)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -14,7 +16,7 @@ import (
|
||||
|
||||
// approvalCallbackPrefix separates tool-approval callbacks from other
|
||||
// callback types handled in defaultHandler. It is deliberately distinct
|
||||
// from dangerousCmdPrefix so the two approval systems never collide.
|
||||
// from every other callback prefix.
|
||||
const approvalCallbackPrefix = "approval:"
|
||||
|
||||
// telegramApprover implements gateway.ApprovalRequester with an inline-button
|
||||
@@ -28,8 +30,7 @@ type telegramApprover struct {
|
||||
}
|
||||
|
||||
// pendingApproval records a tool-approval request waiting on a human
|
||||
// decision. It is the tool-approval analogue of dangerousAction, kept
|
||||
// separate so the dangerous-command model (onApprove callbacks) and the
|
||||
// decision. It is kept separate so the
|
||||
// tool-approval model (result channels) cannot entangle.
|
||||
type pendingApproval struct {
|
||||
token string
|
||||
@@ -84,7 +85,7 @@ func (a *telegramApprover) RequestApproval(ctx context.Context, action, descript
|
||||
return messaging.ApprovalPermanentlyApproved, nil
|
||||
}
|
||||
|
||||
token := makeDangerousToken()
|
||||
token := makeCallbackToken()
|
||||
resultCh := make(chan approvalResult, 1)
|
||||
a.gw.registerPendingApproval(pendingApproval{
|
||||
token: token,
|
||||
@@ -156,7 +157,7 @@ func (a *telegramApprover) applyApprovalDecision(action, description string, res
|
||||
|
||||
// approvalKeyboard builds the three-button inline keyboard for a tool
|
||||
// approval: "Approve this time", "Approve Permanently", "Deny". It mirrors
|
||||
// dangerousKeyboard but carries the approval: callback prefix.
|
||||
// the approval: callback prefix.
|
||||
func (g *Gateway) approvalKeyboard(token string) *models.InlineKeyboardMarkup {
|
||||
return &models.InlineKeyboardMarkup{
|
||||
InlineKeyboard: [][]models.InlineKeyboardButton{
|
||||
@@ -228,19 +229,19 @@ func (g *Gateway) handleApprovalCallback(ctx context.Context, b *bot.Bot, update
|
||||
}
|
||||
if !g.isSenderAllowed(query.From.ID) {
|
||||
g.log.Warn("approval callback from unauthorized sender", "user_id", query.From.ID)
|
||||
g.answerDangerousCallback(ctx, b, query.ID, "You are not authorised to use this bot.", true)
|
||||
g.answerCallback(ctx, b, query.ID, "You are not authorised to use this bot.", true)
|
||||
return
|
||||
}
|
||||
|
||||
decision, token := parseApprovalCallback(query.Data)
|
||||
if decision == "" {
|
||||
g.answerDangerousCallback(ctx, b, query.ID, "That action is no longer valid.", true)
|
||||
g.answerCallback(ctx, b, query.ID, "That action is no longer valid.", true)
|
||||
return
|
||||
}
|
||||
|
||||
pa, ok := g.consumePendingApproval(token, query.From.ID)
|
||||
if !ok {
|
||||
g.answerDangerousCallback(ctx, b, query.ID, "That action is no longer valid.", true)
|
||||
g.answerCallback(ctx, b, query.ID, "That action is no longer valid.", true)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -253,16 +254,16 @@ func (g *Gateway) handleApprovalCallback(ctx context.Context, b *bot.Bot, update
|
||||
switch decision {
|
||||
case "approve":
|
||||
pa.resultCh <- approvalResult{decision: messaging.ApprovalApproved}
|
||||
g.answerDangerousCallback(ctx, b, query.ID, "Approved and executed.", false)
|
||||
g.editDangerousMessage(ctx, b, query, "✅ Approved: "+pa.description)
|
||||
g.answerCallback(ctx, b, query.ID, "Approved and executed.", false)
|
||||
g.editCallbackMessage(ctx, b, query, "✅ Approved: "+pa.description)
|
||||
case "permanent":
|
||||
pa.resultCh <- approvalResult{decision: messaging.ApprovalPermanentlyApproved}
|
||||
g.answerDangerousCallback(ctx, b, query.ID, "Permanently approved (valid 24h).", false)
|
||||
g.editDangerousMessage(ctx, b, query, "✅ Approved (permanent, 24h): "+pa.description)
|
||||
g.answerCallback(ctx, b, query.ID, "Permanently approved (valid 24h).", false)
|
||||
g.editCallbackMessage(ctx, b, query, "✅ Approved (permanent, 24h): "+pa.description)
|
||||
case "deny":
|
||||
pa.resultCh <- approvalResult{decision: messaging.ApprovalDenied, err: messaging.ErrApprovalDenied}
|
||||
g.answerDangerousCallback(ctx, b, query.ID, "Action denied.", false)
|
||||
g.editDangerousMessage(ctx, b, query, "❌ Denied: "+pa.description)
|
||||
g.answerCallback(ctx, b, query.ID, "Action denied.", false)
|
||||
g.editCallbackMessage(ctx, b, query, "❌ Denied: "+pa.description)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -290,3 +291,79 @@ func approvalPromptText(action, description string) string {
|
||||
action, description, minutes,
|
||||
)
|
||||
}
|
||||
|
||||
// answerCallback is the common acknowledge/shake response.
|
||||
func (g *Gateway) answerCallback(ctx context.Context, b *bot.Bot, queryID, text string, alert bool) {
|
||||
if _, err := b.AnswerCallbackQuery(ctx, &bot.AnswerCallbackQueryParams{
|
||||
CallbackQueryID: queryID,
|
||||
Text: text,
|
||||
ShowAlert: alert,
|
||||
}); err != nil {
|
||||
g.log.Warn("answer callback failed", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (g *Gateway) editCallbackMessage(ctx context.Context, b *bot.Bot, query *models.CallbackQuery, text string) {
|
||||
if query.Message.Message == nil {
|
||||
return
|
||||
}
|
||||
message := query.Message.Message
|
||||
if _, err := b.EditMessageText(ctx, &bot.EditMessageTextParams{
|
||||
ChatID: message.Chat.ID,
|
||||
MessageID: message.ID,
|
||||
Text: text,
|
||||
}); err != nil {
|
||||
g.log.Warn("edit callback message failed", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func makeCallbackToken() string {
|
||||
bytes := make([]byte, 16)
|
||||
if _, err := rand.Read(bytes); err != nil {
|
||||
panic("crypto/rand: " + err.Error())
|
||||
}
|
||||
return hex.EncodeToString(bytes)
|
||||
}
|
||||
|
||||
// permanentApproval records a human's decision to approve one tool for 24
|
||||
// hours. Scope and lifetime are explicit.
|
||||
type permanentApproval struct {
|
||||
Pattern string
|
||||
Recipient int64
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
func (g *Gateway) recordPermanentApproval(recipient int64, pattern string) {
|
||||
g.permanentMu.Lock()
|
||||
defer g.permanentMu.Unlock()
|
||||
g.permanentApprovals = append(g.livePermanentApprovals(), permanentApproval{
|
||||
Pattern: pattern, Recipient: recipient, ExpiresAt: time.Now().Add(24 * time.Hour),
|
||||
})
|
||||
g.log.Info("tool permanently approved for 24h", "tool", pattern, "recipient", recipient)
|
||||
}
|
||||
|
||||
// hasPermanentApprovalExact reports whether recipient approved pattern within
|
||||
// the last 24 hours.
|
||||
func (g *Gateway) hasPermanentApprovalExact(recipient int64, pattern string) bool {
|
||||
g.permanentMu.Lock()
|
||||
defer g.permanentMu.Unlock()
|
||||
g.permanentApprovals = g.livePermanentApprovals()
|
||||
for _, pa := range g.permanentApprovals {
|
||||
if pa.Recipient == recipient && pa.Pattern == pattern {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// livePermanentApprovals drops expired approvals. permanentMu must be held.
|
||||
func (g *Gateway) livePermanentApprovals() []permanentApproval {
|
||||
now := time.Now()
|
||||
kept := g.permanentApprovals[:0]
|
||||
for _, pa := range g.permanentApprovals {
|
||||
if pa.ExpiresAt.After(now) {
|
||||
kept = append(kept, pa)
|
||||
}
|
||||
}
|
||||
return kept
|
||||
}
|
||||
@@ -28,9 +28,6 @@ var gatewayCommandSpecs = []commandSpec{
|
||||
{Command: "spawn", Description: "Create a tracked task", Usage: "/spawn [identity=name] [repo=owner/name] [workflow=name] <title>"},
|
||||
{Command: "settings", Description: "Inspect or change runtime settings", Usage: "/settings [list|get <kind>|set <kind> <field>=<value> ...]"},
|
||||
{Command: "cancel", Description: "Cancel a queued or waiting task", Usage: "/cancel [identity=name] <task-id>"},
|
||||
// On Telegram, /approve and /deny decide pending dangerous commands.
|
||||
{Command: "approve", Description: "Show pending dangerous commands to approve", Usage: "/approve"},
|
||||
{Command: "deny", Description: "Show pending dangerous commands to deny", Usage: "/deny"},
|
||||
{Command: "start", Description: "Confirm that Archie is running", Usage: "/start"},
|
||||
{Command: "new", Description: "Start a fresh session, clearing conversation history", Usage: "/new [title]"},
|
||||
{Command: "reset", Description: "Alias for /new", Usage: "/reset [title]"},
|
||||
@@ -48,8 +45,7 @@ var gatewayCommandSpecs = []commandSpec{
|
||||
{Command: "resume", Description: "Switch to a session by id or unique prefix", Usage: "/resume <session-id>"},
|
||||
{Command: "delete", Description: "Permanently delete a session and its history", Usage: "/delete <session-id>"},
|
||||
{Command: "agents", Description: "List tasks currently being worked", Usage: "/agents"},
|
||||
{Command: "rollback", Description: "Restore a filesystem checkpoint", Usage: "/rollback [number]"},
|
||||
{Command: "stop", Description: "Terminate a background process", Usage: "/stop <process-name>"},
|
||||
{Command: "stop", Description: "Stop the running reply, else this chat's tasks; or one task", Usage: "/stop [task-id]"},
|
||||
{Command: "restart", Description: "Reload Archie and its configuration", Usage: "/restart"},
|
||||
{Command: "help", Description: "See what Archie can do", Usage: "/help"},
|
||||
}
|
||||
|
||||
@@ -1,618 +0,0 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-telegram/bot"
|
||||
"github.com/go-telegram/bot/models"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
// These aliases keep Telegram's public configuration surface source
|
||||
// compatible while making the authority contract reusable by other
|
||||
// interactive adapters such as the Web UI.
|
||||
type (
|
||||
DangerousCommandAuthority = messaging.DangerousCommandAuthority
|
||||
CheckpointInfo = messaging.CheckpointInfo
|
||||
)
|
||||
|
||||
// ── dangerous command approval system ─────────────────────────────
|
||||
|
||||
// dangerousCmdPrefix separates dangerous-command callbacks from other
|
||||
// callback types handled in defaultHandler.
|
||||
const dangerousCmdPrefix = "dangerous:"
|
||||
|
||||
// dangerousAction records a pending command a human must approve or deny.
|
||||
// It mirrors the updateAction pattern: random token, recipient-bound,
|
||||
// expiring, single-use, and carrying a hash so a changed command cannot
|
||||
// reuse the callback.
|
||||
type dangerousAction struct {
|
||||
id string // random token
|
||||
command string // the full command text
|
||||
commandHash string // sha256(command) — prevents changed-command replay
|
||||
description string // human-readable label shown to the approver
|
||||
recipient int64 // Telegram user who may approve
|
||||
createdAt time.Time
|
||||
expiresAt time.Time
|
||||
// onApprove is the function to call when approved. The Gateway
|
||||
// supplies this when registering the pending command so the
|
||||
// authority stays out of the Telegram callback path.
|
||||
onApprove func(ctx context.Context) (string, error)
|
||||
}
|
||||
|
||||
// permanentApproval records a decision to approve a category of dangerous
|
||||
// commands permanently. Scope and lifetime are explicit.
|
||||
type permanentApproval struct {
|
||||
// CommandPattern is a prefix match against the command text, e.g.
|
||||
// "/rollback", "/stop", or a tool name.
|
||||
CommandPattern string
|
||||
Recipient int64
|
||||
GrantedAt time.Time
|
||||
ExpiresAt time.Time
|
||||
// Scope describes the approval boundary for audit purposes.
|
||||
Scope string
|
||||
}
|
||||
|
||||
// ── Gateway methods ──────────────────────────────────────────────
|
||||
|
||||
// registerDangerousAction stores a pending command and returns a callback
|
||||
// token. The caller must present the action to the user (via an inline
|
||||
// keyboard) immediately after registering.
|
||||
func (g *Gateway) registerDangerousAction(
|
||||
command, description string,
|
||||
recipient int64,
|
||||
onApprove func(ctx context.Context) (string, error),
|
||||
) string {
|
||||
token := makeDangerousToken()
|
||||
sum := sha256.Sum256([]byte(command))
|
||||
hash := hex.EncodeToString(sum[:])
|
||||
|
||||
g.dangerousMu.Lock()
|
||||
defer g.dangerousMu.Unlock()
|
||||
|
||||
now := time.Now()
|
||||
// Expire tokens older than maxPendingAge.
|
||||
maxPendingAge := 10 * time.Minute
|
||||
for key, action := range g.dangerousActions {
|
||||
if !action.expiresAt.After(now) {
|
||||
delete(g.dangerousActions, key)
|
||||
}
|
||||
}
|
||||
g.dangerousActions[token] = dangerousAction{
|
||||
id: token,
|
||||
command: command,
|
||||
commandHash: hash,
|
||||
description: description,
|
||||
recipient: recipient,
|
||||
createdAt: now,
|
||||
expiresAt: now.Add(maxPendingAge),
|
||||
onApprove: onApprove,
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
// dangerousKeyboard builds the three-button inline keyboard for a
|
||||
// dangerous command: "Approve this time", "Approve Permanently", "Deny".
|
||||
func (g *Gateway) dangerousKeyboard(token string) *models.InlineKeyboardMarkup {
|
||||
return &models.InlineKeyboardMarkup{
|
||||
InlineKeyboard: [][]models.InlineKeyboardButton{
|
||||
{
|
||||
{
|
||||
Text: "Approve this time",
|
||||
CallbackData: dangerousCmdPrefix + "approve:" + token,
|
||||
},
|
||||
},
|
||||
{
|
||||
{
|
||||
Text: "Approve Permanently",
|
||||
CallbackData: dangerousCmdPrefix + "permanent:" + token,
|
||||
},
|
||||
},
|
||||
{
|
||||
{
|
||||
Text: "Deny",
|
||||
CallbackData: dangerousCmdPrefix + "deny:" + token,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// answerDangerousCallback is the common acknowledge/shake response.
|
||||
func (g *Gateway) answerDangerousCallback(ctx context.Context, b *bot.Bot, queryID, text string, alert bool) {
|
||||
if _, err := b.AnswerCallbackQuery(ctx, &bot.AnswerCallbackQueryParams{
|
||||
CallbackQueryID: queryID,
|
||||
Text: text,
|
||||
ShowAlert: alert,
|
||||
}); err != nil {
|
||||
g.log.Warn("answer dangerous callback failed", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
// handleDangerousCallback is the entrypoint for all dangerous-command
|
||||
// inline-button taps. It validates the token (recipient, expiry, replay,
|
||||
// hash), records an audit event, and executes or rejects the command.
|
||||
func (g *Gateway) handleDangerousCallback(ctx context.Context, b *bot.Bot, update *models.Update) {
|
||||
query := update.CallbackQuery
|
||||
if query == nil {
|
||||
return
|
||||
}
|
||||
if !g.isSenderAllowed(query.From.ID) {
|
||||
g.log.Warn("dangerous callback from unauthorized sender", "user_id", query.From.ID)
|
||||
g.answerDangerousCallback(ctx, b, query.ID, "You are not authorised to use this bot.", true)
|
||||
return
|
||||
}
|
||||
|
||||
action, ok := g.consumeDangerousAction(query)
|
||||
if !ok {
|
||||
g.answerDangerousCallback(ctx, b, query.ID, "That action is no longer valid.", true)
|
||||
return
|
||||
}
|
||||
|
||||
decision, _ := parseDangerousCallback(query.Data)
|
||||
g.log.Info(
|
||||
"dangerous command decision",
|
||||
"command", action.command, "decision", decision,
|
||||
"recipient", query.From.ID, "username", query.From.Username,
|
||||
)
|
||||
|
||||
switch decision {
|
||||
case "deny":
|
||||
g.executeDangerousDeny(ctx, b, query, action)
|
||||
case "approve":
|
||||
g.executeDangerousApprove(ctx, b, query, action)
|
||||
case "permanent":
|
||||
g.executeDangerousPermanent(ctx, b, query, action)
|
||||
default:
|
||||
g.answerDangerousCallback(ctx, b, query.ID, "That action is no longer valid.", true)
|
||||
}
|
||||
}
|
||||
|
||||
// consumeDangerousAction validates and atomically consumes the pending
|
||||
// action associated with the callback query. Returns the action and true
|
||||
// if valid; false if expired, wrong recipient, or already consumed.
|
||||
func (g *Gateway) consumeDangerousAction(query *models.CallbackQuery) (dangerousAction, bool) {
|
||||
_, token := parseDangerousCallback(query.Data)
|
||||
g.dangerousMu.Lock()
|
||||
action, found := g.dangerousActions[token]
|
||||
if found && action.recipient == query.From.ID && action.expiresAt.After(time.Now()) {
|
||||
delete(g.dangerousActions, token)
|
||||
}
|
||||
g.dangerousMu.Unlock()
|
||||
return action, found && action.recipient == query.From.ID && action.expiresAt.After(time.Now())
|
||||
}
|
||||
|
||||
func (g *Gateway) executeDangerousDeny(ctx context.Context, b *bot.Bot, query *models.CallbackQuery, action dangerousAction) {
|
||||
g.answerDangerousCallback(ctx, b, query.ID, "Command denied.", false)
|
||||
g.editDangerousMessage(ctx, b, query, "❌ Denied: "+action.description)
|
||||
}
|
||||
|
||||
func (g *Gateway) executeDangerousApprove(ctx context.Context, b *bot.Bot, query *models.CallbackQuery, action dangerousAction) {
|
||||
result, err := action.onApprove(ctx)
|
||||
if err != nil {
|
||||
g.log.Error("dangerous command execution failed", "command", action.command, "error", err)
|
||||
g.answerDangerousCallback(ctx, b, query.ID, fmt.Sprintf("Command failed: %v", err), true)
|
||||
g.editDangerousMessage(ctx, b, query, fmt.Sprintf("❌ Failed: %s — %v", action.description, err))
|
||||
return
|
||||
}
|
||||
g.answerDangerousCallback(ctx, b, query.ID, "Approved and executed.", false)
|
||||
msg := "✅ Approved: " + action.description
|
||||
if result != "" {
|
||||
msg += "\n\n" + result
|
||||
}
|
||||
g.editDangerousMessage(ctx, b, query, msg)
|
||||
}
|
||||
|
||||
func (g *Gateway) executeDangerousPermanent(ctx context.Context, b *bot.Bot, query *models.CallbackQuery, action dangerousAction) {
|
||||
g.recordPermanentApproval(query.From.ID, action.command)
|
||||
|
||||
result, err := action.onApprove(ctx)
|
||||
if err != nil {
|
||||
g.log.Error("dangerous command execution failed (permanent approval)", "command", action.command, "error", err)
|
||||
g.answerDangerousCallback(ctx, b, query.ID, fmt.Sprintf("Command failed: %v", err), true)
|
||||
g.editDangerousMessage(ctx, b, query, fmt.Sprintf("❌ Failed: %s — %v", action.description, err))
|
||||
return
|
||||
}
|
||||
g.answerDangerousCallback(ctx, b, query.ID, "Permanently approved and executed (valid 24h).", false)
|
||||
msg := "✅ Approved (permanent, 24h): " + action.description
|
||||
if result != "" {
|
||||
msg += "\n\n" + result
|
||||
}
|
||||
g.editDangerousMessage(ctx, b, query, msg)
|
||||
}
|
||||
|
||||
func (g *Gateway) recordPermanentApproval(recipient int64, command string) {
|
||||
scope := permanentApproval{
|
||||
CommandPattern: command,
|
||||
Recipient: recipient,
|
||||
GrantedAt: time.Now(),
|
||||
ExpiresAt: time.Now().Add(24 * time.Hour),
|
||||
Scope: fmt.Sprintf("Permanent approval for %q by user %d, expires in 24h", command, recipient),
|
||||
}
|
||||
g.dangerousMu.Lock()
|
||||
g.permanentApprovals = append(g.permanentApprovals, scope)
|
||||
now := time.Now()
|
||||
kept := g.permanentApprovals[:0]
|
||||
for _, pa := range g.permanentApprovals {
|
||||
if pa.ExpiresAt.After(now) {
|
||||
kept = append(kept, pa)
|
||||
}
|
||||
}
|
||||
g.permanentApprovals = kept
|
||||
g.dangerousMu.Unlock()
|
||||
|
||||
g.log.Info("dangerous command permanently approved", "scope", scope.Scope)
|
||||
}
|
||||
|
||||
// hasPermanentApproval checks whether recipient has a current permanent
|
||||
// approval covering the given command text.
|
||||
func (g *Gateway) hasPermanentApproval(recipient int64, command string) bool {
|
||||
g.dangerousMu.Lock()
|
||||
defer g.dangerousMu.Unlock()
|
||||
|
||||
now := time.Now()
|
||||
kept := g.permanentApprovals[:0]
|
||||
found := false
|
||||
for _, pa := range g.permanentApprovals {
|
||||
if !pa.ExpiresAt.After(now) {
|
||||
continue
|
||||
}
|
||||
kept = append(kept, pa)
|
||||
if pa.Recipient == recipient && strings.HasPrefix(command, pa.CommandPattern) {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
g.permanentApprovals = kept
|
||||
return found
|
||||
}
|
||||
|
||||
// hasPermanentApprovalExact is the exact-match approval check for tool
|
||||
// approvals.
|
||||
func (g *Gateway) hasPermanentApprovalExact(recipient int64, pattern string) bool {
|
||||
g.dangerousMu.Lock()
|
||||
defer g.dangerousMu.Unlock()
|
||||
|
||||
now := time.Now()
|
||||
kept := g.permanentApprovals[:0]
|
||||
found := false
|
||||
for _, pa := range g.permanentApprovals {
|
||||
if !pa.ExpiresAt.After(now) {
|
||||
continue
|
||||
}
|
||||
kept = append(kept, pa)
|
||||
if pa.Recipient == recipient && pa.CommandPattern == pattern {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
g.permanentApprovals = kept
|
||||
return found
|
||||
}
|
||||
|
||||
func (g *Gateway) editDangerousMessage(ctx context.Context, b *bot.Bot, query *models.CallbackQuery, text string) {
|
||||
if query.Message.Message == nil {
|
||||
return
|
||||
}
|
||||
message := query.Message.Message
|
||||
if _, err := b.EditMessageText(ctx, &bot.EditMessageTextParams{
|
||||
ChatID: message.Chat.ID,
|
||||
MessageID: message.ID,
|
||||
Text: text,
|
||||
}); err != nil {
|
||||
g.log.Warn("edit dangerous message failed", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
// ── /rollback handler ───────────────────────────────────────────
|
||||
|
||||
// rollbackHandler serves /rollback: show available checkpoints, or with
|
||||
// a number, request approval to restore that checkpoint.
|
||||
func (g *Gateway) rollbackHandler() bot.HandlerFunc {
|
||||
return func(ctx context.Context, b *bot.Bot, update *models.Update) {
|
||||
msg, ok := g.authorizedMessage(ctx, b, update)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if g.Dangerous == nil {
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "Rollback is not configured for this installation.")
|
||||
return
|
||||
}
|
||||
|
||||
rest := strings.TrimSpace(restAfterTelegram(msg.Text, "/rollback", ""))
|
||||
if rest == "" {
|
||||
g.showCheckpoints(ctx, b, msg.Chat.ID, msg.MessageThreadID)
|
||||
return
|
||||
}
|
||||
|
||||
num, err := strconv.Atoi(rest)
|
||||
if err != nil || num < 1 {
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "Usage: /rollback <checkpoint number>")
|
||||
return
|
||||
}
|
||||
g.requestRollbackApproval(ctx, b, msg, num)
|
||||
}
|
||||
}
|
||||
|
||||
func (g *Gateway) showCheckpoints(ctx context.Context, b *bot.Bot, chatID int64, threadID int) {
|
||||
checkpoints, err := g.Dangerous.ListCheckpoints(ctx)
|
||||
if err != nil {
|
||||
g.log.Error("list checkpoints failed", "error", err)
|
||||
g.sendMessage(ctx, b, chatID, threadID, "Could not list checkpoints.")
|
||||
return
|
||||
}
|
||||
if len(checkpoints) == 0 {
|
||||
g.sendMessage(ctx, b, chatID, threadID, "No checkpoints available.")
|
||||
return
|
||||
}
|
||||
var text strings.Builder
|
||||
text.WriteString("Available checkpoints:\n\n")
|
||||
for _, c := range checkpoints {
|
||||
fmt.Fprintf(&text, "%d — %s (%s)", c.Number, c.Timestamp.Format("2006-01-02 15:04"), c.Label)
|
||||
if c.Size != "" {
|
||||
fmt.Fprintf(&text, " — %s", c.Size)
|
||||
}
|
||||
text.WriteByte('\n')
|
||||
}
|
||||
text.WriteString("\nUse /rollback <number> to restore a checkpoint.")
|
||||
g.sendMessage(ctx, b, chatID, threadID, text.String())
|
||||
}
|
||||
|
||||
func (g *Gateway) requestRollbackApproval(ctx context.Context, b *bot.Bot, msg *models.Message, num int) {
|
||||
rest := fmt.Sprintf("%d", num)
|
||||
if g.hasPermanentApproval(msg.From.ID, "/rollback") {
|
||||
result, err := g.Dangerous.Rollback(ctx, num)
|
||||
if err != nil {
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, fmt.Sprintf("❌ Rollback failed: %v", err))
|
||||
return
|
||||
}
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "✅ Rollback to checkpoint "+rest+":\n\n"+result)
|
||||
return
|
||||
}
|
||||
|
||||
cmdText := fmt.Sprintf("/rollback %d", num)
|
||||
desc := fmt.Sprintf("Rollback to checkpoint %d", num)
|
||||
token := g.registerDangerousAction(cmdText, desc, msg.From.ID, func(ctx context.Context) (string, error) {
|
||||
return g.Dangerous.Rollback(ctx, num)
|
||||
})
|
||||
|
||||
params := &bot.SendMessageParams{
|
||||
ChatID: msg.Chat.ID,
|
||||
Text: rollbackApprovalText(num),
|
||||
ReplyMarkup: g.dangerousKeyboard(token),
|
||||
}
|
||||
if msg.MessageThreadID != 0 {
|
||||
params.MessageThreadID = msg.MessageThreadID
|
||||
}
|
||||
if _, err := b.SendMessage(ctx, params); err != nil {
|
||||
g.log.Error("send dangerous prompt (rollback) failed", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func rollbackApprovalText(num int) string {
|
||||
return fmt.Sprintf(
|
||||
"⚠️ **Dangerous command**\n\n"+
|
||||
"Command: `/rollback %d`\n"+
|
||||
"Effect: Restore the worktree filesystem to checkpoint %d.\n"+
|
||||
"This will discard any changes made after that checkpoint.\n\n"+
|
||||
"_This request expires in 10 minutes._",
|
||||
num, num,
|
||||
)
|
||||
}
|
||||
|
||||
// ── /stop handler ──────────────────────────────────────────────
|
||||
|
||||
// stopCurrentTurn cancels the conversation's running turn and any tool under
|
||||
// it. Streamed text stays.
|
||||
func (g *Gateway) stopCurrentTurn(ctx context.Context, b *bot.Bot, msg *models.Message, client messaging.ChatContract) {
|
||||
var cancelled bool
|
||||
var dropped int
|
||||
|
||||
session := conversationID(msg).String()
|
||||
if g.turns != nil {
|
||||
cancelled, dropped = g.turns.Stop(session)
|
||||
g.log.Info("stop requested", "session", session, "cancelled", cancelled, "dropped", dropped)
|
||||
}
|
||||
if client != nil {
|
||||
if res, err := client.Cancel(ctx, session); err == nil {
|
||||
if res.Cancelled {
|
||||
cancelled = true
|
||||
}
|
||||
dropped += res.Dropped
|
||||
}
|
||||
}
|
||||
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID,
|
||||
stopReport(cancelled, dropped, nil))
|
||||
}
|
||||
|
||||
// stopReport describes what a /stop stopped.
|
||||
func stopReport(cancelled bool, dropped int, tasks []int64) string {
|
||||
var parts []string
|
||||
if cancelled {
|
||||
parts = append(parts, "the running reply")
|
||||
}
|
||||
if dropped > 0 {
|
||||
parts = append(parts, fmt.Sprintf("%d queued message(s)", dropped))
|
||||
}
|
||||
if len(tasks) > 0 {
|
||||
ids := make([]string, len(tasks))
|
||||
for i, id := range tasks {
|
||||
ids[i] = fmt.Sprintf("#%d", id)
|
||||
}
|
||||
parts = append(parts, "task(s) "+strings.Join(ids, ", "))
|
||||
}
|
||||
|
||||
if len(parts) == 0 {
|
||||
return "Nothing is running.\n\nUse /stop <process-name> to terminate a background process."
|
||||
}
|
||||
return "🛑 Stopped " + joinWithAnd(parts) + "."
|
||||
}
|
||||
|
||||
// joinWithAnd renders a list the way it would be read aloud.
|
||||
func joinWithAnd(parts []string) string {
|
||||
switch len(parts) {
|
||||
case 1:
|
||||
return parts[0]
|
||||
case 2:
|
||||
return parts[0] + " and " + parts[1]
|
||||
default:
|
||||
return strings.Join(parts[:len(parts)-1], ", ") + " and " + parts[len(parts)-1]
|
||||
}
|
||||
}
|
||||
|
||||
// stopHandler serves /stop. Bare /stop cancels the running turn immediately;
|
||||
// /stop <process-name> terminates a background process after approval.
|
||||
func (g *Gateway) stopHandler(client messaging.ChatContract) bot.HandlerFunc {
|
||||
return func(ctx context.Context, b *bot.Bot, update *models.Update) {
|
||||
msg, ok := g.authorizedMessage(ctx, b, update)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
rest := strings.TrimSpace(restAfterTelegram(msg.Text, "/stop", ""))
|
||||
if rest == "" {
|
||||
g.stopCurrentTurn(ctx, b, msg, client)
|
||||
return
|
||||
}
|
||||
|
||||
if g.Dangerous == nil {
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "Process control is not configured for this installation.")
|
||||
return
|
||||
}
|
||||
|
||||
// Check permanent approval.
|
||||
if g.hasPermanentApproval(msg.From.ID, "/stop") {
|
||||
if err := g.Dangerous.StopProcess(ctx, rest); err != nil {
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, fmt.Sprintf("❌ Stop failed: %v", err))
|
||||
return
|
||||
}
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "✅ Process stopped: "+rest)
|
||||
return
|
||||
}
|
||||
|
||||
cmdText := fmt.Sprintf("/stop %s", rest)
|
||||
desc := fmt.Sprintf("Stop process %q", rest)
|
||||
token := g.registerDangerousAction(cmdText, desc, msg.From.ID, func(ctx context.Context) (string, error) {
|
||||
if err := g.Dangerous.StopProcess(ctx, rest); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "", nil
|
||||
})
|
||||
|
||||
params := &bot.SendMessageParams{
|
||||
ChatID: msg.Chat.ID,
|
||||
Text: fmt.Sprintf(
|
||||
"⚠️ **Dangerous command**\n\n"+
|
||||
"Command: `/stop %s`\n"+
|
||||
"Effect: Terminate the running background process %q.\n"+
|
||||
"This will discard any in-progress work on that process.\n\n"+
|
||||
"_This request expires in 10 minutes._",
|
||||
rest, rest,
|
||||
),
|
||||
ReplyMarkup: g.dangerousKeyboard(token),
|
||||
}
|
||||
if msg.MessageThreadID != 0 {
|
||||
params.MessageThreadID = msg.MessageThreadID
|
||||
}
|
||||
if _, err := b.SendMessage(ctx, params); err != nil {
|
||||
g.log.Error("send dangerous prompt (stop) failed", "error", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── helpers ────────────────────────────────────────────────────
|
||||
|
||||
// restAfterTelegram strips a slash-command token from a Telegram message
|
||||
// text, including an optional @bot suffix.
|
||||
func restAfterTelegram(text, cmd, gatewayName string) string {
|
||||
s := text
|
||||
if gatewayName != "" {
|
||||
s = strings.TrimPrefix(s, cmd+"@"+gatewayName)
|
||||
}
|
||||
s = strings.TrimPrefix(s, cmd)
|
||||
return s
|
||||
}
|
||||
|
||||
func makeDangerousToken() string {
|
||||
bytes := make([]byte, 16)
|
||||
if _, err := rand.Read(bytes); err != nil {
|
||||
panic("crypto/rand: " + err.Error())
|
||||
}
|
||||
return hex.EncodeToString(bytes)
|
||||
}
|
||||
|
||||
// parseDangerousCallback splits a dangerous-command callback data into
|
||||
// decision ("approve", "permanent", "deny") and token.
|
||||
func parseDangerousCallback(data string) (decision, token string) {
|
||||
data = strings.TrimPrefix(data, dangerousCmdPrefix)
|
||||
decision, token, _ = strings.Cut(data, ":")
|
||||
if decision != "approve" && decision != "permanent" && decision != "deny" {
|
||||
return "", ""
|
||||
}
|
||||
return decision, token
|
||||
}
|
||||
|
||||
// ── /approve and /deny handlers ─────────────────────────────────
|
||||
|
||||
// approveHandler serves /approve: lists pending dangerous commands or
|
||||
// approves one by token.
|
||||
func (g *Gateway) approveHandler() bot.HandlerFunc {
|
||||
return func(ctx context.Context, b *bot.Bot, update *models.Update) {
|
||||
msg, ok := g.authorizedMessage(ctx, b, update)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if g.Dangerous == nil {
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID,
|
||||
"Dangerous-command approval is not configured.\n\n"+
|
||||
"Use /rollback or /stop to trigger approval inline.")
|
||||
return
|
||||
}
|
||||
|
||||
g.dangerousMu.Lock()
|
||||
now := time.Now()
|
||||
var pending []dangerousAction
|
||||
for key, action := range g.dangerousActions {
|
||||
if !action.expiresAt.After(now) {
|
||||
delete(g.dangerousActions, key)
|
||||
continue
|
||||
}
|
||||
if action.recipient == msg.From.ID {
|
||||
pending = append(pending, action)
|
||||
}
|
||||
}
|
||||
g.dangerousMu.Unlock()
|
||||
|
||||
if len(pending) == 0 {
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID,
|
||||
"No pending commands to approve.\n\n"+
|
||||
"Use /rollback or /stop to trigger a dangerous command approval inline.")
|
||||
return
|
||||
}
|
||||
|
||||
var text strings.Builder
|
||||
text.WriteString("Pending dangerous commands:\n\n")
|
||||
for i, action := range pending {
|
||||
fmt.Fprintf(&text, "%d. %s", i+1, action.description)
|
||||
remaining := time.Until(action.expiresAt).Truncate(time.Second)
|
||||
fmt.Fprintf(&text, " (expires in %s)", remaining)
|
||||
text.WriteByte('\n')
|
||||
}
|
||||
text.WriteString("\nUse the inline buttons on each pending command to approve or deny.")
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, text.String())
|
||||
}
|
||||
}
|
||||
|
||||
// denyHandler serves /deny: the counterpart to /approve for rejecting
|
||||
// pending dangerous commands. Like /approve, the primary interaction is
|
||||
// through inline buttons on each pending command.
|
||||
func (g *Gateway) denyHandler() bot.HandlerFunc {
|
||||
return g.approveHandler() // Same behaviour: show pending commands.
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/go-telegram/bot"
|
||||
"github.com/go-telegram/bot/models"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
// stopHandler serves /stop. Bare /stop cancels the chat agent's running
|
||||
// reply; when nothing is replying it stops the tasks this conversation's
|
||||
// agent created. /stop <id> stops that one task.
|
||||
func (g *Gateway) stopHandler(client messaging.ChatContract) bot.HandlerFunc {
|
||||
return func(ctx context.Context, b *bot.Bot, update *models.Update) {
|
||||
msg, ok := g.authorizedMessage(ctx, b, update)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
rest := strings.TrimSpace(restAfterTelegram(msg.Text, "/stop", ""))
|
||||
if rest == "" {
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, g.stopConversation(ctx, msg, client))
|
||||
return
|
||||
}
|
||||
id, err := strconv.ParseInt(strings.TrimPrefix(rest, "#"), 10, 64)
|
||||
if err != nil || id <= 0 {
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, "Usage: /stop, or /stop <task-id>")
|
||||
return
|
||||
}
|
||||
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, stopTasks(ctx, client, "", id))
|
||||
}
|
||||
}
|
||||
|
||||
// stopConversation cancels the running reply and queued messages; with none
|
||||
// running it stops the conversation's tasks instead.
|
||||
func (g *Gateway) stopConversation(ctx context.Context, msg *models.Message, client messaging.ChatContract) string {
|
||||
var cancelled bool
|
||||
var dropped int
|
||||
session := conversationID(msg).String()
|
||||
if g.turns != nil {
|
||||
cancelled, dropped = g.turns.Stop(session)
|
||||
g.log.Info("stop requested", "session", session, "cancelled", cancelled, "dropped", dropped)
|
||||
}
|
||||
if client == nil {
|
||||
return stopReport(cancelled, dropped, nil)
|
||||
}
|
||||
if res, err := client.Cancel(ctx, session); err == nil {
|
||||
cancelled = cancelled || res.Cancelled
|
||||
dropped += res.Dropped
|
||||
}
|
||||
if cancelled || dropped > 0 {
|
||||
return stopReport(cancelled, dropped, nil)
|
||||
}
|
||||
return stopTasks(ctx, client, messaging.Origin("telegram", conversationID(msg)), 0)
|
||||
}
|
||||
|
||||
func stopTasks(ctx context.Context, client messaging.ChatContract, origin string, id int64) string {
|
||||
if client == nil {
|
||||
return "Task control is not configured."
|
||||
}
|
||||
stopped, err := client.StopTasks(ctx, origin, id)
|
||||
report := stopReport(false, 0, stopped)
|
||||
if err != nil {
|
||||
return report + "\n\nCould not stop: " + err.Error()
|
||||
}
|
||||
return report
|
||||
}
|
||||
|
||||
// stopReport describes what a /stop stopped.
|
||||
func stopReport(cancelled bool, dropped int, tasks []int64) string {
|
||||
var parts []string
|
||||
if cancelled {
|
||||
parts = append(parts, "the running reply")
|
||||
}
|
||||
if dropped > 0 {
|
||||
parts = append(parts, fmt.Sprintf("%d queued message(s)", dropped))
|
||||
}
|
||||
if len(tasks) > 0 {
|
||||
ids := make([]string, len(tasks))
|
||||
for i, id := range tasks {
|
||||
ids[i] = fmt.Sprintf("#%d", id)
|
||||
}
|
||||
parts = append(parts, "task(s) "+strings.Join(ids, ", "))
|
||||
}
|
||||
if len(parts) == 0 {
|
||||
return "Nothing is running."
|
||||
}
|
||||
return "🛑 Stopped " + joinWithAnd(parts) + "."
|
||||
}
|
||||
|
||||
// joinWithAnd renders a list the way it would be read aloud.
|
||||
func joinWithAnd(parts []string) string {
|
||||
switch len(parts) {
|
||||
case 1:
|
||||
return parts[0]
|
||||
case 2:
|
||||
return parts[0] + " and " + parts[1]
|
||||
default:
|
||||
return strings.Join(parts[:len(parts)-1], ", ") + " and " + parts[len(parts)-1]
|
||||
}
|
||||
}
|
||||
|
||||
// restAfterTelegram strips a slash-command token from a Telegram message
|
||||
// text, including an optional @bot suffix.
|
||||
func restAfterTelegram(text, cmd, gatewayName string) string {
|
||||
s := text
|
||||
if gatewayName != "" {
|
||||
s = strings.TrimPrefix(s, cmd+"@"+gatewayName)
|
||||
}
|
||||
s = strings.TrimPrefix(s, cmd)
|
||||
return s
|
||||
}
|
||||
@@ -60,11 +60,6 @@ type Gateway struct {
|
||||
// verify update reports. Nil leaves claims unverified.
|
||||
RunningVersions func() map[string]string
|
||||
|
||||
// Dangerous is the sandbox/process authority for /rollback and /stop.
|
||||
// When nil, those commands return "not configured". The composition
|
||||
// root supplies this; Telegram only renders approval UX.
|
||||
Dangerous DangerousCommandAuthority
|
||||
|
||||
// showToolCalls controls whether new live replies render completed tool
|
||||
// calls. Each reply snapshots it so reloads affect only later turns.
|
||||
showToolCalls atomic.Bool
|
||||
@@ -83,17 +78,14 @@ type Gateway struct {
|
||||
updateActions map[string]updateAction
|
||||
updateReportMu sync.Mutex
|
||||
|
||||
// dangerous command approval state
|
||||
dangerousMu sync.Mutex
|
||||
dangerousActions map[string]dangerousAction
|
||||
permanentApprovals []permanentApproval
|
||||
|
||||
// tool approval state (gateway.ApprovalRequester). Kept separate from
|
||||
// the dangerous-command state above: tool approvals deliver the human's
|
||||
// decision on a channel to the blocked RequestApproval call rather than
|
||||
// executing through an onApprove callback.
|
||||
// tool approval state (gateway.ApprovalRequester): tool approvals
|
||||
// deliver the human's decision on a channel to the blocked
|
||||
// RequestApproval call.
|
||||
approvalMu sync.Mutex
|
||||
pendingApprovals map[string]*pendingApproval
|
||||
// permanentMu guards the 24-hour approvals a human granted per tool.
|
||||
permanentMu sync.Mutex
|
||||
permanentApprovals []permanentApproval
|
||||
|
||||
// interactive state (gateway clarify/picker). A blocked clarify or
|
||||
// picker waits on one entry here, keyed by the chat it was posed to, so
|
||||
@@ -156,18 +148,16 @@ type ReleaseAnnouncer interface {
|
||||
// New returns an unstarted Gateway. Call Start to begin long-polling.
|
||||
func New(token string, allowedUserIDs []int64, log *slog.Logger) *Gateway {
|
||||
g := &Gateway{
|
||||
Token: token,
|
||||
AllowedUserIDs: allowedUserIDs,
|
||||
restartCh: make(chan restartRequest, 1),
|
||||
modelCallbacks: make(map[string]string),
|
||||
modelPages: make(map[string]modelPage),
|
||||
providerCallbacks: make(map[string]string),
|
||||
updateActions: make(map[string]updateAction),
|
||||
dangerousActions: make(map[string]dangerousAction),
|
||||
permanentApprovals: nil,
|
||||
pendingApprovals: make(map[string]*pendingApproval),
|
||||
pendingReplies: make(map[pendingReplyKey]*pendingReply),
|
||||
log: log.With("component", "gateway-telegram"),
|
||||
Token: token,
|
||||
AllowedUserIDs: allowedUserIDs,
|
||||
restartCh: make(chan restartRequest, 1),
|
||||
modelCallbacks: make(map[string]string),
|
||||
modelPages: make(map[string]modelPage),
|
||||
providerCallbacks: make(map[string]string),
|
||||
updateActions: make(map[string]updateAction),
|
||||
pendingApprovals: make(map[string]*pendingApproval),
|
||||
pendingReplies: make(map[pendingReplyKey]*pendingReply),
|
||||
log: log.With("component", "gateway-telegram"),
|
||||
}
|
||||
g.newEphemeralSender = func() *channels.EphemeralSender {
|
||||
return channels.NewEphemeralSender(g.log, nil)
|
||||
@@ -267,10 +257,7 @@ var telegramTextHandlers = []telegramTextHandler{
|
||||
{"/start", bot.MatchTypeExact, func(g *Gateway, _ messaging.ChatContract) bot.HandlerFunc { return g.startHandler() }},
|
||||
{"/help", bot.MatchTypeExact, func(g *Gateway, _ messaging.ChatContract) bot.HandlerFunc { return g.helpHandler() }},
|
||||
{"/restart", bot.MatchTypeExact, func(g *Gateway, _ messaging.ChatContract) bot.HandlerFunc { return g.restartHandler() }},
|
||||
{"/rollback", bot.MatchTypePrefix, func(g *Gateway, _ messaging.ChatContract) bot.HandlerFunc { return g.rollbackHandler() }},
|
||||
{"/stop", bot.MatchTypePrefix, func(g *Gateway, c messaging.ChatContract) bot.HandlerFunc { return g.stopHandler(c) }},
|
||||
{"/approve", bot.MatchTypeExact, func(g *Gateway, _ messaging.ChatContract) bot.HandlerFunc { return g.approveHandler() }},
|
||||
{"/deny", bot.MatchTypeExact, func(g *Gateway, _ messaging.ChatContract) bot.HandlerFunc { return g.denyHandler() }},
|
||||
}
|
||||
|
||||
func (g *Gateway) registerCommandHandlers(b *bot.Bot, client messaging.ChatContract) {
|
||||
@@ -565,8 +552,6 @@ func (g *Gateway) handleCallback(ctx context.Context, b *bot.Bot, update *models
|
||||
switch {
|
||||
case strings.HasPrefix(update.CallbackQuery.Data, approvalCallbackPrefix):
|
||||
g.handleApprovalCallback(ctx, b, update)
|
||||
case strings.HasPrefix(update.CallbackQuery.Data, dangerousCmdPrefix):
|
||||
g.handleDangerousCallback(ctx, b, update)
|
||||
case strings.HasPrefix(update.CallbackQuery.Data, providerCallbackPrefix):
|
||||
g.handleProviderCallback(ctx, b, update, client)
|
||||
case strings.HasPrefix(update.CallbackQuery.Data, modelCallbackPrefix):
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -26,6 +26,7 @@ const (
|
||||
ChatService_Route_FullMethodName = "/gateway.v1.ChatService/Route"
|
||||
ChatService_Stream_FullMethodName = "/gateway.v1.ChatService/Stream"
|
||||
ChatService_Cancel_FullMethodName = "/gateway.v1.ChatService/Cancel"
|
||||
ChatService_StopTasks_FullMethodName = "/gateway.v1.ChatService/StopTasks"
|
||||
ChatService_SetPersona_FullMethodName = "/gateway.v1.ChatService/SetPersona"
|
||||
ChatService_ApplyTaskAction_FullMethodName = "/gateway.v1.ChatService/ApplyTaskAction"
|
||||
ChatService_ApplyOperatorTaskAction_FullMethodName = "/gateway.v1.ChatService/ApplyOperatorTaskAction"
|
||||
@@ -56,6 +57,7 @@ type ChatServiceClient interface {
|
||||
Route(ctx context.Context, in *RouteRequest, opts ...grpc.CallOption) (*RouteResponse, error)
|
||||
Stream(ctx context.Context, in *StreamRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[StreamResponse], error)
|
||||
Cancel(ctx context.Context, in *CancelRequest, opts ...grpc.CallOption) (*CancelResponse, error)
|
||||
StopTasks(ctx context.Context, in *StopTasksRequest, opts ...grpc.CallOption) (*StopTasksResponse, error)
|
||||
SetPersona(ctx context.Context, in *SetPersonaRequest, opts ...grpc.CallOption) (*SetPersonaResponse, error)
|
||||
ApplyTaskAction(ctx context.Context, in *ApplyTaskActionRequest, opts ...grpc.CallOption) (*ApplyTaskActionResponse, error)
|
||||
ApplyOperatorTaskAction(ctx context.Context, in *ApplyOperatorTaskActionRequest, opts ...grpc.CallOption) (*ApplyOperatorTaskActionResponse, error)
|
||||
@@ -162,6 +164,16 @@ func (c *chatServiceClient) Cancel(ctx context.Context, in *CancelRequest, opts
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *chatServiceClient) StopTasks(ctx context.Context, in *StopTasksRequest, opts ...grpc.CallOption) (*StopTasksResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(StopTasksResponse)
|
||||
err := c.cc.Invoke(ctx, ChatService_StopTasks_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *chatServiceClient) SetPersona(ctx context.Context, in *SetPersonaRequest, opts ...grpc.CallOption) (*SetPersonaResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(SetPersonaResponse)
|
||||
@@ -343,6 +355,7 @@ type ChatServiceServer interface {
|
||||
Route(context.Context, *RouteRequest) (*RouteResponse, error)
|
||||
Stream(*StreamRequest, grpc.ServerStreamingServer[StreamResponse]) error
|
||||
Cancel(context.Context, *CancelRequest) (*CancelResponse, error)
|
||||
StopTasks(context.Context, *StopTasksRequest) (*StopTasksResponse, error)
|
||||
SetPersona(context.Context, *SetPersonaRequest) (*SetPersonaResponse, error)
|
||||
ApplyTaskAction(context.Context, *ApplyTaskActionRequest) (*ApplyTaskActionResponse, error)
|
||||
ApplyOperatorTaskAction(context.Context, *ApplyOperatorTaskActionRequest) (*ApplyOperatorTaskActionResponse, error)
|
||||
@@ -391,6 +404,9 @@ func (UnimplementedChatServiceServer) Stream(*StreamRequest, grpc.ServerStreamin
|
||||
func (UnimplementedChatServiceServer) Cancel(context.Context, *CancelRequest) (*CancelResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method Cancel not implemented")
|
||||
}
|
||||
func (UnimplementedChatServiceServer) StopTasks(context.Context, *StopTasksRequest) (*StopTasksResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method StopTasks not implemented")
|
||||
}
|
||||
func (UnimplementedChatServiceServer) SetPersona(context.Context, *SetPersonaRequest) (*SetPersonaResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method SetPersona not implemented")
|
||||
}
|
||||
@@ -582,6 +598,24 @@ func _ChatService_Cancel_Handler(srv interface{}, ctx context.Context, dec func(
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _ChatService_StopTasks_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(StopTasksRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(ChatServiceServer).StopTasks(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: ChatService_StopTasks_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(ChatServiceServer).StopTasks(ctx, req.(*StopTasksRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _ChatService_SetPersona_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(SetPersonaRequest)
|
||||
if err := dec(in); err != nil {
|
||||
@@ -919,6 +953,10 @@ var ChatService_ServiceDesc = grpc.ServiceDesc{
|
||||
MethodName: "Cancel",
|
||||
Handler: _ChatService_Cancel_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "StopTasks",
|
||||
Handler: _ChatService_StopTasks_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "SetPersona",
|
||||
Handler: _ChatService_SetPersona_Handler,
|
||||
|
||||
+1373
-1265
File diff suppressed because it is too large.
Load diff
@@ -41,6 +41,7 @@ const (
|
||||
StateStoreService_RevokePersonalToken_FullMethodName = "/state.v1.StateStoreService/RevokePersonalToken"
|
||||
StateStoreService_EnqueueIssue_FullMethodName = "/state.v1.StateStoreService/EnqueueIssue"
|
||||
StateStoreService_EnqueueChatTask_FullMethodName = "/state.v1.StateStoreService/EnqueueChatTask"
|
||||
StateStoreService_ActiveTasksByOrigin_FullMethodName = "/state.v1.StateStoreService/ActiveTasksByOrigin"
|
||||
StateStoreService_ClaimNext_FullMethodName = "/state.v1.StateStoreService/ClaimNext"
|
||||
StateStoreService_ClaimByIssue_FullMethodName = "/state.v1.StateStoreService/ClaimByIssue"
|
||||
StateStoreService_Transition_FullMethodName = "/state.v1.StateStoreService/Transition"
|
||||
@@ -187,6 +188,7 @@ type StateStoreServiceClient interface {
|
||||
// Lifecycle
|
||||
EnqueueIssue(ctx context.Context, in *EnqueueIssueRequest, opts ...grpc.CallOption) (*EnqueueIssueResponse, error)
|
||||
EnqueueChatTask(ctx context.Context, in *EnqueueChatTaskRequest, opts ...grpc.CallOption) (*EnqueueChatTaskResponse, error)
|
||||
ActiveTasksByOrigin(ctx context.Context, in *ActiveTasksByOriginRequest, opts ...grpc.CallOption) (*ActiveTasksByOriginResponse, error)
|
||||
ClaimNext(ctx context.Context, in *ClaimNextRequest, opts ...grpc.CallOption) (*ClaimNextResponse, error)
|
||||
ClaimByIssue(ctx context.Context, in *ClaimByIssueRequest, opts ...grpc.CallOption) (*ClaimByIssueResponse, error)
|
||||
Transition(ctx context.Context, in *TransitionRequest, opts ...grpc.CallOption) (*TransitionResponse, error)
|
||||
@@ -598,6 +600,16 @@ func (c *stateStoreServiceClient) EnqueueChatTask(ctx context.Context, in *Enque
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) ActiveTasksByOrigin(ctx context.Context, in *ActiveTasksByOriginRequest, opts ...grpc.CallOption) (*ActiveTasksByOriginResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(ActiveTasksByOriginResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_ActiveTasksByOrigin_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) ClaimNext(ctx context.Context, in *ClaimNextRequest, opts ...grpc.CallOption) (*ClaimNextResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(ClaimNextResponse)
|
||||
@@ -1651,6 +1663,7 @@ type StateStoreServiceServer interface {
|
||||
// Lifecycle
|
||||
EnqueueIssue(context.Context, *EnqueueIssueRequest) (*EnqueueIssueResponse, error)
|
||||
EnqueueChatTask(context.Context, *EnqueueChatTaskRequest) (*EnqueueChatTaskResponse, error)
|
||||
ActiveTasksByOrigin(context.Context, *ActiveTasksByOriginRequest) (*ActiveTasksByOriginResponse, error)
|
||||
ClaimNext(context.Context, *ClaimNextRequest) (*ClaimNextResponse, error)
|
||||
ClaimByIssue(context.Context, *ClaimByIssueRequest) (*ClaimByIssueResponse, error)
|
||||
Transition(context.Context, *TransitionRequest) (*TransitionResponse, error)
|
||||
@@ -1908,6 +1921,9 @@ func (UnimplementedStateStoreServiceServer) EnqueueIssue(context.Context, *Enque
|
||||
func (UnimplementedStateStoreServiceServer) EnqueueChatTask(context.Context, *EnqueueChatTaskRequest) (*EnqueueChatTaskResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method EnqueueChatTask not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) ActiveTasksByOrigin(context.Context, *ActiveTasksByOriginRequest) (*ActiveTasksByOriginResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method ActiveTasksByOrigin not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) ClaimNext(context.Context, *ClaimNextRequest) (*ClaimNextResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method ClaimNext not implemented")
|
||||
}
|
||||
@@ -2619,6 +2635,24 @@ func _StateStoreService_EnqueueChatTask_Handler(srv interface{}, ctx context.Con
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_ActiveTasksByOrigin_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(ActiveTasksByOriginRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).ActiveTasksByOrigin(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_ActiveTasksByOrigin_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).ActiveTasksByOrigin(ctx, req.(*ActiveTasksByOriginRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_ClaimNext_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(ClaimNextRequest)
|
||||
if err := dec(in); err != nil {
|
||||
@@ -4457,6 +4491,10 @@ var StateStoreService_ServiceDesc = grpc.ServiceDesc{
|
||||
MethodName: "EnqueueChatTask",
|
||||
Handler: _StateStoreService_EnqueueChatTask_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "ActiveTasksByOrigin",
|
||||
Handler: _StateStoreService_ActiveTasksByOrigin_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "ClaimNext",
|
||||
Handler: _StateStoreService_ClaimNext_Handler,
|
||||
|
||||
@@ -19,6 +19,10 @@ type ChatContract interface { //nolint:interfacebloat // wire contract intention
|
||||
// Callers must drain the stream or cancel the context. Cancellation closes it.
|
||||
Stream(context.Context, Inbound) (<-chan ChatEvent, error)
|
||||
Cancel(context.Context, string) (ChatCancellation, error)
|
||||
// StopTasks stops the chat identity's task taskID, or with taskID zero
|
||||
// every queued or running task the conversation origin created. It
|
||||
// returns the tasks it stopped.
|
||||
StopTasks(ctx context.Context, origin string, taskID int64) ([]int64, error)
|
||||
SetPersona(context.Context, string, string) (bool, error)
|
||||
ChatTaskActionContract
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ package messaging
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Inbound is a received message plus transport context that is not
|
||||
@@ -36,6 +35,9 @@ type SpawnRequest struct {
|
||||
Workflow string // empty = daemon's default workflow routing
|
||||
Inputs map[string]any
|
||||
Identity string // the identity spawning this task; propagated from Router.Identity
|
||||
// Origin names the conversation that spawned the task, so its /stop can
|
||||
// find it; empty for a task no conversation started.
|
||||
Origin string
|
||||
}
|
||||
|
||||
// TaskCreator creates a chat task and returns its database ID. Nil makes
|
||||
@@ -43,20 +45,3 @@ type SpawnRequest struct {
|
||||
type TaskCreator interface {
|
||||
CreateTask(ctx context.Context, req SpawnRequest) (taskID int64, err error)
|
||||
}
|
||||
|
||||
// DangerousCommandAuthority is the sandbox-owned authority for operations
|
||||
// that can destroy process or filesystem state. Adapters only request and
|
||||
// present approval; they never implement these operations themselves.
|
||||
type DangerousCommandAuthority interface {
|
||||
StopProcess(context.Context, string) error
|
||||
Rollback(context.Context, int) (string, error)
|
||||
ListCheckpoints(context.Context) ([]CheckpointInfo, error)
|
||||
}
|
||||
|
||||
// CheckpointInfo describes a saved sandbox filesystem checkpoint.
|
||||
type CheckpointInfo struct {
|
||||
Number int
|
||||
Timestamp time.Time
|
||||
Label string
|
||||
Size string
|
||||
}
|
||||
@@ -19,6 +19,12 @@ func (c ConversationID) String() string {
|
||||
return c.ChannelID + "/" + c.ThreadID
|
||||
}
|
||||
|
||||
// Origin names a conversation across platforms: the key a task records for
|
||||
// the chat that created it.
|
||||
func Origin(platform string, c ConversationID) string {
|
||||
return platform + ":" + c.String()
|
||||
}
|
||||
|
||||
// MessageID is the canonical, immutable identifier for a Message. Once
|
||||
// assigned it never changes, including across branch and fork operations —
|
||||
// a forked transcript references the original MessageID it branched from
|
||||
|
||||
@@ -131,7 +131,7 @@ func Mesh(records []storecontract.Presence, now time.Time) []Service {
|
||||
func Unreachable() []Service {
|
||||
services := make([]Service, 0, len(Services()))
|
||||
for _, name := range Services() {
|
||||
service := Service{Presence: storecontract.Presence{Service: name}, State: StateUnknown}
|
||||
service := Service{Service: name, State: StateUnknown}
|
||||
if name == StateStore {
|
||||
service.State, service.Detail = StateDown, "unreachable"
|
||||
}
|
||||
|
||||
@@ -37,7 +37,7 @@ type TaskStore interface {
|
||||
// poll, chat spawn, drain loop) do not acquire a binding-specific shape.
|
||||
type TaskLifecycle interface {
|
||||
EnqueueIssue(ctx context.Context, owner, repo string, number int, title, body, labels, identity string) (bool, error)
|
||||
EnqueueChatTask(ctx context.Context, owner, repo, title, body, wf, identity string, inputs map[string]any) (*task.Task, error)
|
||||
EnqueueChatTask(ctx context.Context, owner, repo, title, body, wf, identity, origin string, inputs map[string]any) (*task.Task, error)
|
||||
ClaimNext(ctx context.Context) (*task.Task, error)
|
||||
ClaimByIssue(ctx context.Context, owner, repo string, number int) (*task.Task, error)
|
||||
Transition(ctx context.Context, taskID int64, from, to, detail string) error
|
||||
@@ -81,6 +81,7 @@ type HarnessSecretStore interface {
|
||||
// consumers that only run tasks do not acquire an operator-only capability.
|
||||
type TaskArchiver interface {
|
||||
ArchiveTask(ctx context.Context, taskID int64, fromStatus string, audit events.Event) (eventID int64, err error)
|
||||
ClearTerminalTasks(ctx context.Context) (int64, error)
|
||||
}
|
||||
|
||||
// TaskRetryer atomically requeues recoverable work and accounts for the new
|
||||
@@ -124,7 +125,9 @@ type TaskQueries interface {
|
||||
OpenTaskByPR(ctx context.Context, owner, repo string, number int) (*task.Task, error)
|
||||
TaskByID(ctx context.Context, taskID int64) (*task.Task, error)
|
||||
OpenPRs(ctx context.Context) ([]task.Task, error)
|
||||
ClearTerminalTasks(ctx context.Context) (int64, error)
|
||||
// ActiveTasksByOrigin returns the queued and running tasks the
|
||||
// conversation origin created, for its /stop.
|
||||
ActiveTasksByOrigin(ctx context.Context, origin string) ([]*task.Task, error)
|
||||
// Tasks returns the most recently updated tasks.
|
||||
Tasks(ctx context.Context, limit int) ([]task.Task, error)
|
||||
// TasksPage returns one page of tasks, most recently updated first.
|
||||
|
||||
@@ -49,10 +49,6 @@ type (
|
||||
MessagePage = messaging.MessagePage
|
||||
// CommandSpec describes a local command for adapter-provided discovery.
|
||||
CommandSpec = messaging.CommandSpec
|
||||
// DangerousCommandAuthority is the sandbox-owned authority for destructive operations.
|
||||
DangerousCommandAuthority = messaging.DangerousCommandAuthority
|
||||
// CheckpointInfo describes a saved sandbox filesystem checkpoint.
|
||||
CheckpointInfo = messaging.CheckpointInfo
|
||||
// TaskActionResult is what task_action returns.
|
||||
TaskActionResult = messaging.TaskActionResult
|
||||
// DashboardNavigateResult is what dashboard_navigate returns.
|
||||
|
||||
@@ -3,11 +3,13 @@ package gateway
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/domain/taskactions"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
)
|
||||
|
||||
@@ -21,6 +23,14 @@ type LocalChatAdapter struct {
|
||||
Models ModelManager
|
||||
Personas *PersonaRegistry
|
||||
TaskActor ChatTaskActor
|
||||
// Tasks reads the tasks /stop acts on.
|
||||
Tasks TaskReader
|
||||
}
|
||||
|
||||
// TaskReader is the task reads /stop needs.
|
||||
type TaskReader interface {
|
||||
TaskByID(ctx context.Context, taskID int64) (*task.Task, error)
|
||||
ActiveTasksByOrigin(ctx context.Context, origin string) ([]*task.Task, error)
|
||||
}
|
||||
|
||||
var _ ChatContract = (*LocalChatAdapter)(nil)
|
||||
@@ -108,6 +118,58 @@ func (a *LocalChatAdapter) Cancel(ctx context.Context, id string) (ChatCancellat
|
||||
return ChatCancellation{Cancelled: cancelled, Dropped: dropped}, nil
|
||||
}
|
||||
|
||||
func (a *LocalChatAdapter) StopTasks(ctx context.Context, origin string, taskID int64) ([]int64, error) {
|
||||
if a.TaskActor == nil || a.Tasks == nil {
|
||||
return nil, ErrChatCapabilityUnavailable
|
||||
}
|
||||
var targets []*task.Task
|
||||
if taskID != 0 {
|
||||
t, err := a.Tasks.TaskByID(ctx, taskID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if t == nil {
|
||||
return nil, fmt.Errorf("task %d not found", taskID)
|
||||
}
|
||||
targets = []*task.Task{t}
|
||||
} else {
|
||||
active, err := a.Tasks.ActiveTasksByOrigin(ctx, origin)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
targets = active
|
||||
}
|
||||
identity := a.Router.Identity
|
||||
var stopped []int64
|
||||
var errs []error
|
||||
for _, t := range targets {
|
||||
action, ok := haltAction(t.Status)
|
||||
if !ok {
|
||||
errs = append(errs, fmt.Errorf("task %d is %s, not running or queued", t.ID, t.Status))
|
||||
continue
|
||||
}
|
||||
if _, err := a.TaskActor.ApplyChatTaskAction(ctx, &identity, taskactions.ActorFromScope(identity), t.ID, action, taskactions.ActionPayload{}); err != nil {
|
||||
errs = append(errs, fmt.Errorf("task %d: %w", t.ID, err))
|
||||
continue
|
||||
}
|
||||
stopped = append(stopped, t.ID)
|
||||
}
|
||||
return stopped, errors.Join(errs...)
|
||||
}
|
||||
|
||||
// haltAction is how /stop ends a task: a running one is stopped, keeping its
|
||||
// recoverable work parked; a queued one is cancelled before it starts.
|
||||
func haltAction(status string) (taskstate.Action, bool) {
|
||||
switch status {
|
||||
case taskstate.Running:
|
||||
return taskstate.ActionStop, true
|
||||
case taskstate.Queued:
|
||||
return taskstate.ActionCancel, true
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
|
||||
func (a *LocalChatAdapter) SetPersona(ctx context.Context, id, name string) (bool, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return false, err
|
||||
|
||||
@@ -290,6 +290,7 @@ func (r *Router) CollectTurn(ctx context.Context, in Inbound) (Inbound, bool, er
|
||||
// local-command fallthrough and the streamed adapter's degraded-to-non-
|
||||
// streaming path do, to avoid charging one message twice).
|
||||
func (r *Router) route(ctx context.Context, in Inbound) (string, error) {
|
||||
ctx = r.turnContext(ctx, in)
|
||||
text := strings.TrimSpace(in.Message.Text)
|
||||
cmd, _ := parseCmd(text, r.gatewayName)
|
||||
|
||||
@@ -454,6 +455,7 @@ func (r *Router) dispatchSessionCommand(ctx context.Context, msg messaging.Messa
|
||||
// streamTurn dispatches one streamed turn whose gates and batching already
|
||||
// ran in the adapter's prelude.
|
||||
func (r *Router) streamTurn(ctx context.Context, in Inbound, stream TurnStream) (string, error) {
|
||||
ctx = r.turnContext(ctx, in)
|
||||
if r.LLMStream == nil || stream == nil {
|
||||
return r.route(ctx, in)
|
||||
}
|
||||
@@ -541,7 +543,7 @@ func (r *Router) handleSpawn(ctx context.Context, rest string) (string, error) {
|
||||
if r.Tasks == nil {
|
||||
return "Task creation is not configured.", nil
|
||||
}
|
||||
req := SpawnRequest{Identity: r.Identity}
|
||||
req := SpawnRequest{Identity: r.Identity, Origin: originFrom(ctx)}
|
||||
fields := strings.Fields(rest)
|
||||
i := 0
|
||||
for i < len(fields) {
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
type originKey struct{}
|
||||
|
||||
// withOrigin marks ctx as a turn of the conversation origin, so a task the
|
||||
// turn spawns records where it came from.
|
||||
func withOrigin(ctx context.Context, origin string) context.Context {
|
||||
return context.WithValue(ctx, originKey{}, origin)
|
||||
}
|
||||
|
||||
// originFrom is the conversation ctx's turn belongs to, or empty.
|
||||
func originFrom(ctx context.Context) string {
|
||||
origin, _ := ctx.Value(originKey{}).(string)
|
||||
return origin
|
||||
}
|
||||
|
||||
func (r *Router) turnContext(ctx context.Context, in Inbound) context.Context {
|
||||
return withOrigin(ctx, messaging.Origin(r.sessionPlatform(in), in.Message.ConversationID))
|
||||
}
|
||||
@@ -259,6 +259,7 @@ func taskSpawnTool(creator TaskCreator, identity string) tools.ToolEntry {
|
||||
// The bound identity, never input["identity"]. CreateTask
|
||||
// enforces the repository allow-list for it.
|
||||
Identity: identity,
|
||||
Origin: originFrom(ctx),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("task_spawn: %w", err)
|
||||
|
||||
@@ -39,7 +39,7 @@ type taskProfile struct {
|
||||
|
||||
// chatTaskWriter creates a chat task and returns its database ID.
|
||||
type chatTaskWriter interface {
|
||||
EnqueueChatTask(ctx context.Context, owner, repo, title, body, workflow, identity string, inputs map[string]any) (taskID int64, err error)
|
||||
EnqueueChatTask(ctx context.Context, owner, repo, title, body, workflow, identity, origin string, inputs map[string]any) (taskID int64, err error)
|
||||
}
|
||||
|
||||
// NewStoreTaskCreator returns a TaskCreator. repos lists the allowed
|
||||
@@ -92,7 +92,7 @@ func (c *StoreTaskCreator) CreateTask(ctx context.Context, req SpawnRequest) (in
|
||||
if owner == "" || repo == "" {
|
||||
return 0, fmt.Errorf("no repo configured for chat-spawned tasks")
|
||||
}
|
||||
return c.store.EnqueueChatTask(ctx, owner, repo, req.Title, req.Body, req.Workflow, req.Identity, req.Inputs)
|
||||
return c.store.EnqueueChatTask(ctx, owner, repo, req.Title, req.Body, req.Workflow, req.Identity, req.Origin, req.Inputs)
|
||||
}
|
||||
|
||||
func splitOwnerRepo(s string) (owner, repo string, ok bool) {
|
||||
|
||||
@@ -82,6 +82,17 @@ func (c *Client) SetPersona(ctx context.Context, id, name string) (bool, error)
|
||||
return v.Found, nil
|
||||
}
|
||||
|
||||
func (c *Client) StopTasks(ctx context.Context, origin string, taskID int64) ([]int64, error) {
|
||||
v, err := c.client.StopTasks(ctx, &pb.StopTasksRequest{Origin: origin, TaskId: taskID})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if v.Error != "" {
|
||||
return v.Stopped, errors.New(v.Error)
|
||||
}
|
||||
return v.Stopped, nil
|
||||
}
|
||||
|
||||
func (c *Client) ApplyTaskAction(ctx context.Context, identity string, taskID int64, action taskstate.Action, res taskactions.ActionPayload) (messaging.TaskActionResult, error) {
|
||||
v, err := c.client.ApplyTaskAction(ctx, &pb.ApplyTaskActionRequest{
|
||||
Identity: identity, TaskId: taskID, Action: string(action),
|
||||
|
||||
@@ -92,6 +92,18 @@ func (s *server) SetPersona(ctx context.Context, r *pb.SetPersonaRequest) (*pb.S
|
||||
return &pb.SetPersonaResponse{Found: v}, nil
|
||||
}
|
||||
|
||||
func (s *server) StopTasks(ctx context.Context, r *pb.StopTasksRequest) (*pb.StopTasksResponse, error) {
|
||||
stopped, err := s.chat.StopTasks(ctx, r.Origin, r.TaskId)
|
||||
if err != nil && len(stopped) == 0 {
|
||||
return nil, err
|
||||
}
|
||||
out := &pb.StopTasksResponse{Stopped: stopped}
|
||||
if err != nil {
|
||||
out.Error = err.Error()
|
||||
}
|
||||
return out, 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), taskactions.ActionPayload{
|
||||
Instructions: r.Instructions,
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
-- tasks.origin names the conversation that created a chat task, so a chat's
|
||||
-- /stop can find the work its agent started. Empty for every other task.
|
||||
|
||||
-- +goose Up
|
||||
|
||||
ALTER TABLE tasks ADD COLUMN origin text NOT NULL DEFAULT '';
|
||||
CREATE INDEX idx_tasks_origin ON tasks (origin) WHERE origin <> '';
|
||||
|
||||
-- +goose Down
|
||||
|
||||
DROP INDEX idx_tasks_origin;
|
||||
ALTER TABLE tasks DROP COLUMN origin;
|
||||
@@ -24,7 +24,7 @@ func (q *Queries) CallStatusDetail(ctx context.Context, taskID int64) (string, e
|
||||
|
||||
const enqueueCallTask = `-- name: EnqueueCallTask :one
|
||||
WITH caller AS (
|
||||
SELECT t.id, t.owner, t.repo, t.issue_number, t.title, t.body, t.labels, t.status, t.workflow, t.branch, t.plan, t.notes, t.pr_number, t.tokens_used, t.iterations, t.attempt, t.park_reason, t.watch_comment_id, t.park_class, t.remediation_rounds, t.retry_count, t.source, t.identity, t.binding_id, t.binding_version, t.review_payload, t.workflow_definition_version, t.workflow_definition_digest, t.workflow_definition_yaml, t.created_at, t.updated_at, t.review_cursor, t.inputs, t.org_id, t.workspace_id, t.call_parent_task_id, t.call_depth, t.outputs, t.review_gate, t.rereview_rounds, t.retry_mode, t.resume_from, t.resume_results, t.pending_reviews FROM tasks t WHERE t.id = $1 FOR UPDATE
|
||||
SELECT t.id, t.owner, t.repo, t.issue_number, t.title, t.body, t.labels, t.status, t.workflow, t.branch, t.plan, t.notes, t.pr_number, t.tokens_used, t.iterations, t.attempt, t.park_reason, t.watch_comment_id, t.park_class, t.remediation_rounds, t.retry_count, t.source, t.identity, t.binding_id, t.binding_version, t.review_payload, t.workflow_definition_version, t.workflow_definition_digest, t.workflow_definition_yaml, t.created_at, t.updated_at, t.review_cursor, t.inputs, t.org_id, t.workspace_id, t.call_parent_task_id, t.call_depth, t.outputs, t.review_gate, t.rereview_rounds, t.retry_mode, t.resume_from, t.resume_results, t.pending_reviews, t.origin FROM tasks t WHERE t.id = $1 FOR UPDATE
|
||||
)
|
||||
INSERT INTO tasks (owner, repo, issue_number, title, body, labels, workflow, source, identity, org_id, workspace_id, inputs, call_parent_task_id, call_depth)
|
||||
SELECT
|
||||
@@ -41,7 +41,7 @@ SELECT
|
||||
caller.id, caller.call_depth + 1
|
||||
FROM caller
|
||||
WHERE caller.status = 'running' AND caller.call_depth + 1 <= $7::int
|
||||
RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews
|
||||
RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin
|
||||
`
|
||||
|
||||
type EnqueueCallTaskParams struct {
|
||||
@@ -111,6 +111,7 @@ func (q *Queries) EnqueueCallTask(ctx context.Context, arg EnqueueCallTaskParams
|
||||
&i.ResumeFrom,
|
||||
&i.ResumeResults,
|
||||
&i.PendingReviews,
|
||||
&i.Origin,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -428,6 +428,7 @@ type Task struct {
|
||||
ResumeFrom string
|
||||
ResumeResults []byte
|
||||
PendingReviews []byte
|
||||
Origin string
|
||||
}
|
||||
|
||||
type ToolCall struct {
|
||||
|
||||
@@ -12,6 +12,79 @@ import (
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const activeTasksByOrigin = `-- name: ActiveTasksByOrigin :many
|
||||
SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin FROM tasks
|
||||
WHERE origin = $1 AND origin <> '' AND status IN ('queued', 'running')
|
||||
ORDER BY id
|
||||
`
|
||||
|
||||
// The queued and running tasks one conversation created, for its /stop.
|
||||
func (q *Queries) ActiveTasksByOrigin(ctx context.Context, origin string) ([]Task, error) {
|
||||
rows, err := q.db.Query(ctx, activeTasksByOrigin, origin)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []Task
|
||||
for rows.Next() {
|
||||
var i Task
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.Owner,
|
||||
&i.Repo,
|
||||
&i.IssueNumber,
|
||||
&i.Title,
|
||||
&i.Body,
|
||||
&i.Labels,
|
||||
&i.Status,
|
||||
&i.Workflow,
|
||||
&i.Branch,
|
||||
&i.Plan,
|
||||
&i.Notes,
|
||||
&i.PrNumber,
|
||||
&i.TokensUsed,
|
||||
&i.Iterations,
|
||||
&i.Attempt,
|
||||
&i.ParkReason,
|
||||
&i.WatchCommentID,
|
||||
&i.ParkClass,
|
||||
&i.RemediationRounds,
|
||||
&i.RetryCount,
|
||||
&i.Source,
|
||||
&i.Identity,
|
||||
&i.BindingID,
|
||||
&i.BindingVersion,
|
||||
&i.ReviewPayload,
|
||||
&i.WorkflowDefinitionVersion,
|
||||
&i.WorkflowDefinitionDigest,
|
||||
&i.WorkflowDefinitionYaml,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.ReviewCursor,
|
||||
&i.Inputs,
|
||||
&i.OrgID,
|
||||
&i.WorkspaceID,
|
||||
&i.CallParentTaskID,
|
||||
&i.CallDepth,
|
||||
&i.Outputs,
|
||||
&i.ReviewGate,
|
||||
&i.RereviewRounds,
|
||||
&i.RetryMode,
|
||||
&i.ResumeFrom,
|
||||
&i.ResumeResults,
|
||||
&i.PendingReviews,
|
||||
&i.Origin,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const appendPendingReview = `-- name: AppendPendingReview :execrows
|
||||
UPDATE tasks SET pending_reviews = CASE
|
||||
WHEN review_payload = $2::text THEN pending_reviews
|
||||
@@ -80,7 +153,7 @@ func (q *Queries) BeginRemediationTask(ctx context.Context, arg BeginRemediation
|
||||
const claimByIssue = `-- name: ClaimByIssue :one
|
||||
UPDATE tasks SET status = 'running', attempt = attempt + 1, outputs = '', updated_at = now()
|
||||
WHERE owner = $1 AND repo = $2 AND issue_number = $3 AND status = 'queued'
|
||||
RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews
|
||||
RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin
|
||||
`
|
||||
|
||||
type ClaimByIssueParams struct {
|
||||
@@ -139,6 +212,7 @@ func (q *Queries) ClaimByIssue(ctx context.Context, arg ClaimByIssueParams) (Tas
|
||||
&i.ResumeFrom,
|
||||
&i.ResumeResults,
|
||||
&i.PendingReviews,
|
||||
&i.Origin,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -153,7 +227,7 @@ WHERE id = (
|
||||
FOR UPDATE SKIP LOCKED
|
||||
LIMIT 1
|
||||
)
|
||||
RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews
|
||||
RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin
|
||||
`
|
||||
|
||||
// FOR UPDATE SKIP LOCKED replaces the SQLite single-writer assumption: two
|
||||
@@ -210,6 +284,7 @@ func (q *Queries) ClaimNextTask(ctx context.Context) (Task, error) {
|
||||
&i.ResumeFrom,
|
||||
&i.ResumeResults,
|
||||
&i.PendingReviews,
|
||||
&i.Origin,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -302,7 +377,7 @@ func (q *Queries) EnqueueIssue(ctx context.Context, arg EnqueueIssueParams) (int
|
||||
}
|
||||
|
||||
const insertChatTask = `-- name: InsertChatTask :one
|
||||
INSERT INTO tasks (owner, repo, issue_number, title, body, labels, workflow, source, identity, org_id, inputs)
|
||||
INSERT INTO tasks (owner, repo, issue_number, title, body, labels, workflow, source, identity, org_id, inputs, origin)
|
||||
VALUES (
|
||||
$1, $2,
|
||||
COALESCE((
|
||||
@@ -318,9 +393,10 @@ VALUES (
|
||||
ORDER BY m.created_at, m.org_id, m.workspace_id NULLS LAST LIMIT 1),
|
||||
'org-sys'
|
||||
),
|
||||
$8
|
||||
$8,
|
||||
$9
|
||||
)
|
||||
RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews
|
||||
RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin
|
||||
`
|
||||
|
||||
type InsertChatTaskParams struct {
|
||||
@@ -332,6 +408,7 @@ type InsertChatTaskParams struct {
|
||||
Workflow string
|
||||
Identity string
|
||||
Inputs string
|
||||
Origin string
|
||||
}
|
||||
|
||||
// The synthetic issue number keeps chat-sourced tasks off the forge's real
|
||||
@@ -351,6 +428,7 @@ func (q *Queries) InsertChatTask(ctx context.Context, arg InsertChatTaskParams)
|
||||
arg.Workflow,
|
||||
arg.Identity,
|
||||
arg.Inputs,
|
||||
arg.Origin,
|
||||
)
|
||||
var i Task
|
||||
err := row.Scan(
|
||||
@@ -398,6 +476,7 @@ func (q *Queries) InsertChatTask(ctx context.Context, arg InsertChatTaskParams)
|
||||
&i.ResumeFrom,
|
||||
&i.ResumeResults,
|
||||
&i.PendingReviews,
|
||||
&i.Origin,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -836,7 +915,7 @@ func (q *Queries) StampTaskBinding(ctx context.Context, arg StampTaskBindingPara
|
||||
}
|
||||
|
||||
const taskByID = `-- name: TaskByID :one
|
||||
SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews FROM tasks WHERE id = $1
|
||||
SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin FROM tasks WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) TaskByID(ctx context.Context, id int64) (Task, error) {
|
||||
@@ -887,12 +966,13 @@ func (q *Queries) TaskByID(ctx context.Context, id int64) (Task, error) {
|
||||
&i.ResumeFrom,
|
||||
&i.ResumeResults,
|
||||
&i.PendingReviews,
|
||||
&i.Origin,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const taskByIssue = `-- name: TaskByIssue :one
|
||||
SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews FROM tasks WHERE owner = $1 AND repo = $2 AND issue_number = $3
|
||||
SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin FROM tasks WHERE owner = $1 AND repo = $2 AND issue_number = $3
|
||||
`
|
||||
|
||||
type TaskByIssueParams struct {
|
||||
@@ -949,12 +1029,13 @@ func (q *Queries) TaskByIssue(ctx context.Context, arg TaskByIssueParams) (Task,
|
||||
&i.ResumeFrom,
|
||||
&i.ResumeResults,
|
||||
&i.PendingReviews,
|
||||
&i.Origin,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const taskByPR = `-- name: TaskByPR :one
|
||||
SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews FROM tasks WHERE owner = $1 AND repo = $2 AND pr_number = $3 AND status = $4
|
||||
SELECT id, owner, repo, issue_number, title, body, labels, status, workflow, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, park_class, remediation_rounds, retry_count, source, identity, binding_id, binding_version, review_payload, workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at, review_cursor, inputs, org_id, workspace_id, call_parent_task_id, call_depth, outputs, review_gate, rereview_rounds, retry_mode, resume_from, resume_results, pending_reviews, origin FROM tasks WHERE owner = $1 AND repo = $2 AND pr_number = $3 AND status = $4
|
||||
`
|
||||
|
||||
type TaskByPRParams struct {
|
||||
@@ -1020,6 +1101,7 @@ func (q *Queries) TaskByPR(ctx context.Context, arg TaskByPRParams) (Task, error
|
||||
&i.ResumeFrom,
|
||||
&i.ResumeResults,
|
||||
&i.PendingReviews,
|
||||
&i.Origin,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
@@ -60,7 +60,7 @@ SELECT status, count(*)::int AS count FROM tasks GROUP BY status;
|
||||
-- inputs is the chat task's own workflow inputs; a binding dispatch passes
|
||||
-- its inputs here too, so this insert is the single writer of the column and
|
||||
-- StampTaskBinding adds only the provenance.
|
||||
INSERT INTO tasks (owner, repo, issue_number, title, body, labels, workflow, source, identity, org_id, inputs)
|
||||
INSERT INTO tasks (owner, repo, issue_number, title, body, labels, workflow, source, identity, org_id, inputs, origin)
|
||||
VALUES (
|
||||
sqlc.arg(owner), sqlc.arg(repo),
|
||||
COALESCE((
|
||||
@@ -76,10 +76,17 @@ VALUES (
|
||||
ORDER BY m.created_at, m.org_id, m.workspace_id NULLS LAST LIMIT 1),
|
||||
'org-sys'
|
||||
),
|
||||
sqlc.arg(inputs)
|
||||
sqlc.arg(inputs),
|
||||
sqlc.arg(origin)
|
||||
)
|
||||
RETURNING *;
|
||||
|
||||
-- name: ActiveTasksByOrigin :many
|
||||
-- The queued and running tasks one conversation created, for its /stop.
|
||||
SELECT * FROM tasks
|
||||
WHERE origin = sqlc.arg(origin) AND origin <> '' AND status IN ('queued', 'running')
|
||||
ORDER BY id;
|
||||
|
||||
-- name: StampTaskBinding :exec
|
||||
UPDATE tasks SET binding_id = $2, binding_version = $3 WHERE id = $1;
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ func TestRetryTaskResume(t *testing.T) {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
db := pgstore.Open(t)
|
||||
if _, err := db.EnqueueChatTask(ctx, "", "", "resume", "", "tdd", "", nil); err != nil {
|
||||
if _, err := db.EnqueueChatTask(ctx, "", "", "resume", "", "tdd", "", "", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
run, err := db.ClaimNext(ctx)
|
||||
|
||||
@@ -59,7 +59,7 @@ func TestSecondReviewDuringRemediationIsQueued(t *testing.T) {
|
||||
func openTaskAtPROpen(t *testing.T, db *pgstore.TaskDB) int64 {
|
||||
t.Helper()
|
||||
ctx := t.Context()
|
||||
created, err := db.EnqueueChatTask(ctx, "acme", "widget", "a task", "", "tdd", "", nil)
|
||||
created, err := db.EnqueueChatTask(ctx, "acme", "widget", "a task", "", "tdd", "", "", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -153,8 +153,8 @@ func (s *Store) EnqueueIssue(ctx context.Context, owner, repo string, number int
|
||||
}
|
||||
|
||||
// EnqueueChatTask inserts a queued chat task with a store-allocated synthetic
|
||||
// issue number.
|
||||
func (s *Store) EnqueueChatTask(ctx context.Context, owner, repo, title, body, wf, identity string, inputs map[string]any) (*workflow.Task, error) {
|
||||
// issue number. origin names the conversation that created it, if any.
|
||||
func (s *Store) EnqueueChatTask(ctx context.Context, owner, repo, title, body, wf, identity, origin string, inputs map[string]any) (*workflow.Task, error) {
|
||||
encoded, err := task.EncodeInputs(inputs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -162,6 +162,7 @@ func (s *Store) EnqueueChatTask(ctx context.Context, owner, repo, title, body, w
|
||||
t, err := s.queries().InsertChatTask(ctx, postgresdb.InsertChatTaskParams{
|
||||
Owner: owner, Repo: repo, Title: title, Body: body, Workflow: wf, Identity: identity,
|
||||
Inputs: encoded,
|
||||
Origin: origin,
|
||||
FallbackIssueNumber: syntheticIssueNumberBase - 1,
|
||||
})
|
||||
if err != nil {
|
||||
@@ -175,7 +176,7 @@ func (s *Store) EnqueueChatTask(ctx context.Context, owner, repo, title, body, w
|
||||
// inputs travel with the insert, so a failed stamp leaves a task whose inputs
|
||||
// are already right and whose provenance is absent, never the reverse.
|
||||
func (s *Store) EnqueueBindingTask(ctx context.Context, owner, repo, title, body, wf, identity, bindingID string, bindingVersion int, inputs map[string]any) (*workflow.Task, error) {
|
||||
t, err := s.EnqueueChatTask(ctx, owner, repo, title, body, wf, identity, inputs)
|
||||
t, err := s.EnqueueChatTask(ctx, owner, repo, title, body, wf, identity, "", inputs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -855,3 +856,17 @@ func (s *Store) CallStatus(ctx context.Context, callerTaskID, callTaskID int64)
|
||||
}
|
||||
return callee.Status, detail, outputs, nil
|
||||
}
|
||||
|
||||
// ActiveTasksByOrigin returns the queued and running tasks the conversation
|
||||
// origin created.
|
||||
func (s *Store) ActiveTasksByOrigin(ctx context.Context, origin string) ([]*workflow.Task, error) {
|
||||
rows, err := s.queries().ActiveTasksByOrigin(ctx, origin)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("store: active tasks by origin: %w", err)
|
||||
}
|
||||
out := make([]*workflow.Task, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
out = append(out, taskFromRow(row))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
)
|
||||
|
||||
// A conversation's /stop finds the queued and running tasks it created, and
|
||||
// only those: not another conversation's, not finished ones, not originless.
|
||||
func TestActiveTasksByOrigin(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
db := pgstore.Open(t)
|
||||
enqueue := func(origin string) int64 {
|
||||
created, err := db.EnqueueChatTask(ctx, "", "", "work", "", "tdd", "", origin, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return created.ID
|
||||
}
|
||||
running, queued, finished := enqueue("telegram:1"), enqueue("telegram:1"), enqueue("telegram:1")
|
||||
enqueue("telegram:2")
|
||||
enqueue("")
|
||||
if err := db.Transition(ctx, running, taskstate.Queued, taskstate.Running, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Transition(ctx, finished, taskstate.Queued, taskstate.Declined, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
origin string
|
||||
want []int64
|
||||
}{
|
||||
{"telegram:1", []int64{running, queued}},
|
||||
{"telegram:2", []int64{finished + 1}},
|
||||
{"", nil},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
tasks, err := db.ActiveTasksByOrigin(ctx, tc.origin)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var got []int64
|
||||
for _, task := range tasks {
|
||||
got = append(got, task.ID)
|
||||
}
|
||||
if !slices.Equal(got, tc.want) {
|
||||
t.Errorf("origin %q: tasks %v, want %v", tc.origin, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -78,12 +78,24 @@ func (c *Client) EnqueueIssue(ctx context.Context, owner, repo string, number in
|
||||
return r.Inserted, nil
|
||||
}
|
||||
|
||||
func (c *Client) EnqueueChatTask(ctx context.Context, owner, repo, title, body, wf, identity string, inputs map[string]any) (*task.Task, error) {
|
||||
func (c *Client) ActiveTasksByOrigin(ctx context.Context, origin string) ([]*task.Task, error) {
|
||||
r, err := c.client.ActiveTasksByOrigin(ctx, &pb.ActiveTasksByOriginRequest{Origin: origin})
|
||||
if err != nil {
|
||||
return nil, unmapError(err)
|
||||
}
|
||||
out := make([]*task.Task, 0, len(r.Tasks))
|
||||
for _, t := range r.Tasks {
|
||||
out = append(out, taskValue(t))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *Client) EnqueueChatTask(ctx context.Context, owner, repo, title, body, wf, identity, origin string, inputs map[string]any) (*task.Task, error) {
|
||||
encoded, err := task.EncodeInputs(inputs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r, err := c.client.EnqueueChatTask(ctx, &pb.EnqueueChatTaskRequest{Owner: owner, Repo: repo, Title: title, Body: body, Workflow: wf, Identity: identity, InputsJson: encoded})
|
||||
r, err := c.client.EnqueueChatTask(ctx, &pb.EnqueueChatTaskRequest{Owner: owner, Repo: repo, Title: title, Body: body, Workflow: wf, Identity: identity, InputsJson: encoded, Origin: origin})
|
||||
if err != nil {
|
||||
return nil, unmapError(err)
|
||||
}
|
||||
|
||||
@@ -184,12 +184,24 @@ func (s *server) EnqueueIssue(ctx context.Context, r *pb.EnqueueIssueRequest) (*
|
||||
return &pb.EnqueueIssueResponse{Inserted: inserted}, nil
|
||||
}
|
||||
|
||||
func (s *server) ActiveTasksByOrigin(ctx context.Context, r *pb.ActiveTasksByOriginRequest) (*pb.ActiveTasksByOriginResponse, error) {
|
||||
tasks, err := s.deps.Tasks.ActiveTasksByOrigin(ctx, r.Origin)
|
||||
if err != nil {
|
||||
return nil, s.logErr("ActiveTasksByOrigin", err)
|
||||
}
|
||||
out := make([]*pb.Task, 0, len(tasks))
|
||||
for _, t := range tasks {
|
||||
out = append(out, taskProto(t))
|
||||
}
|
||||
return &pb.ActiveTasksByOriginResponse{Tasks: out}, nil
|
||||
}
|
||||
|
||||
func (s *server) EnqueueChatTask(ctx context.Context, r *pb.EnqueueChatTaskRequest) (*pb.EnqueueChatTaskResponse, error) {
|
||||
inputs, err := task.DecodeInputs(r.InputsJson)
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||
}
|
||||
t, err := s.deps.Tasks.EnqueueChatTask(ctx, r.Owner, r.Repo, r.Title, r.Body, r.Workflow, r.Identity, inputs)
|
||||
t, err := s.deps.Tasks.EnqueueChatTask(ctx, r.Owner, r.Repo, r.Title, r.Body, r.Workflow, r.Identity, r.Origin, inputs)
|
||||
if err != nil {
|
||||
return nil, s.logErr("EnqueueChatTask", err)
|
||||
}
|
||||
|
||||
+10
-89
@@ -22,7 +22,6 @@ import (
|
||||
type ChatService struct {
|
||||
Contract messaging.ChatContract
|
||||
Updates ChatUpdateService
|
||||
Dangerous *DangerousService
|
||||
updateMu sync.Mutex
|
||||
updateInProgress bool
|
||||
}
|
||||
@@ -126,14 +125,6 @@ type chatToolView struct {
|
||||
Failed bool `json:"failed"`
|
||||
}
|
||||
|
||||
type dangerousRequest struct {
|
||||
Spec string `json:"spec"`
|
||||
}
|
||||
|
||||
type dangerousDecisionRequest struct {
|
||||
Decision string `json:"decision"`
|
||||
}
|
||||
|
||||
func (s *Server) chatReady(w http.ResponseWriter) (*ChatService, bool) {
|
||||
if s.Chat == nil || s.Chat.Contract == nil {
|
||||
http.Error(w, "chat is not configured", http.StatusNotImplemented)
|
||||
@@ -176,30 +167,21 @@ func (s *Server) handleChatSessions(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
writeJSON(w, map[string]any{
|
||||
"sessions": out,
|
||||
"models": snapshot.Models,
|
||||
"models_by_provider": snapshot.ModelsByProvider,
|
||||
"providers": snapshot.Providers,
|
||||
"active_model": snapshot.ActiveModel,
|
||||
"active_provider": snapshot.ActiveProvider,
|
||||
"personas": snapshot.Personas,
|
||||
"active_personas": active,
|
||||
"commands": chatCommandSpecs(chat),
|
||||
"restart_available": snapshot.RestartAvailable,
|
||||
"dangerous_available": chat.Dangerous != nil,
|
||||
"sessions": out,
|
||||
"models": snapshot.Models,
|
||||
"models_by_provider": snapshot.ModelsByProvider,
|
||||
"providers": snapshot.Providers,
|
||||
"active_model": snapshot.ActiveModel,
|
||||
"active_provider": snapshot.ActiveProvider,
|
||||
"personas": snapshot.Personas,
|
||||
"active_personas": active,
|
||||
"commands": chatCommandSpecs(chat),
|
||||
"restart_available": snapshot.RestartAvailable,
|
||||
})
|
||||
}
|
||||
|
||||
func chatCommandSpecs(chat *ChatService) []messaging.CommandSpec {
|
||||
specs := messaging.LocalCommandSpecs()
|
||||
if chat.Dangerous != nil {
|
||||
specs = append(
|
||||
specs,
|
||||
messaging.CommandSpec{Command: "/rollback", Description: "Request approval to restore a filesystem checkpoint", Usage: "/rollback [number]"},
|
||||
messaging.CommandSpec{Command: "/stop", Description: "Request approval to terminate a background process", Usage: "/stop <process-name>"},
|
||||
messaging.CommandSpec{Command: "/deny", Description: "Deny a pending dangerous action", Usage: "/deny <action-id>"},
|
||||
)
|
||||
}
|
||||
return specs
|
||||
}
|
||||
|
||||
@@ -618,67 +600,6 @@ func (s *Server) handleChatUpdateInstall(w http.ResponseWriter, r *http.Request)
|
||||
writeJSON(w, map[string]any{"ok": true, "progress": progress, "result": result})
|
||||
}
|
||||
|
||||
func (s *Server) handleChatDangerousState(w http.ResponseWriter, r *http.Request) {
|
||||
chat, ok := s.chatReady(w)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if chat.Dangerous == nil {
|
||||
http.Error(w, "dangerous sandbox actions are not configured", http.StatusNotImplemented)
|
||||
return
|
||||
}
|
||||
checkpoints, err := chat.Dangerous.Checkpoints(r.Context())
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
writeJSON(w, map[string]any{"checkpoints": checkpoints, "pending": chat.Dangerous.Pending()})
|
||||
}
|
||||
|
||||
func (s *Server) handleChatDangerousRequest(w http.ResponseWriter, r *http.Request) {
|
||||
chat, ok := s.chatReady(w)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if chat.Dangerous == nil {
|
||||
http.Error(w, "dangerous sandbox actions are not configured", http.StatusNotImplemented)
|
||||
return
|
||||
}
|
||||
var req dangerousRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || strings.TrimSpace(req.Spec) == "" {
|
||||
http.Error(w, "spec is required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
action, result, executed, err := chat.Dangerous.Request(r.Context(), r.PathValue("kind"), req.Spec)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
writeJSON(w, map[string]any{"action": action, "result": result, "executed": executed})
|
||||
}
|
||||
|
||||
func (s *Server) handleChatDangerousDecision(w http.ResponseWriter, r *http.Request) {
|
||||
chat, ok := s.chatReady(w)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if chat.Dangerous == nil {
|
||||
http.Error(w, "dangerous sandbox actions are not configured", http.StatusNotImplemented)
|
||||
return
|
||||
}
|
||||
var req dangerousDecisionRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || strings.TrimSpace(req.Decision) == "" {
|
||||
http.Error(w, "decision is required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
result, err := chat.Dangerous.Decide(r.Context(), r.PathValue("id"), req.Decision)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusConflict)
|
||||
return
|
||||
}
|
||||
writeJSON(w, map[string]any{"ok": true, "result": result})
|
||||
}
|
||||
|
||||
func newChatSourceID() string {
|
||||
id, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
|
||||
@@ -104,7 +104,7 @@ func (s *Server) handleWorkRequest(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, err.Error(), status)
|
||||
return
|
||||
}
|
||||
created, err := s.Store.EnqueueChatTask(r.Context(), owner, repo, request.Title, request.Instructions, request.Workflow, request.Identity, request.Inputs)
|
||||
created, err := s.Store.EnqueueChatTask(r.Context(), owner, repo, request.Title, request.Instructions, request.Workflow, request.Identity, "", request.Inputs)
|
||||
if err != nil {
|
||||
s.logf("work request enqueue failed", "err", err)
|
||||
http.Error(w, "work request rejected", http.StatusBadRequest)
|
||||
|
||||
@@ -1,160 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
const (
|
||||
dangerousApprovalLifetime = 10 * time.Minute
|
||||
// The "permanent" decision on the wire grants an extended, but still
|
||||
// bounded, approval: 24 hours, then requests queue again.
|
||||
extendedApprovalLifetime = 24 * time.Hour
|
||||
)
|
||||
|
||||
// DangerousService adapts the daemon-owned sandbox authority to an
|
||||
// interactive approval workflow. It intentionally has no host process or
|
||||
// filesystem access of its own.
|
||||
type DangerousService struct {
|
||||
Authority messaging.DangerousCommandAuthority
|
||||
|
||||
mu sync.Mutex
|
||||
actions map[string]dangerousAction
|
||||
extended map[string]time.Time
|
||||
}
|
||||
|
||||
type dangerousAction struct {
|
||||
ID string
|
||||
Kind string
|
||||
Spec string
|
||||
Description string
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
type DangerousActionView struct {
|
||||
ID string `json:"id"`
|
||||
Kind string `json:"kind"`
|
||||
Description string `json:"description"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
}
|
||||
|
||||
func NewDangerousService(authority messaging.DangerousCommandAuthority) *DangerousService {
|
||||
return &DangerousService{
|
||||
Authority: authority,
|
||||
actions: make(map[string]dangerousAction),
|
||||
extended: make(map[string]time.Time),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *DangerousService) enabled() error {
|
||||
if s == nil || s.Authority == nil {
|
||||
return errors.New("dangerous sandbox actions are not configured")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *DangerousService) Checkpoints(ctx context.Context) ([]messaging.CheckpointInfo, error) {
|
||||
if err := s.enabled(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.Authority.ListCheckpoints(ctx)
|
||||
}
|
||||
|
||||
func (s *DangerousService) Pending() []DangerousActionView {
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
now := time.Now()
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
views := make([]DangerousActionView, 0, len(s.actions))
|
||||
for id, action := range s.actions {
|
||||
if !action.ExpiresAt.After(now) {
|
||||
delete(s.actions, id)
|
||||
continue
|
||||
}
|
||||
views = append(views, DangerousActionView{
|
||||
ID: action.ID, Kind: action.Kind, Description: action.Description, ExpiresAt: action.ExpiresAt,
|
||||
})
|
||||
}
|
||||
return views
|
||||
}
|
||||
|
||||
// Request creates a pending action unless the local operator has granted a
|
||||
// still-valid extended (24-hour) approval for this operation family.
|
||||
func (s *DangerousService) Request(ctx context.Context, kind, spec string) (DangerousActionView, string, bool, error) {
|
||||
if err := s.enabled(); err != nil {
|
||||
return DangerousActionView{}, "", false, err
|
||||
}
|
||||
kind = strings.ToLower(strings.TrimSpace(kind))
|
||||
spec = strings.TrimSpace(spec)
|
||||
if kind != "rollback" && kind != "stop" || spec == "" {
|
||||
return DangerousActionView{}, "", false, errors.New("invalid dangerous action")
|
||||
}
|
||||
description := fmt.Sprintf("%s %s", kind, spec)
|
||||
s.mu.Lock()
|
||||
now := time.Now()
|
||||
if expires := s.extended[kind]; expires.After(now) {
|
||||
s.mu.Unlock()
|
||||
result, err := s.execute(ctx, kind, spec)
|
||||
return DangerousActionView{Kind: kind, Description: description, ExpiresAt: expires}, result, true, err
|
||||
}
|
||||
id := uuid.NewString()
|
||||
action := dangerousAction{ID: id, Kind: kind, Spec: spec, Description: description, ExpiresAt: now.Add(dangerousApprovalLifetime)}
|
||||
s.actions[id] = action
|
||||
s.mu.Unlock()
|
||||
return DangerousActionView{ID: id, Kind: kind, Description: description, ExpiresAt: action.ExpiresAt}, "", false, nil
|
||||
}
|
||||
|
||||
func (s *DangerousService) Decide(ctx context.Context, id, decision string) (string, error) {
|
||||
if err := s.enabled(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
s.mu.Lock()
|
||||
action, ok := s.actions[id]
|
||||
if ok {
|
||||
delete(s.actions, id)
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if !ok || !action.ExpiresAt.After(time.Now()) {
|
||||
return "", errors.New("dangerous action is expired or unknown")
|
||||
}
|
||||
switch strings.ToLower(strings.TrimSpace(decision)) {
|
||||
case "deny":
|
||||
return "Command denied.", nil
|
||||
case "approve":
|
||||
return s.execute(ctx, action.Kind, action.Spec)
|
||||
case "permanent":
|
||||
// Wire kind "permanent" grants the 24-hour extended approval, not an
|
||||
// unlimited one; the literal string is part of the contract with the
|
||||
// channels that dispatch decisions (see the telegram gateway).
|
||||
s.mu.Lock()
|
||||
s.extended[action.Kind] = time.Now().Add(extendedApprovalLifetime)
|
||||
s.mu.Unlock()
|
||||
return s.execute(ctx, action.Kind, action.Spec)
|
||||
default:
|
||||
return "", errors.New("decision must be approve, permanent, or deny")
|
||||
}
|
||||
}
|
||||
|
||||
func (s *DangerousService) execute(ctx context.Context, kind, spec string) (string, error) {
|
||||
if kind == "stop" {
|
||||
if err := s.Authority.StopProcess(ctx, spec); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "Process stopped.", nil
|
||||
}
|
||||
var checkpoint int
|
||||
if _, err := fmt.Sscan(spec, &checkpoint); err != nil || checkpoint <= 0 {
|
||||
return "", errors.New("checkpoint must be a positive number")
|
||||
}
|
||||
return s.Authority.Rollback(ctx, checkpoint)
|
||||
}
|
||||
@@ -360,9 +360,6 @@ func (s *Server) registerChatRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/chat/update", s.handleChatUpdate)
|
||||
mux.HandleFunc("POST /api/chat/update/defer", s.handleChatUpdateDefer)
|
||||
mux.HandleFunc("POST /api/chat/update/install", s.handleChatUpdateInstall)
|
||||
mux.HandleFunc("GET /api/chat/dangerous", s.handleChatDangerousState)
|
||||
mux.HandleFunc("POST /api/chat/dangerous/{kind}", s.handleChatDangerousRequest)
|
||||
mux.HandleFunc("POST /api/chat/dangerous/{id}/decision", s.handleChatDangerousDecision)
|
||||
}
|
||||
|
||||
func (s *Server) Handler() http.Handler {
|
||||
|
||||
Reference in new issue
Block a user