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:
sam committed 2026-10-06 01:12:28 +11:00
1 parent 27b16603ff
commit c56344ea41
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
}
+3 -3
View File
@@ -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
}
+91 -14
View File
@@ -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
}
+1 -5
View File
@@ -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"},
}
-618
View File
@@ -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.
}
+116
View File
@@ -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
}
+16 -31
View File
@@ -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,
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
}
+3 -18
View File
@@ -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
}
+6
View File
@@ -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
+1 -1
View File
@@ -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.
+62
View File
@@ -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
+3 -1
View File
@@ -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) {
+25
View File
@@ -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))
}
+1
View File
@@ -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)
+2 -2
View File
@@ -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)
}
+18 -3
View File
@@ -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)
}
}
}
+14 -2
View File
@@ -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)
}
+13 -1
View File
@@ -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
View File
@@ -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 {
+1 -1
View File
@@ -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)
-160
View File
@@ -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)
}
-3
View File
@@ -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 {
+6
View File
@@ -12,6 +12,7 @@ service ChatService {
rpc Route(RouteRequest) returns (RouteResponse);
rpc Stream(StreamRequest) returns (stream StreamResponse);
rpc Cancel(CancelRequest) returns (CancelResponse);
rpc StopTasks(StopTasksRequest) returns (StopTasksResponse);
rpc SetPersona(SetPersonaRequest) returns (SetPersonaResponse);
rpc ApplyTaskAction(ApplyTaskActionRequest) returns (ApplyTaskActionResponse);
rpc ApplyOperatorTaskAction(ApplyOperatorTaskActionRequest) returns (ApplyOperatorTaskActionResponse);
@@ -153,6 +154,11 @@ message StreamResponse {
}
message CancelRequest { string session_id = 1; }
message CancelResponse { bool cancelled = 1; int64 dropped = 2; }
// StopTasksRequest stops task_id, or with task_id zero every queued or running
// task the conversation origin created.
message StopTasksRequest { string origin = 1; int64 task_id = 2; }
// error reports tasks that could not be stopped alongside those that were.
message StopTasksResponse { repeated int64 stopped = 1; string error = 2; }
message SetPersonaRequest { string session_id = 1; string name = 2; }
message SetPersonaResponse { bool found = 1; }
message ApplyTaskActionRequest { string identity = 1; int64 task_id = 2; string action = 3; string instructions = 4; repeated string findings = 5; }
+6
View File
@@ -46,6 +46,7 @@ service StateStoreService {
// Lifecycle
rpc EnqueueIssue(EnqueueIssueRequest) returns (EnqueueIssueResponse);
rpc EnqueueChatTask(EnqueueChatTaskRequest) returns (EnqueueChatTaskResponse);
rpc ActiveTasksByOrigin(ActiveTasksByOriginRequest) returns (ActiveTasksByOriginResponse);
rpc ClaimNext(ClaimNextRequest) returns (ClaimNextResponse);
rpc ClaimByIssue(ClaimByIssueRequest) returns (ClaimByIssueResponse);
rpc Transition(TransitionRequest) returns (TransitionResponse);
@@ -607,6 +608,9 @@ message EnqueueIssueRequest {
}
message EnqueueIssueResponse { bool inserted = 1; }
message ActiveTasksByOriginRequest { string origin = 1; }
message ActiveTasksByOriginResponse { repeated Task tasks = 1; }
message EnqueueChatTaskRequest {
string owner = 1;
string repo = 2;
@@ -618,6 +622,8 @@ message EnqueueChatTaskRequest {
// EnqueueBindingTaskRequest carries. A chat task sets them at insert
// time: it has no binding provenance to stamp afterwards.
string inputs_json = 7;
// origin names the conversation that created the task; empty for none.
string origin = 8;
}
message EnqueueChatTaskResponse { Task task = 1; }
+1 -1
View File
@@ -1 +1 @@
.vue-flow{z-index:0;direction:ltr;width:100%;height:100%;position:relative;overflow:hidden}.vue-flow__container{width:100%;height:100%;position:absolute;top:0;left:0}.vue-flow__pane{z-index:1}.vue-flow__pane.draggable{cursor:grab}.vue-flow__pane.selection{cursor:pointer}.vue-flow__pane.dragging{cursor:grabbing}.vue-flow__transformationpane{transform-origin:0 0;z-index:2;pointer-events:none}.vue-flow__viewport{z-index:4;overflow:clip}.vue-flow__selection{z-index:6}.vue-flow__edge-labels{pointer-events:none;-webkit-user-select:none;user-select:none;width:100%;height:100%;position:absolute}.vue-flow__nodesselection-rect:focus,.vue-flow__nodesselection-rect:focus-visible{outline:none}.vue-flow .vue-flow__edges{pointer-events:none;overflow:visible}.vue-flow__edge-path,.vue-flow__connection-path{stroke:#b1b1b7;stroke-width:1px;fill:none}.vue-flow__edge{pointer-events:visibleStroke;cursor:pointer}.vue-flow__edge.animated path{stroke-dasharray:5;animation:.5s linear infinite dashdraw}.vue-flow__edge.animated path.vue-flow__edge-interaction{stroke-dasharray:none;animation:none}.vue-flow__edge.inactive{pointer-events:none}.vue-flow__edge.selected,.vue-flow__edge:focus,.vue-flow__edge:focus-visible{outline:none}.vue-flow__edge.selected .vue-flow__edge-path,.vue-flow__edge:focus .vue-flow__edge-path,.vue-flow__edge:focus-visible .vue-flow__edge-path{stroke:#555}.vue-flow__edge-textwrapper{pointer-events:all}.vue-flow__edge-textbg{fill:#fff}.vue-flow__edge-text{pointer-events:none;-webkit-user-select:none;user-select:none}.vue-flow__connection{pointer-events:none}.vue-flow__connection .animated{stroke-dasharray:5;animation:.5s linear infinite dashdraw}.vue-flow__connectionline{z-index:1001}.vue-flow__nodes{pointer-events:none;transform-origin:0 0}.vue-flow__node{-webkit-user-select:none;user-select:none;pointer-events:all;transform-origin:0 0;box-sizing:border-box;cursor:default;position:absolute}.vue-flow__node.draggable{cursor:grab;pointer-events:all}.vue-flow__node.draggable.dragging{cursor:grabbing}.vue-flow__nodesselection{z-index:3;transform-origin:0 0;pointer-events:none}.vue-flow__nodesselection-rect{pointer-events:all;cursor:grab;position:absolute}.vue-flow__nodesselection-rect.dragging{cursor:grabbing}.vue-flow__handle{pointer-events:none;min-width:5px;min-height:5px;position:absolute}.vue-flow__handle.connectable{pointer-events:all;cursor:crosshair}.vue-flow__handle-bottom{bottom:0;left:50%;transform:translate(-50%,50%)}.vue-flow__handle-top{top:0;left:50%;transform:translate(-50%,-50%)}.vue-flow__handle-left{top:50%;left:0;transform:translate(-50%,-50%)}.vue-flow__handle-right{top:50%;right:0;transform:translate(50%,-50%)}.vue-flow__edgeupdater{cursor:move;pointer-events:all}.vue-flow__panel{z-index:5;margin:15px;position:absolute}.vue-flow__panel.top{top:0}.vue-flow__panel.bottom{bottom:0}.vue-flow__panel.left{left:0}.vue-flow__panel.right{right:0}.vue-flow__panel.center{left:50%;transform:translate(-50%)}@keyframes dashdraw{0%{stroke-dashoffset:10px}}.vue-flow__controls{box-shadow:0 0 2px 1px #00000014}.vue-flow__controls-button{box-sizing:content-box;cursor:pointer;-webkit-user-select:none;user-select:none;background:#fefefe;border:none;border-bottom:1px solid #eee;justify-content:center;align-items:center;width:16px;height:16px;padding:5px;display:flex}.vue-flow__controls-button svg{width:100%;max-width:12px;max-height:12px}.vue-flow__controls-button:hover{background:#f4f4f4}.vue-flow__controls-button:disabled{pointer-events:none}.vue-flow__controls-button:disabled svg{fill-opacity:.4}.workflow-flow-edge path{stroke:var(--color-muted-foreground);stroke-width:1.5px}.workflow-data-edge path{stroke:var(--color-primary);stroke-dasharray:5 4;stroke-width:1.25px}@keyframes step-running{50%{box-shadow:0 0 0 4px color-mix(in oklab, var(--color-info) 30%, transparent)}}.step-running{animation:1.6s ease-in-out infinite step-running}.workflow-canvas .vue-flow__controls{box-shadow:none}.workflow-canvas .vue-flow__controls-button{background:var(--color-card);border-color:var(--color-border);fill:var(--color-foreground)}.workflow-canvas .vue-flow__controls-button:hover{background:var(--color-secondary)}@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){:root,:host{--shimmer-angle:20deg}*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-space-y-reverse:0;--tw-space-x-reverse:0;--tw-divide-x-reverse:0;--tw-border-style:solid;--tw-divide-y-reverse:0;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--twLine truncated
.vue-flow{z-index:0;direction:ltr;width:100%;height:100%;position:relative;overflow:hidden}.vue-flow__container{width:100%;height:100%;position:absolute;top:0;left:0}.vue-flow__pane{z-index:1}.vue-flow__pane.draggable{cursor:grab}.vue-flow__pane.selection{cursor:pointer}.vue-flow__pane.dragging{cursor:grabbing}.vue-flow__transformationpane{transform-origin:0 0;z-index:2;pointer-events:none}.vue-flow__viewport{z-index:4;overflow:clip}.vue-flow__selection{z-index:6}.vue-flow__edge-labels{pointer-events:none;-webkit-user-select:none;user-select:none;width:100%;height:100%;position:absolute}.vue-flow__nodesselection-rect:focus,.vue-flow__nodesselection-rect:focus-visible{outline:none}.vue-flow .vue-flow__edges{pointer-events:none;overflow:visible}.vue-flow__edge-path,.vue-flow__connection-path{stroke:#b1b1b7;stroke-width:1px;fill:none}.vue-flow__edge{pointer-events:visibleStroke;cursor:pointer}.vue-flow__edge.animated path{stroke-dasharray:5;animation:.5s linear infinite dashdraw}.vue-flow__edge.animated path.vue-flow__edge-interaction{stroke-dasharray:none;animation:none}.vue-flow__edge.inactive{pointer-events:none}.vue-flow__edge.selected,.vue-flow__edge:focus,.vue-flow__edge:focus-visible{outline:none}.vue-flow__edge.selected .vue-flow__edge-path,.vue-flow__edge:focus .vue-flow__edge-path,.vue-flow__edge:focus-visible .vue-flow__edge-path{stroke:#555}.vue-flow__edge-textwrapper{pointer-events:all}.vue-flow__edge-textbg{fill:#fff}.vue-flow__edge-text{pointer-events:none;-webkit-user-select:none;user-select:none}.vue-flow__connection{pointer-events:none}.vue-flow__connection .animated{stroke-dasharray:5;animation:.5s linear infinite dashdraw}.vue-flow__connectionline{z-index:1001}.vue-flow__nodes{pointer-events:none;transform-origin:0 0}.vue-flow__node{-webkit-user-select:none;user-select:none;pointer-events:all;transform-origin:0 0;box-sizing:border-box;cursor:default;position:absolute}.vue-flow__node.draggable{cursor:grab;pointer-events:all}.vue-flow__node.draggable.dragging{cursor:grabbing}.vue-flow__nodesselection{z-index:3;transform-origin:0 0;pointer-events:none}.vue-flow__nodesselection-rect{pointer-events:all;cursor:grab;position:absolute}.vue-flow__nodesselection-rect.dragging{cursor:grabbing}.vue-flow__handle{pointer-events:none;min-width:5px;min-height:5px;position:absolute}.vue-flow__handle.connectable{pointer-events:all;cursor:crosshair}.vue-flow__handle-bottom{bottom:0;left:50%;transform:translate(-50%,50%)}.vue-flow__handle-top{top:0;left:50%;transform:translate(-50%,-50%)}.vue-flow__handle-left{top:50%;left:0;transform:translate(-50%,-50%)}.vue-flow__handle-right{top:50%;right:0;transform:translate(50%,-50%)}.vue-flow__edgeupdater{cursor:move;pointer-events:all}.vue-flow__panel{z-index:5;margin:15px;position:absolute}.vue-flow__panel.top{top:0}.vue-flow__panel.bottom{bottom:0}.vue-flow__panel.left{left:0}.vue-flow__panel.right{right:0}.vue-flow__panel.center{left:50%;transform:translate(-50%)}@keyframes dashdraw{0%{stroke-dashoffset:10px}}.vue-flow__controls{box-shadow:0 0 2px 1px #00000014}.vue-flow__controls-button{box-sizing:content-box;cursor:pointer;-webkit-user-select:none;user-select:none;background:#fefefe;border:none;border-bottom:1px solid #eee;justify-content:center;align-items:center;width:16px;height:16px;padding:5px;display:flex}.vue-flow__controls-button svg{width:100%;max-width:12px;max-height:12px}.vue-flow__controls-button:hover{background:#f4f4f4}.vue-flow__controls-button:disabled{pointer-events:none}.vue-flow__controls-button:disabled svg{fill-opacity:.4}.workflow-flow-edge path{stroke:var(--color-muted-foreground);stroke-width:1.5px}.workflow-data-edge path{stroke:var(--color-primary);stroke-dasharray:5 4;stroke-width:1.25px}@keyframes step-running{50%{box-shadow:0 0 0 4px color-mix(in oklab, var(--color-info) 30%, transparent)}}.step-running{animation:1.6s ease-in-out infinite step-running}.workflow-canvas .vue-flow__controls{box-shadow:none}.workflow-canvas .vue-flow__controls-button{background:var(--color-card);border-color:var(--color-border);fill:var(--color-foreground)}.workflow-canvas .vue-flow__controls-button:hover{background:var(--color-secondary)}@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){:root,:host{--shimmer-angle:20deg}*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-space-y-reverse:0;--tw-space-x-reverse:0;--tw-divide-x-reverse:0;--tw-border-style:solid;--tw-divide-y-reverse:0;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--twLine truncated
+1 -1
View File
@@ -3,7 +3,7 @@ var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],en
`&&(e.tagName===`PRE`||e.tagName===`TEXTAREA`)&&(n=n.slice(1));let{textContent:r}=e;r!==n&&r!==n.replace(/\r\n|\r/g,`
`)&&(pi(e,0)||ri(),e.textContent=t.children)}if(d){if(_||b||!o||f&48){let t=e.tagName.includes(`-`),i=e.namespaceURI.includes(`svg`)?`svg`:e.namespaceURI.includes(`MathML`)?`mathml`:void 0;for(let a in d)if(_&&(a.endsWith(`value`)||a===`indeterminate`)||s(a)&&!O(a)||a[0]===`.`||t&&!O(a)||u&&u.includes(a)){if(ui(e,a,d[a]))continue;r(e,a,null,d[a],i,n)}}else if(d.onClick)r(e,`onClick`,null,d.onClick,void 0,n);else if(f&4&&$t(d.style))for(let e in d.style)d.style[e]}let x;(x=d&&d.onVnodeBeforeMount)&&us(x,n,t),h&&lr(t,null,n,`beforeMount`),((x=d&&d.onVnodeMounted)||h||l)&&Ho(()=>{x&&us(x,n,t),l&&g.enter(e),h&&lr(t,null,n,`mounted`)},i)}return e.nextSibling},m=(e,t,r,o,s,c,u)=>{u||=!!t.dynamicChildren;let d=t.children,p=d.length,m=!1;for(let t=0;t<p;t++){let h=u?d[t]:d[t]=ss(d[t]),g=h.type===Wo;e?(g&&!u&&t+1<p&&ss(d[t+1]).type===Wo&&(l(i(e.data.slice(h.children.length)),r,a(e)),e.data=h.children),e=f(e,h,o,s,c,u)):g&&!h.children?l(h.el=i(``),r):(m||(m=!0,pi(r,1)||ri()),n(null,h,r,null,o,s,oi(r),c))}return e},h=(e,t,n,r,i,s)=>{let{slotScopeIds:c}=t;c&&(i=i?i.concat(c):c);let d=o(e),f=m(a(e),t,d,n,r,i,s);return f&&si(f)&&f.data===`]`?a(t.anchor=f):(ri(),l(t.anchor=u(`]`),d,f),f)},g=(e,t,r,i,s,l)=>{if(hi(e,t)||ri(),t.el=null,l){let t=_(e);for(;;){let n=a(e);if(n&&n!==t)c(n);else break}}let u=a(e),d=o(e);return c(e),n(null,t,d,u,r,i,oi(d),s),r&&(r.vnode.el=t.el,eo(r,t.el)),u},_=(e,t=`[`,n=`]`)=>{let r=0;for(;e;)if(e=a(e),e&&si(e)&&(e.data===t&&r++,e.data===n)){if(r===0)return a(e);r--}return e},v=(e,t,n)=>{let r=t.parentNode;r&&r.replaceChild(e,t);let i=n;for(;i;)i.vnode.el===t&&(i.vnode.el=i.subTree.el=e),i=i.parent},y=e=>e.nodeType===1&&e.tagName===`TEMPLATE`;return[d,f]}var li=new Set([`src`,`srcset`,`href`,`poster`]);function ui(e,t,n){return li.has(t)?e.getAttribute(t)===(n==null?null:`${n}`):!1}var di=`data-allow-mismatch`,fi={0:`text`,1:`children`,2:`class`,3:`style`,4:`attribute`};function pi(e,t){if(t===0||t===1)for(;e&&!e.hasAttribute(di);)e=e.parentElement;return mi(e&&e.getAttribute(di),t)}function mi(e,t){if(e==null)return!1;if(e===``)return!0;{let n=e.split(`,`);return t===0&&n.includes(`children`)?!0:n.includes(fi[t])}}function hi(e,t){return pi(e.parentElement,1)||gi(e)||_i(t)}function gi(e){return e.nodeType===1&&mi(e.getAttribute(di),1)}function _i({props:e}){let t=e&&e[di];return typeof t==`string`&&mi(t,1)}var vi=fe().requestIdleCallback||(e=>setTimeout(e,1)),yi=fe().cancelIdleCallback||(e=>clearTimeout(e)),bi=(e=1e4)=>t=>{let n=vi(t,{timeout:e});return()=>yi(n)};function xi(e){let{top:t,left:n,bottom:r,right:i}=e.getBoundingClientRect(),{innerHeight:a,innerWidth:o}=window;return(t>0&&t<a||r>0&&r<a)&&(n>0&&n<o||i>0&&i<o)}var Si=e=>(t,n)=>{let r=new IntersectionObserver(e=>{for(let n of e)if(n.isIntersecting){r.disconnect(),t();break}},e);return n(e=>{if(e instanceof Element){if(xi(e))return t(),r.disconnect(),!1;r.observe(e)}}),()=>r.disconnect()},Ci=e=>t=>{if(e){let n=matchMedia(e);if(n.matches)t();else return n.addEventListener(`change`,t,{once:!0}),()=>n.removeEventListener(`change`,t)}},wi=(e=[])=>(t,n)=>{y(e)&&(e=[e]);let r=!1,i=e=>{r||(r=!0,a(),t(),e.target.dispatchEvent(new e.constructor(e.type,e)))},a=()=>{n(t=>{for(let n of e)t.removeEventListener(n,i)})};return n(t=>{for(let n of e)t.addEventListener(n,i,{once:!0})}),a};function Ti(e,t){if(si(e)&&e.data===`[`){let n=1,r=e.nextSibling;for(;r;){if(r.nodeType===1){if(t(r)===!1)break}else if(si(r)){if(r.data===`]`){if(--n===0)break}else r.data===`[`&&n++}r=r.nextSibling}}else t(e)}var Ei=e=>!!e.type.__asyncLoader;function Di(e){v(e)&&(e={loader:e});let{loader:t,loadingComponent:n,errorComponent:r,delay:i=200,hydrate:a,timeout:o,suspensible:s=!0,onError:c}=e,l=null,u,d=0,f=()=>(d++,l=null,p()),p=()=>{let e;return l||(e=l=t().catch(e=>{if(e=e instanceof Error?e:Error(String(e)),c)return new Promise((t,n)=>{c(e,()=>t(f()),()=>n(e),d+1)});throw e}).then(t=>e!==l&&l?l:(t&&(t.__esModule||t[Symbol.toStringTag]===`Module`)&&(t=t.default),u=t,t)))};return I({name:`AsyncComponentWrapper`,__asyncLoader:p,__asyncHydrate(e,t,n){let r=e.isConnected,i=!1;(t.bu||=[]).push(()=>i=!0);let o=()=>{i||!e.parentNode||r&&!e.isConnected||n()},s=a?()=>{let n=a(o,t=>Ti(e,t));n&&(t.bum||=[]).push(n)}:o;u?s():p().then(()=>!t.isUnmounted&&s())},get __asyncResolved(){return u},setup(){let e=ms;if(Xr(e),u)return()=>Oi(u,e);let t=t=>{l=null,Rn(t,e,13,!r)};if(s&&e.suspense||xs)return p().then(t=>()=>Oi(t,e)).catch(e=>(t(e),()=>r?W(r,{error:e}):null));let a=M(!1),c=M(),d=M(!!i),f,m;return Gi(()=>{f!=null&&clearTimeout(f),m!=null&&clearTimeout(m)}),i&&(m=setTimeout(()=>{e.isUnmounted||(d.value=!1)},i)),o!=null&&(f=setTimeout(()=>{if(!e.isUnmounted&&!a.value&&!c.value){let e=Error(`Async component timed out after ${o}ms.`);t(e),c.value=e}},o)),p().then(()=>{e.isUnmounted||(a.value=!0,e.parent&&ki(e.parent.vnode)&&e.parent.update())}).catch(n=>{if(e.isUnmounted){l=null;return}t(n),c.value=n}),()=>{if(a.value&&u)return Oi(u,e);if(c.value&&r)return W(r,{error:c.value});if(n&&!d Line truncated
`))),e[Sl]=yl(i);let a=r||i.props&&i.props.type===`number`;Bc(e,t?`change`:`input`,t=>{t.target.composing||e[Sl](wl(e.value,n,a))}),(n||a)&&Bc(e,`change`,()=>{e.value=wl(e.value,n,a)}),t||(Bc(e,`compositionstart`,bl),Bc(e,`compositionend`,xl),Bc(e,`change`,xl))},mounted(e,{value:t,modifiers:{trim:n,number:r}}){let i=t??``,a=e[Cl];delete e[Cl],a!==void 0&&(e.type===`text`||e.type===`textarea`)&&e.value!==a?e[Sl](wl(e.value,n,r)):e.value=i},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:r,trim:i,number:a}},o){if(e[Sl]=yl(o),e.composing)return;let s=(a||e.type===`number`)&&!/^0\d/.test(e.value)?le(e.value):e.value,c=t??``;if(s===c)return;let l=e.getRootNode();(l instanceof Document||l instanceof ShadowRoot)&&l.activeElement===e&&e.type!==`range`&&(r&&t===n||i&&e.value.trim()===c)||(e.value=c)}},El={deep:!0,created(e,t,n){e[Sl]=yl(n),Bc(e,`change`,()=>{let t=e._modelValue,n=jl(e),r=e.checked,i=e[Sl];if(p(t)){let e=Oe(t,n),a=e!==-1;if(r&&!a)i(t.concat(n));else if(!r&&a){let n=[...t];n.splice(e,1),i(n)}}else if(h(t)){let e=new Set(t);r?e.add(n):e.delete(n),i(e)}else i(Ml(e,r))})},mounted:Dl,beforeUpdate(e,t,n){e[Sl]=yl(n),Dl(e,t,n)}};function Dl(e,{value:t,oldValue:n},r){e._modelValue=t;let i;if(p(t))i=Oe(t,r.props.value)>-1;else if(h(t))i=t.has(r.props.value);else{if(t===n)return;i=De(t,Ml(e,!0))}e.checked!==i&&(e.checked=i)}var Ol={created(e,{value:t},n){e.checked=De(t,n.props.value),e[Sl]=yl(n),Bc(e,`change`,()=>{e[Sl](jl(e))})},beforeUpdate(e,{value:t,oldValue:n},r){e[Sl]=yl(r),t!==n&&(e.checked=De(t,r.props.value))}},kl={deep:!0,created(e,{value:t,modifiers:{number:n}},r){e._modelValue=t,Bc(e,`change`,()=>{let t=Array.prototype.filter.call(e.options,e=>e.selected).map(e=>n?le(jl(e)):jl(e)),r=e.multiple,i=r?h(e._modelValue)?new Set(t):t:t[0],a=e._pendingValue=[r,r?p(i)?t.slice():t:i];try{e[Sl](i)}finally{qn(()=>{e._pendingValue===a&&(e._pendingValue=void 0)})}}),e[Sl]=yl(r)},mounted(e,{value:t}){Al(e,t)},beforeUpdate(e,{value:t},n){e._modelValue=t,e[Sl]=yl(n)},updated(e,{value:t}){let n=e._pendingValue;e._pendingValue=void 0,(!n||n[0]!==e.multiple||!yee(t,n[1],n[0]))&&Al(e,t)}};function yee(e,t,n){if(!n||p(e))return De(e,t);if(h(e)){if(e.size!==t.length)return!1;for(let n of t)if(!e.has(n))return!1;return!0}return!1}function Al(e,t){let n=e.multiple,r=p(t);if(!n||r||h(t)){for(let i=0,a=e.options.length;i<a;i++){let a=e.options[i],o=jl(a);if(n){if(r){let e=typeof o;a.selected=e===`string`||e===`number`?t.some(e=>String(e)===String(o)):Oe(t,o)>-1}else a.selected=t.has(o)}else if(De(jl(a),t)){e.selectedIndex!==i&&(e.selectedIndex=i);return}}!n&&e.selectedIndex!==-1&&(e.selectedIndex=-1)}}function jl(e){return`_value`in e?e._value:e.value}function Ml(e,t){let n=t?`_trueValue`:`_falseValue`;return n in e?e[n]:t}var Nl={created(e,t,n){Fl(e,t,n,null,`created`)},mounted(e,t,n){Fl(e,t,n,null,`mounted`)},beforeUpdate(e,t,n,r){Fl(e,t,n,r,`beforeUpdate`)},updated(e,t,n,r){Fl(e,t,n,r,`updated`)}};function Pl(e,t){switch(e){case`SELECT`:return kl;case`TEXTAREA`:return Tl;default:switch(t){case`checkbox`:return El;case`radio`:return Ol;default:return Tl}}}function Fl(e,t,n,r,i){let a=Pl(e.tagName,n.props&&n.props.type)[i];a&&a(e,t,n,r)}function bee(){Tl.getSSRProps=({value:e})=>({value:e}),Ol.getSSRProps=({value:e},t)=>{if(t.props&&De(t.props.value,e))return{checked:!0}},El.getSSRProps=({value:e},t)=>{if(p(e)){if(t.props&&Oe(e,t.props.value)>-1)return{checked:!0}}else if(h(e)){if(t.props&&e.has(t.props.value))return{checked:!0}}else if(e)return{checked:!0}},Nl.getSSRProps=(e,t)=>{if(typeof t.type!=`string`)return;let n=Pl(t.type.toUpperCase(),t.props&&t.props.type);if(n.getSSRProps)return n.getSSRProps(e,t)}}var xee=[`ctrl`,`shift`,`alt`,`meta`],See={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>`button`in e&&e.button!==0,middle:e=>`button`in e&&e.button!==1,right:e=>`button`in e&&e.button!==2,exact:(e,t)=>xee.some(n=>e[`${n}Key`]&&!t.includes(n))},Il=(e,t)=>{if(!e)return e;let n=e._withMods||={},r=t.join(`.`);return n[r]||(n[r]=((n,...r)=>{for(let e=0;e<t.length;e++){let r=See[t[e]];if(r&&r(n,t))return}return e(n,...r)}))},Cee={esc:`escape`,space:` `,up:`arrow-up`,left:`arrow-left`,right:`arrow-right`,down:`arrow-down`,delete:`backspace`},Ll=(e,t)=>{let n=e._withKeys||={},r=t.join(`.`);return n[r]||(n[r]=(n=>{if(!(`key`in n))return;let r=ie(n.key);if(t.some(e=>e===r||Cee[e]===r))return e(n)}))},Rl=l({patchProp:Qc},Qs),zl,Bl=!1;function Vl(){return zl||=xo(Rl)}function Hl(){return zl=Bl?zl:So(Rl),Bl=!0,zl}var Ul=((...e)=>{Vl().render(...e)}),Wl=((...e)=>{Hl().hydrate(...e)}),Gl=((...e)=>{let t=Vl().createApp(...e),{mount:n}=t;return t.mount=e=>{let r=Jl(e);if(!r)return;let i=t._component;!v(i)&&!i.render&&!i.template&&(i.template=r.innerHTML),r.nodeType===1&&(r.textContent=``);let a=n(r,!1,ql(r));return r instanceof Element&&(r.removeAttribute(`v-cloak`),r.setAttribute(`data-v-app`,``)),a}, Line truncated
`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var Mp;function Np(e){Mp=e}var Pp=class extends Error{status;constructor(e,t){super(e),this.name=`ApiError`,this.status=t}};function Fp(e){let t=e instanceof Pp?e.status:void 0,n=e instanceof Error&&e.message?e.message:`Action failed`;return t===401?{kind:`session-expired`,message:n}:t!==void 0&&t>=400&&t<500?{kind:`refused`,message:n}:{kind:`broken`,message:n}}async function Ip(e,t){let n=await fetch(e,t);if(Mp?.(n.status===401),!n.ok)throw new Pp(await jp(n),n.status);return n}async function Lp(e,t={}){let{method:n=`GET`,body:r,timeoutMs:i=kp,parse:a=!0}=t,o={Accept:`application/json`},s={method:n,headers:o,signal:AbortSignal.timeout(i)};n!==`GET`&&(o[`Content-Type`]=`application/json`,o[`X-Archie-CSRF`]=`1`),r!==void 0&&(s.body=JSON.stringify(r));let c=await Ip(e,s);return a?await c.json():void 0}var X={health:()=>Lp(`/health/detailed`),services:()=>Lp(`/api/services`),policies:()=>Lp(`/api/access/policies`),putPolicy:e=>Lp(`/api/access/policies`,{method:`PUT`,body:e}),deletePolicy:e=>Lp(`/api/access/policies`,{method:`DELETE`,body:e,parse:!1}),orgs:()=>Lp(`/api/orgs`),orgCreate:e=>Lp(`/api/orgs`,{method:`POST`,body:e}),org:e=>Lp(`/api/orgs/${encodeURIComponent(e)}`),orgWorkspaces:e=>Lp(`/api/orgs/${encodeURIComponent(e)}/workspaces`),createOrgWorkspace:(e,t)=>Lp(`/api/orgs/${encodeURIComponent(e)}/workspaces`,{method:`POST`,body:t}),orgMembers:e=>Lp(`/api/orgs/${encodeURIComponent(e)}/members`),setOrgMember:(e,t,n)=>Lp(`/api/orgs/${encodeURIComponent(e)}/members/${encodeURIComponent(t)}`,{method:`PUT`,body:n}),removeOrgMember:(e,t,n)=>Lp(`/api/orgs/${encodeURIComponent(e)}/members/${encodeURIComponent(t)}`+Ap({workspace:n}),{method:`DELETE`,parse:!1}),assignOrgAgent:(e,t)=>Lp(`/api/orgs/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}`,{method:`PUT`}),summary:()=>Lp(`/api/summary`),tasks:()=>Lp(`/api/tasks`),taskPage:async e=>{let t=await Ip(`/api/tasks`+Ap(e),{headers:{Accept:`application/json`},signal:AbortSignal.timeout(kp)});return{tasks:await t.json(),next:t.headers.get(`X-Next-Cursor`)}},taskMeta:()=>Lp(`/api/task-meta`),task:e=>Lp(`/api/tasks/${encodeURIComponent(e)}`),taskAttempts:e=>Lp(`/api/tasks/${encodeURIComponent(e)}/attempts`),taskChanges:(e,t)=>Lp(`/api/tasks/${encodeURIComponent(e)}/changes`+Ap(t)),taskDebug:(e,t)=>Lp(`/api/tasks/${encodeURIComponent(e)}/debug`+Ap(t)),taskAction:(e,t,n)=>Lp(`/api/tasks/${encodeURIComponent(e)}/action`,{method:`POST`,body:{action:t,...n}}),setup:()=>Lp(`/api/setup`),capabilities:()=>Lp(`/api/capabilities`),workflows:()=>Lp(`/api/workflows`),workflowEnabled:(e,t)=>Lp(`/api/workflows/${encodeURIComponent(e)}/enabled`,{method:`PUT`,body:{enabled:t},parse:!1}),workRequest:e=>Lp(`/api/work-requests`,{method:`POST`,body:e}),skills:()=>Lp(`/api/skills`),channels:()=>Lp(`/api/channels`),curators:()=>Lp(`/api/curators`),channelReload:e=>Lp(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,body:{}}),config:()=>Lp(`/api/config`),logs:e=>Lp(`/api/logs`+Ap(e)),taskLogs:(e,t)=>Lp(`/api/tasks/${encodeURIComponent(e)}/logs`+Ap(t)),taskLogDownloadURL:(e,t)=>`/api/tasks/${encodeURIComponent(e)}/logs/download`+(t==null?``:`?attempt=${t}`),version:()=>Lp(`/api/version`),updateSnapshot:()=>Lp(`/api/chat/update`),updateInstall:e=>Lp(`/api/chat/update/install`,{method:`POST`,body:{snapshot:e},timeoutMs:9e5}),captures:e=>Lp(`/api/captures`+Ap({limit:e})),eventTypes:()=>Lp(`/api/event-types`),eventTypeCreate:e=>Lp(`/api/event-types`,{method:`POST`,body:e}),eventTypeUpdate:(e,t)=>Lp(`/api/event-types/${encodeURIComponent(e)}`,{method:`PUT`,body:t}),eventTypeDelete:e=>Lp(`/api/event-types/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),mappings:()=>Lp(`/api/mappings`),mappingCreate:e=>Lp(`/api/mappings`,{method:`POST`,body:e}),mappingUpdate:(e,t)=>Lp(`/api/mappings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),mappingDelete:e=>Lp(`/api/mappings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),mappingPreview:(e,t)=>Lp(`/api/mappings/preview`,{method:`POST`,body:{capture_id:e,fields:t}}),bindings:()=>Lp(`/api/bindings`),dispatches:(e,t)=>Lp(`/api/${e}/${encodeURIComponent(t)}/dispatches`),bindingCreate:e=>Lp(`/api/bindings`,{method:`POST`,body:e}),bindingUpdate:(e,t)=>Lp(`/api/bindings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),bindingDelete:e=>Lp(`/api/bindings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),bindingApprove:e=>Lp(`/api/bindings/${encodeURIComponent(e)}/approve`,{method:`POST`}),bindingPause:e=>Lp(`/api/bindings/${encodeURIComponent(e)}/pause`,{method:`POST`}),bindingResume:e=>Lp(`/api/bindings/${encodeURIComponent(e)}/resume`,{method:`POST`}),harnessBindings:()=>Lp(`/api/harness/bindings`),sources:()=>Lp(`/api/sources`),sourceCreate:e=>Lp(`/api/sources`,{method:`POST`,body:{path:e}}),sourceSigning:(e,t)=>Lp(`/api/sources/${encodeURIComponent(e)}/signing`,{method:`POST`,body:{signed:t}}),sourceApproveUnsigned:e=>Lp(`/api/sources/${encodeURIComponent(e)}/aLine truncated
`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var Mp;function Np(e){Mp=e}var Pp=class extends Error{status;constructor(e,t){super(e),this.name=`ApiError`,this.status=t}};function Fp(e){let t=e instanceof Pp?e.status:void 0,n=e instanceof Error&&e.message?e.message:`Action failed`;return t===401?{kind:`session-expired`,message:n}:t!==void 0&&t>=400&&t<500?{kind:`refused`,message:n}:{kind:`broken`,message:n}}async function Ip(e,t){let n=await fetch(e,t);if(Mp?.(n.status===401),!n.ok)throw new Pp(await jp(n),n.status);return n}async function Lp(e,t={}){let{method:n=`GET`,body:r,timeoutMs:i=kp,parse:a=!0}=t,o={Accept:`application/json`},s={method:n,headers:o,signal:AbortSignal.timeout(i)};n!==`GET`&&(o[`Content-Type`]=`application/json`,o[`X-Archie-CSRF`]=`1`),r!==void 0&&(s.body=JSON.stringify(r));let c=await Ip(e,s);return a?await c.json():void 0}var X={health:()=>Lp(`/health/detailed`),services:()=>Lp(`/api/services`),policies:()=>Lp(`/api/access/policies`),putPolicy:e=>Lp(`/api/access/policies`,{method:`PUT`,body:e}),deletePolicy:e=>Lp(`/api/access/policies`,{method:`DELETE`,body:e,parse:!1}),orgs:()=>Lp(`/api/orgs`),orgCreate:e=>Lp(`/api/orgs`,{method:`POST`,body:e}),org:e=>Lp(`/api/orgs/${encodeURIComponent(e)}`),orgWorkspaces:e=>Lp(`/api/orgs/${encodeURIComponent(e)}/workspaces`),createOrgWorkspace:(e,t)=>Lp(`/api/orgs/${encodeURIComponent(e)}/workspaces`,{method:`POST`,body:t}),orgMembers:e=>Lp(`/api/orgs/${encodeURIComponent(e)}/members`),setOrgMember:(e,t,n)=>Lp(`/api/orgs/${encodeURIComponent(e)}/members/${encodeURIComponent(t)}`,{method:`PUT`,body:n}),removeOrgMember:(e,t,n)=>Lp(`/api/orgs/${encodeURIComponent(e)}/members/${encodeURIComponent(t)}`+Ap({workspace:n}),{method:`DELETE`,parse:!1}),assignOrgAgent:(e,t)=>Lp(`/api/orgs/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}`,{method:`PUT`}),summary:()=>Lp(`/api/summary`),tasks:()=>Lp(`/api/tasks`),taskPage:async e=>{let t=await Ip(`/api/tasks`+Ap(e),{headers:{Accept:`application/json`},signal:AbortSignal.timeout(kp)});return{tasks:await t.json(),next:t.headers.get(`X-Next-Cursor`)}},taskMeta:()=>Lp(`/api/task-meta`),task:e=>Lp(`/api/tasks/${encodeURIComponent(e)}`),taskAttempts:e=>Lp(`/api/tasks/${encodeURIComponent(e)}/attempts`),taskChanges:(e,t)=>Lp(`/api/tasks/${encodeURIComponent(e)}/changes`+Ap(t)),taskDebug:(e,t)=>Lp(`/api/tasks/${encodeURIComponent(e)}/debug`+Ap(t)),taskAction:(e,t,n)=>Lp(`/api/tasks/${encodeURIComponent(e)}/action`,{method:`POST`,body:{action:t,...n}}),setup:()=>Lp(`/api/setup`),capabilities:()=>Lp(`/api/capabilities`),workflows:()=>Lp(`/api/workflows`),workflowEnabled:(e,t)=>Lp(`/api/workflows/${encodeURIComponent(e)}/enabled`,{method:`PUT`,body:{enabled:t},parse:!1}),workRequest:e=>Lp(`/api/work-requests`,{method:`POST`,body:e}),skills:()=>Lp(`/api/skills`),channels:()=>Lp(`/api/channels`),curators:()=>Lp(`/api/curators`),channelReload:e=>Lp(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,body:{}}),config:()=>Lp(`/api/config`),logs:e=>Lp(`/api/logs`+Ap(e)),taskLogs:(e,t)=>Lp(`/api/tasks/${encodeURIComponent(e)}/logs`+Ap(t)),taskLogDownloadURL:(e,t)=>`/api/tasks/${encodeURIComponent(e)}/logs/download`+(t==null?``:`?attempt=${t}`),version:()=>Lp(`/api/version`),updateSnapshot:()=>Lp(`/api/chat/update`),updateInstall:e=>Lp(`/api/chat/update/install`,{method:`POST`,body:{snapshot:e},timeoutMs:9e5}),captures:e=>Lp(`/api/captures`+Ap({limit:e})),eventTypes:()=>Lp(`/api/event-types`),eventTypeCreate:e=>Lp(`/api/event-types`,{method:`POST`,body:e}),eventTypeUpdate:(e,t)=>Lp(`/api/event-types/${encodeURIComponent(e)}`,{method:`PUT`,body:t}),eventTypeDelete:e=>Lp(`/api/event-types/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),mappings:()=>Lp(`/api/mappings`),mappingCreate:e=>Lp(`/api/mappings`,{method:`POST`,body:e}),mappingUpdate:(e,t)=>Lp(`/api/mappings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),mappingDelete:e=>Lp(`/api/mappings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),mappingPreview:(e,t)=>Lp(`/api/mappings/preview`,{method:`POST`,body:{capture_id:e,fields:t}}),bindings:()=>Lp(`/api/bindings`),dispatches:(e,t)=>Lp(`/api/${e}/${encodeURIComponent(t)}/dispatches`),bindingCreate:e=>Lp(`/api/bindings`,{method:`POST`,body:e}),bindingUpdate:(e,t)=>Lp(`/api/bindings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),bindingDelete:e=>Lp(`/api/bindings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),bindingApprove:e=>Lp(`/api/bindings/${encodeURIComponent(e)}/approve`,{method:`POST`}),bindingPause:e=>Lp(`/api/bindings/${encodeURIComponent(e)}/pause`,{method:`POST`}),bindingResume:e=>Lp(`/api/bindings/${encodeURIComponent(e)}/resume`,{method:`POST`}),harnessBindings:()=>Lp(`/api/harness/bindings`),sources:()=>Lp(`/api/sources`),sourceCreate:e=>Lp(`/api/sources`,{method:`POST`,body:{path:e}}),sourceSigning:(e,t)=>Lp(`/api/sources/${encodeURIComponent(e)}/signing`,{method:`POST`,body:{signed:t}}),sourceApproveUnsigned:e=>Lp(`/api/sources/${encodeURIComponent(e)}/aLine truncated
`);u=r.pop()||``;for(let e of r){let t=e.split(`
`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&($p.value=n.session_id),n.type===`delta`&&(o+=n.text,im.value=im.value?{...im.value,text:o}:null),(n.type===`tool`||n.type===`navigate`)&&(a=[...a,n],im.value=im.value?{...im.value,tools:a}:null),n.type===`done`&&(s=!0,o||=n.text||``),n.type===`error`)throw Error(n.text)}if(t)break}if(!s)throw Error(`chat stream ended before completion`);em.value=[...em.value,{from:`assistant`,text:o,tool_calls:a}],im.value=null,nm.value=`Ready`,await ym()}catch(e){let t=e;t.name===`AbortError`&&!c?(im.value={text:`Turn stopped.`,tools:a,isError:!1,turn:r,isRetry:i},nm.value=`Stopped`):(im.value={text:`Unable to complete that turn: ${t.message||t}`,tools:a,isError:!0,turn:r?Jp(r):void 0,isRetry:i},nm.value=`Error — retry available`)}finally{clearTimeout(l),_m=null,rm.value=!1}}function Mee(){nm.value=`Stopping…`,$p.value&&X.chatCancel($p.value).catch(()=>{}),vm()}function Nee(){Vi(()=>{ym().catch(e=>{nm.value=e.message||`Chat unavailable`})}),Gi(()=>{vm()})}var Pee=[`aria-label`,`title`,`aria-expanded`,`aria-controls`],Fee=I({__name:`ChatFab`,props:{open:{type:Boolean}},emits:[`toggle`],setup(e,{emit:t}){let n=t;function r(e){return Y(`col-start-1 row-start-1 grid place-items-center transition-[opacity,transform] duration-[140ms]`,e?`opacity-100`:`-rotate-45 scale-[0.7] opacity-0`)}return(t,i)=>(B(),V(`button`,{type:`button`,class:`relative z-10 grid size-14 cursor-pointer place-items-center rounded-full border border-border-strong bg-secondary text-primary shadow-[var(--shadow-md)] transition-transform duration-[140ms] hover:-translate-y-px focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:translate-y-0`,"aria-label":e.open?`Close chat`:`Chat with Archie`,title:e.open?`Close chat`:`Chat with Archie`,"aria-expanded":e.open,"aria-controls":N(Xp),onClick:i[0]||=e=>n(`toggle`)},[U(`span`,{"aria-hidden":`true`,class:A(r(!e.open))},[W(N(_d),{size:22})],2),U(`span`,{"aria-hidden":`true`,class:A(r(e.open))},[W(N(qd),{size:22})],2)],8,Pee))}});function Tm(e){return typeof e==`string`?`'${e}'`:new Lee().serialize(e)}var Iee=` _-,;:!?.'"()[]{}@*/\\&#%\`^+<=>|~$0123456789abcdefghijklmnopqrstuvwxyz`,Em=(function(){let e=new Uint8Array(128);for(let t=0;t<69;t++)e[Iee.charCodeAt(t)]=t+1;for(let t=65;t<=90;t++)e[t]=e[t+32];return e})();function Dm(e,t){if(e===t)return 0;let n=Math.min(e.length,t.length),r=0;for(let i=0;i<n;i++){let n=e.charCodeAt(i),a=t.charCodeAt(i);if(n===a)continue;let o=n<128&&Em[n]?Em[n]:n+128,s=a<128&&Em[a]?Em[a]:a+128;if(o!==s)return o<s?-1:1;r===0&&(r=n>a?-1:1)}return e.length===t.length?r:e.length<t.length?-1:1}var Lee=(function(){class e{#e=new Map;compare(e,t){let n=typeof e,r=typeof t;return n===`string`&&r===`string`?Dm(e,t):n===`number`&&r===`number`?e-t:Dm(this.serialize(e,!0),this.serialize(t,!0))}serialize(e,t){if(e===null)return`null`;switch(typeof e){case`string`:return t?e:`'${e}'`;case`bigint`:return`${e}n`;case`object`:return this.$object(e);case`function`:return this.$function(e)}return String(e)}serializeObject(e){let t=Object.prototype.toString.call(e);if(t!==`[object Object]`)return this.serializeBuiltInType(t.length<10?`unknown:${t}`:t.slice(8,-1),e);let n=e.constructor,r=n===Object||n===void 0?``:n.name;if(r!==``&&globalThis[r]===n)return this.serializeBuiltInType(r,e);if(`toJSON`in e&&typeof e.toJSON==`function`){let t=e.toJSON();return r+(typeof t==`object`&&t?this.$object(t):`(${this.serialize(t)})`)}let i=Object.keys(e).sort(Dm),a=`${r}{`;for(let t=0;t<i.length;t++){let n=i[t];a+=`${n}:${this.serialize(e[n])}`,t<i.length-1&&(a+=`,`)}return a+`}`}serializeBuiltInType(e,t){let n=this[`$`+e];if(n)return n.call(this,t);if(typeof t.entries==`function`)return this.serializeObjectEntries(e,t.entries());throw Error(`Cannot serialize ${e}`)}serializeObjectEntries(e,t){let n=Array.from(t).sort((e,t)=>this.compare(e[0],t[0])),r=`${e}{`;for(let e=0;e<n.length;e++){let[t,i]=n[e];r+=`${this.serialize(t,!0)}:${this.serialize(i)}`,e<n.length-1&&(r+=`,`)}return r+`}`}$object(e){let t=this.#e.get(e);return t===void 0&&(this.#e.set(e,`#${this.#e.size}`),t=this.serializeObject(e),this.#e.set(e,t)),t}$function(e){let t=Function.prototype.toString.call(e);return t.slice(-15)===`[native code] }`?`${e.name||``}()[native]`:`${e.name}(${e.length})${t.replace(/\s*\n\s*/g,``)}`}$Array(e){let t=`[`;for(let n=0;n<e.length;n++)t+=this.serialize(e[n]),n<e.length-1&&(t+=`,`);return t+`]`}$Date(e){try{return`Date(${e.toISOString()})`}catch{return`Date(null)`}}$ArrayBuffer(e){return`ArrayBuffer[${new Uint8Array(e).join(`,`)}]`}$Set(e){return`Set${this.$Array(Array.from(e).sort((e,t)=>this.compare(e,t)))}`}$Map(e){return this.serializeObjectEntries(`Map`,e.entries())}}for(let t of[`Error`,`RegExp`,`URL`])e.prototype[`$`+t]=function(e){return`${t}(${e})`};for(let t of[`Int8Array`,`Uint8Array`,`Uint8ClampedArray`,`Int16Array`,`Uint16Array`,`Int32Array`,`Uint32Array`,`Float32Array`,`FloatLine truncated
-11
View File
@@ -377,17 +377,6 @@ export const api = {
method: "POST",
body: { session_id: sessionID, name },
}),
chatDangerous: <T = unknown>() => request<T>("/api/chat/dangerous"),
chatDangerousRequest: <T = unknown>(kind: string, spec: unknown) =>
request<T>(`/api/chat/dangerous/${encodeURIComponent(kind)}`, {
method: "POST",
body: { spec },
}),
chatDangerousDecision: <T = unknown>(id: string, decision: string) =>
request<T>(`/api/chat/dangerous/${encodeURIComponent(id)}/decision`, {
method: "POST",
body: { decision },
}),
// A server-sent event stream cannot be parsed as JSON and outlives a normal
// request, so the caller owns the abort controller and the timeout, and
// reads the body itself. Only the URL, headers, and failure shape are shared.
-61
View File
@@ -1,61 +0,0 @@
<script setup lang="ts">
import { ref } from "vue";
import { Button } from "@/components/ui/button";
import { Field, FieldLabel } from "@/components/ui/field";
import {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { requestDangerous } from "./state";
import type { DangerCheckpoint } from "./types";
/**
* Queues a rollback to a checkpoint. The request only asks: an approval has to
* be granted in the list below before anything runs.
*
* A checkpoint's number and label arrive under either casing depending on the
* source, so both are read.
*/
const props = defineProps<{ checkpoints: DangerCheckpoint[] }>();
const checkpoint = ref("");
const number = (cp: DangerCheckpoint): number | undefined =>
cp.Number ?? cp.number;
const label = (cp: DangerCheckpoint): string =>
cp.Label ?? cp.label ?? "checkpoint";
</script>
<template>
<Field orientation="horizontal">
<FieldLabel class="sr-only" for="danger-checkpoint">Checkpoint</FieldLabel>
<Select v-model="checkpoint">
<SelectTrigger id="danger-checkpoint" class="w-full md:max-w-80">
<SelectValue placeholder="Select checkpoint" />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem
v-for="cp in props.checkpoints"
:key="String(number(cp))"
:value="String(number(cp))"
>
{{ number(cp) }} — {{ label(cp) }}
</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
<Button
variant="outline"
:disabled="!checkpoint"
@click="requestDangerous('rollback', checkpoint)"
>
Request rollback
</Button>
</Field>
</template>
-36
View File
@@ -1,36 +0,0 @@
<script setup lang="ts">
import { computed, ref } from "vue";
import { Button } from "@/components/ui/button";
import { Field, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { requestDangerous } from "./state";
/**
* Queues a stop for a named process. Like every request here it only asks:
* the approval decides whether it runs.
*/
const spec = ref("");
const requested = computed(() => spec.value.trim().length > 0);
</script>
<template>
<Field orientation="horizontal">
<FieldLabel class="sr-only" for="danger-stop"
>Process name or id</FieldLabel
>
<Input
id="danger-stop"
v-model="spec"
placeholder="Process name or id"
autocomplete="off"
class="w-full md:max-w-80"
/>
<Button
variant="outline"
:disabled="!requested"
@click="requestDangerous('stop', spec)"
>Request stop</Button
>
</Field>
</template>
-91
View File
@@ -1,91 +0,0 @@
<script setup lang="ts">
import { computed, ref } from "vue";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { decideDangerous } from "./state";
import type { DangerousAction } from "./types";
/**
* One queued request: what it would do, and the decisions open on it. Approve
* runs it once, "Approve for 24h" runs it for a day, and Deny drops it.
*
* Both approves are destructive-weighted and confirmed first, because they
* grant authority: approve for the one run, the 24h option for every future
* request of the same family. Deny takes nothing away, so it stays plain.
*/
const props = defineProps<{ action: DangerousAction }>();
// Which approve decision is awaiting its confirmation, if any: one dialog
// driven by the decision it will run, rather than two copies of the same
// footer. The decision kinds are fixed by the endpoint ('approve' |
// 'permanent' | 'deny') and must not be reworded here.
const confirming = ref<"approve" | "permanent" | null>(null);
const description = computed(() => props.action.description || "this action");
function decide(decision: "approve" | "permanent" | "deny"): void {
void decideDangerous(props.action.id, decision);
}
function onConfirmationOpen(open: boolean): void {
if (!open) confirming.value = null;
}
</script>
<template>
<div
class="flex flex-wrap items-center justify-between gap-3 border-t border-hairline py-3"
>
<span class="text-sm">{{ props.action.description }}</span>
<div class="flex flex-wrap gap-2">
<Button variant="destructive" @click="confirming = 'approve'"
>Approve</Button
>
<Button variant="destructive" @click="confirming = 'permanent'"
>Approve for 24h</Button
>
<Button variant="default" @click="decide('deny')">Deny</Button>
</div>
</div>
<AlertDialog :open="confirming !== null" @update:open="onConfirmationOpen">
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{{
confirming === "permanent"
? "Approve for 24 hours?"
: "Approve this action?"
}}
</AlertDialogTitle>
<AlertDialogDescription>
<template v-if="confirming === 'permanent'">
This runs "{{ description }}" now, and approves its action family
for 24 hours — further requests of the same kind run without asking
again.
</template>
<template v-else> This runs "{{ description }}" once, now. </template>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
variant="destructive"
@click="confirming && decide(confirming)"
>
{{ confirming === "permanent" ? "Approve for 24h" : "Approve" }}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</template>
-58
View File
@@ -1,58 +0,0 @@
<script setup lang="ts">
import { computed } from "vue";
import ConfigCard from "./ConfigCard.vue";
import DangerRollbackRequest from "./DangerRollbackRequest.vue";
import DangerStopRequest from "./DangerStopRequest.vue";
import DangerousActionRow from "./DangerousActionRow.vue";
import { dangerous } from "./state";
/**
* Requests and adjudicates the actions that need approval.
*
* These controls used to sit in the chat panel, which is where they were first
* built; installing an update and approving a dangerous action are things you
* do to the deployment, not things you say to Archie, so they moved here with
* Configuration's other operator controls (archie-core-tf20).
*
* Nothing here acts on its own: a request only queues an approval, and the
* decision buttons are the only thing that lets one run. A deployment that did
* not wire the capability answers 501, which leaves `dangerous` null and the
* card absent rather than in an error state.
*/
const pending = computed(() => dangerous.value?.pending ?? []);
const checkpoints = computed(() => dangerous.value?.checkpoints ?? []);
const error = computed(() => dangerous.value?.error ?? "");
</script>
<template>
<ConfigCard
v-if="dangerous"
title="Dangerous actions"
:description="
error
? 'Actions that need explicit approval before they run.'
: 'Actions that need explicit approval before they run. Requesting one only queues it.'
"
>
<p v-if="error" class="text-sm text-fg-muted">{{ error }}</p>
<template v-else>
<!-- Each request is its own row with its own input: they queue
different kinds of approval and share nothing but the card. -->
<div class="flex flex-col gap-3">
<DangerRollbackRequest :checkpoints="checkpoints" />
<DangerStopRequest />
</div>
<p v-if="!pending.length" class="mt-3 text-sm text-fg-muted">
No pending dangerous actions.
</p>
<div v-else class="mt-3">
<DangerousActionRow
v-for="action in pending"
:key="action.id"
:action="action"
/>
</div>
</template>
</ConfigCard>
</template>
-16
View File
@@ -1,16 +0,0 @@
<script setup lang="ts">
import { onMounted } from "vue";
import PageHeader from "@/base/PageHeader.vue";
import DangerousActionsCard from "./DangerousActionsCard.vue";
import { loadDangerous } from "./state";
onMounted(loadDangerous);
</script>
<template>
<div>
<PageHeader title="Advanced" />
<DangerousActionsCard />
</div>
</template>
+2 -35
View File
@@ -1,7 +1,7 @@
import { computed, ref } from "vue";
import { ApiError, api } from "@/lib/api";
import type { ConfigView, DangerousActions } from "./types";
import { api } from "@/lib/api";
import type { ConfigView } from "./types";
/**
* The System pages' shared state.
@@ -18,12 +18,6 @@ export function errorText(err: unknown): string {
return String((err as Error).message || err);
}
function isMissing(err: unknown): boolean {
// 501 is a deployment that did not wire the capability, which is a
// legitimate state and a different thing from a broken one.
return err instanceof ApiError && err.status === 501;
}
// ── The configuration projection ────────────────────────────────────────────
export const config = ref<ConfigView | null>(null);
@@ -45,30 +39,3 @@ export async function loadConfig(): Promise<void> {
}
}
// ── Dangerous actions ───────────────────────────────────────────────────────
export const dangerous = ref<DangerousActions | null>(null);
export async function loadDangerous(): Promise<void> {
try {
dangerous.value = await api.chatDangerous<DangerousActions>();
} catch (err) {
dangerous.value = isMissing(err) ? null : { error: errorText(err) };
}
}
export async function requestDangerous(
kind: string,
spec: unknown,
): Promise<void> {
await api.chatDangerousRequest(kind, spec);
await loadDangerous();
}
export async function decideDangerous(
id: string,
decision: string,
): Promise<void> {
await api.chatDangerousDecision(id, decision);
await loadDangerous();
}
-20
View File
@@ -95,23 +95,3 @@ export interface ConfigView {
schema?: ConfigSection[];
}
/** A rollback point a dangerous action can target. Number and Label arrive in
* either case depending on the source, so both are carried. */
export interface DangerCheckpoint {
Number?: number;
number?: number;
Label?: string;
label?: string;
}
export interface DangerousAction {
id: string;
description?: string;
}
export interface DangerousActions {
pending?: DangerousAction[];
checkpoints?: DangerCheckpoint[];
/** Set when the read failed rather than being unwired. */
error?: string;
}
-1
View File
@@ -20,7 +20,6 @@ const passiveRefreshSurfaces = [
"../src/settings/SystemTasksPage.vue",
"../src/settings/SystemModelsPage.vue",
"../src/settings/SystemReposPage.vue",
"../src/settings/SystemAdvancedPage.vue",
"../src/tasks/PanelError.vue",
"../src/tasks/TaskLogs.vue",
];