Files
archie/internal/gateway/gateway.go
T
sam c4ddb9acdf Feat/q9au inline review comments (#895)
* feat(workflow): post line-anchored review comments with suggested fixes

Bead archie-core-q9au (docs/prds/inline-review.md). A review's findings reached
the operator only as a flat list in the PR body, so the author had to map every
finding back to its line by hand and apply mechanical fixes by hand. Now the
line-anchored findings are also posted as inline review comments, carrying a
one-click suggestion when the reviewer could state the fix.

Domain (internal/domain/workflow):
- ReviewFinding gains Suggestion; Validate rejects one on anything but a
  confirmed finding, so the agent's record_finding call is refused with
  something it can act on. Validate splits into validateAnchor /
  validateClassification / validateDisposition, which also brings it back under
  the cyclop limit the gate enforces.
- StagePostReviewComments runs after StageOpenPR in the implement workflow. It
  posts only line-anchored findings (Line > 0); a whole-file finding has no line
  to attach to and stays in the body list, which remains the complete record.
  It is best-effort: the PR is open and the body already lists every finding, so
  a failed comment is logged, never a park -- the same reasoning as OpenPR's
  existing best-effort LinkBranch call.
- The suggestion fence is gated on Verdict == confirmed where the fence is
  written, because it is a one-click apply: a wrong suggestion breaks the code
  and the author has to notice.

Forge (internal/forge): ReviewCommentWriter + GitHub/Gitea implementations,
type-asserted like PullRequestReader so a forge that cannot is skipped rather
than faked (NoopForge is pinned as not satisfying it). GitHub loops one
CreateComment per comment and joins the failures, so one refused anchor cannot
drop the rest; Gitea carries them on a single COMMENT-state review.

Two deliberate departures from the PRD's sketch, both recorded in it:
- The interface is batch (CreateReviewComments), not one call per comment:
  Gitea's only inline shape is one submitted review, and the set then crosses
  NATS once instead of once per finding.
- The head SHA is resolved inside each forge implementation rather than by the
  caller. The stage runs in archie-agent, which holds no forge credentials and
  has no PullRequestReader; the daemon-side forgerpc handler is the only place
  that does.

Transport (internal/forgerpc): workflow.Forger gains the method, so the agent
reaches the daemon over the new create_review_comments subject; the server
type-asserts the writer and answers an incapable forge with an error the stage
logs. This is the one proxied method whose absence on an image skew does not
park a task.

The reviewer prompt and record_finding schema ask for a suggestion on a
confirmed, mechanically fixable defect only.

Regenerating the wfextract symbol table -- the documented way a new exported
workflow symbol reaches interpreted stage plugins -- also picked up symbols that
were missing from the committed table (the Status* and Source* constants,
ReviewCheck, Store, Task, and the _Store wrapper). Nil-guards were re-applied to
every wrapper afterwards, as that file's header requires.

Evidence: task check exit 0 (incl. 229 UI tests). Three mutations of the new
stage logic each fail a test that names the behaviour -- dropping the
confirmed-only gate, dropping the Line > 0 filter, and letting a posting failure
escape -- so the tests discriminate rather than passing vacuously.

* fix(build): drop the Dockerfile pin assertion

The guard fetched golangci-lint's go.mod at image build time to fail the build
when GOLANGCI_LINT_VERSION and GOFUMPT_VERSION disagreed. It only ever tripped
on self-inflicted pin drift, but it added a network fetch and a new failure
mode to the release build, which is not where that belongs.

The pins stay correct (golangci-lint 2.13.2, whose vendored gofumpt v0.11.0
equals GOFUMPT_VERSION) and the comment above them still states the invariant,
so the reasoning survives without the build-time machinery. The pin change
itself reaches the agent image through the normal release path: CI rebuilds
and pushes archie-agent on an archie/vX.Y.Z release, and a gateway-only
release deliberately does not.

* feat(workflow): add the remediate workflow for PR review remediation

Implements step 5 of docs/prds/pr-review-remediation.md: a remediate
workflow that resumes the task's existing worktree onto its PR branch
(worktree.Manager.Resume, not Prepare's refresh), runs a builder agent
against the review's actionable comments, commits and pushes to the
same branch, and replies via the forge's ReplyToReview. Task.RetryCount
doubles as the remediation round counter, capped by the repo's
max_retries; the round-cap stage parks the task and posts one comment
when it's hit.

Task gains a ReviewPayload field (JSON-encoded review unit) with full
store/proto/staterpc plumbing. workflow.Forger gains Comment and
ReplyToReview, proxied to archie-agent via a new forgerpc RPC. Resume
and its Dir lookup are added as an unexported optional Trees capability
rather than widening the exported interface, which is already at
golangci-lint's interfacebloat cap and is projected into wfextract's
Yaegi symbol table for repository-authored stage plugins.

The daemon-side reaction consumer that dispatches into this workflow
(subscribing ARCHIE_REACTIONS, grouping comments by review, enforcing
per-task serialization) is tracked separately in archie-core-8li9.4.

* feat(messaging): extract standalone messaging service binary and process composition

* feat(messaging): adapt channel frontends to consume Gateway ChatContract

* feat(messaging): remove in-process channels and Router from daemon bootstrap

Telegram, email and webhook now run only in the Messaging Service, which
reaches this process through the Gateway's ChatContract. The daemon builds
no channel and no gateway.Router, so the wiring that existed only to serve
them goes with it: setupGateways, setupEmailGateway, setupWebhookGateway,
setupTelegramGateway, buildTelegramRouter, makeTelegramReload and the
release-announcement path helper.

The seams those paths owned move to where they can still be honoured:

- Channel ValidateConfig runs in archiemessaging.compose, which now returns
  an error, so a configured-but-invalid front-end fails the service rather
  than being dropped silently.
- The inbound rate limiter moves to the Gateway process, which owns the only
  Router and therefore the only place a per-sender budget applies to every
  channel's turns.
- The daemon's gateway readiness probe becomes a ContractProbe against the
  Gateway. It cannot observe a channel lifecycle it no longer runs, and a
  channel-count probe would have reported every daemon degraded.
- telegramSetup is now chatSetup (in chat_setup.go), trimmed to the fields a
  chat turn runner actually reads.

Telegram operator features that were wired only in the daemon (/update,
release announcements, version reporting, SIGHUP reload) are not yet wired
in the Messaging Service: archie-core-8cda.6.6. Channel lifecycle reporting:
archie-core-8cda.6.8. The Gateway process builds no worktree manager, so
review_pr is unadvertised on every channel: archie-core-8cda.6.7.

* feat(messaging): re-wire the Telegram operator surface in the Messaging Service

setupTelegramGateway satisfied eight telegram.Gateway seams from the daemon's
own process. Each is resolved by where the fact it needs is owned, not by
where it used to be built; the decision table is in
docs/architecture/migration-decisions.md.

Wired here: /update (built from this service's own [chat.telegram] check and
install commands), the update-report relay (same sha256(bot_user)[:8] path the
daemon wrote, so a pending report is found rather than written afresh),
show_tool_calls, and /restart's config reload, which re-resolves the token and
allowlist from this service's own file and refuses a reload that resolves to
an empty token.

/version is sourced from the Gateway: ChatSnapshot gains a Version field
carrying the Gateway's rendered build block, read per call and bounded by the
dependency timeout. cmd/archie-messaging deliberately takes no version
ldflags, so it cannot report a partial upgrade as a matched one.

RunningVersions and ReleaseAnnouncements stay nil. Both need a component's
real running version, and the only versions this process can obtain are a
different binary's stamps -- reporting them would manufacture exactly the
false success the update check exists to catch, and the announcer without
parseable versions is a no-op that reads as configured. archie-core-8cda.6.9
carries the contract that unblocks them. Dangerous stays nil: no composition
has ever supplied a command authority.

Enrich is dropped from the update service: componentInstallTypeEnricher read
[nats], which this service must not decode, so the check command's own
reported install type stands.

* fix(workflow): guard inline review comments against head drift

Two findings from the review of q9au.

A comment's line numbers describe exactly one revision of the branch, but the
forge resolved the pull request's head at posting time -- after the review had
already read the worktree. A push in that window (a collaborator, a retry) meant
the findings were anchored to whatever now occupied those lines, mislabelling
instead of failing. The revision the review measured now travels with the
comment set: OpenPR records it from the same worktree read it already performs
(TaskContext.ReviewedHeadSHA), StagePostReviewComments threads it through
Forger to forgerpc, and the forge refuses the whole set once the head it reads
has moved off it -- which the best-effort stage logs, the PR body remaining the
record. An unmeasured revision posts unverified rather than dropping every
finding, so a worktree that cannot report one degrades instead of regressing.

Suggestion was documented single-line only, because GitHub applies a suggestion
fence up to its first line and a multi-line replacement would silently corrupt
the file. Only the verdict was validated, so a multi-line suggestion reached the
renderer and posted as that truncated fence. Validate now rejects an embedded
newline, which makes record_finding refuse it with feedback the model can act on
instead of the reviewer discovering the corruption later.

* fix(gateway): render chat reports as lines, not one run-on paragraph

/status and /tasks are line-oriented reports, but their newlines were plain
"\n" -- CommonMark's soft wrap. The Telegram rich-block renderer space-joins
soft-wrapped lines, by design: a Telegram paragraph renders an embedded
newline as nothing at all, so a space is the only separator that survives.
The reports therefore arrived as one line each: "Runtime Provider: DeepSeek
Model: deepseek/deepseek-flash", and every task's title, state and park
reason jammed together.

The renderer now implements CommonMark's hard line break (two trailing
spaces, or a trailing backslash): the line closes its own block and the next
one hugs it, so a stanza keeps its lines without the spacer paragraph that
separates unrelated blocks. Ordinary prose is untouched -- a model's wrapped
paragraph still joins with a space. The producers mark their report lines
with it.

Two report fixes alongside:

- A park reason is capped to its first line at 160 runes. It carries whatever
  the failing stage reported, which for a lint gate is the whole tool log;
  unbounded, one parked task pushed every other task out of the reply. The
  full reason is still on the task.
- /status loses its "Runtime" sub-header. A section header over two fields
  made a four-fact report read like a document.
2026-09-19 23:44:51 +10:00

1087 lines
37 KiB
Go

// Package gateway defines the persistent-connection layer between archie
// and its users. Each gateway implementation (Telegram, web UI, Discord,
// etc.) owns its connection lifecycle and delegates message dispatch to a
// shared CommandRouter.
//
// The router distinguishes gateway-local commands -- handled directly
// without the LLM (model changes, status queries, restart) -- from
// general messages that need LLM processing.
package gateway
import (
"cmp"
"context"
"fmt"
"log/slog"
"slices"
"strconv"
"strings"
"sync"
"time"
"unicode"
"github.com/samcharles93/archie-core/internal/domain/messaging"
"github.com/samcharles93/archie-core/internal/ratelimit"
"github.com/samcharles93/archie-core/internal/releaseupdate"
"github.com/samcharles93/archie-core/internal/taskstate"
)
// Lifecycle receives adapter-owned startup facts.
type Lifecycle = messaging.Lifecycle
// A Gateway owns a persistent connection to a chat channel. Start blocks;
// the gateway should remain running until ctx is cancelled or Stop is called.
type Gateway interface {
Name() string
Start(ctx context.Context, router *Router, lifecycle Lifecycle) error
Stop(ctx context.Context) error
}
// StatusReader is the read-only query surface gateway-local commands
// like /status need. The daemon supplies its store, which satisfies this
// structurally.
type StatusReader interface {
StatusCounts(ctx context.Context) (map[string]int, error)
}
// LLMResponder routes a message to the LLM and returns the reply. When
// nil (not yet wired -- see abg.13), non-command messages get a static
// "LLM not configured" response. Gateways call this for any message the
// router did not handle directly.
type LLMResponder func(ctx context.Context, in Inbound) (string, error)
// LLMStreamResponder is the streaming counterpart of LLMResponder. It
// reports the turn's progress -- text fragments and completed tool calls
// -- to stream as it is generated, and returns the complete reply when the
// turn finishes.
//
// It is optional: a gateway that cannot render partial output, or a
// deployment whose provider does not stream, simply leaves it nil and the
// Router falls back to the blocking LLMResponder. stream is called from the
// generating goroutine and must not block for long -- adapters should
// throttle their own network writes rather than stall the stream.
type LLMStreamResponder func(ctx context.Context, in Inbound, stream TurnStream) (string, error)
// ModelManager provides access to available models and allows switching the
// active LLM model. The daemon supplies an implementation backed by its
// runtime provider catalog. When nil on a Router, /model returns a
// "not configured" message.
type ModelManager interface {
// Models returns all available model references in "provider/model" format.
Models() []string
// ActiveModel returns the currently active model reference.
// Returns empty string when no model is active.
ActiveModel() string
// SetActiveModel switches the active model. Returns an error if the
// reference is unknown.
SetActiveModel(ctx context.Context, ref string) error
}
// ProviderModelManager is the optional provider-aware extension used by
// gateways that offer a provider selector before model selection.
type ProviderModelManager interface {
ModelManager
Providers() []string
ActiveProvider() string
ModelsForProvider(provider string) []string
SetActiveProvider(ctx context.Context, provider string) error
}
// ModelDetails is the catalog metadata rendered after an interactive model
// selection. Limits are zero when the upstream catalog does not publish them.
type ModelDetails = messaging.ModelDetails
// DetailedModelManager is the optional catalog-aware extension used by rich
// model selectors. Runtime routing remains on ModelManager.
type DetailedModelManager interface {
ModelManager
ModelDetails(ref string) (ModelDetails, bool)
}
type ProviderDisplayNamer interface {
ProviderDisplayName(provider string) string
}
// UpdateService is the shared release workflow used by chat adapters. The
// recipient id scopes deferrals; each adapter chooses its own stable id.
type UpdateService interface {
Check(context.Context, int64) (releaseupdate.Snapshot, error)
Defer(context.Context, int64, releaseupdate.Snapshot) error
Install(context.Context, releaseupdate.Snapshot, releaseupdate.InstallMeta, func(string)) (releaseupdate.Result, error)
CanInstall() bool
}
// TaskController approves or cancels a chat-originated task. Both
// methods must enforce authorization (identity must own the task) and
// valid state transitions; see gateway.tasks.go's StoreTaskController
// for the reference implementation. When nil on a Router, /approve and
// /cancel return "not configured".
// AgentInfo is a lightweight agent summary for /agents.
type AgentInfo struct {
ID int64
Title string
Status string
Identity string
}
// AgentReader is the read surface /agents uses.
type AgentReader interface {
AgentList(ctx context.Context) ([]AgentInfo, error)
}
type TaskController interface {
// Approve moves a waiting_human task back to queued. Returns an
// error (surfaced to the user, not the LLM) if the task doesn't
// exist, isn't owned by identity, or isn't in waiting_human.
Approve(ctx context.Context, taskID int64, identity string) error
// Cancel moves an active task to a rejected/cancelled terminal
// state, interrupting it first if it is running. Returns an error if
// the task doesn't exist, isn't owned by identity, or is already
// terminal.
Cancel(ctx context.Context, taskID int64, identity string) error
// StopRunning interrupts every task currently executing for
// identity and returns the IDs it stopped. It is the agent half of
// /stop, so it must not require knowing a task ID: someone reaching
// for the brake is not in a position to look one up.
StopRunning(ctx context.Context, identity string) ([]int64, error)
}
// Router dispatches inbound messages. Gateway-local commands (like
// /status) are handled directly. Everything else is routed to the LLM
// responder. Gateway implementations call Route on every inbound
// message.
type Router struct {
Store StatusReader
Models ModelManager // nil = /model not configured
// ModelPersist persists the active model selection so it survives
// restarts (e.g. writing back to identity config). nil = not configured.
ModelPersist func(ctx context.Context, modelRef string) error
// Personas holds the available personality registry for /personality.
Personas *PersonaRegistry
Tasks TaskCreator // nil = /spawn not configured
Controller TaskController // nil = /approve and /cancel not configured
// TaskLister backs /tasks: the live work view (id, title, status,
// workflow/stage, age). nil = /tasks not configured.
TaskLister ChatTaskLister
LLM LLMResponder // nil = LLM not wired yet
// LLMStream is the optional streaming responder. When set, adapters
// that can render partial output (see RouteStream) show the reply as
// it generates; when nil, everything falls back to LLM.
LLMStream LLMStreamResponder
// Identity is the archie identity this router belongs to (empty in
// single-identity deployments). Propagated into SpawnRequest and
// used to scope /approve and /cancel authorization -- a task
// spawned under one identity cannot be controlled from another's
// chat session.
Identity string
// Version is shown by the shared /version command when supplied by the
// composition root. Empty means version information is unavailable.
Version string
// Updates handles the shared /update command. Nil means unavailable.
Updates UpdateService
// Restart requests a scoped chat-adapter reload. It deliberately does not
// restart the daemon; Telegram's /restart has this same boundary.
Restart func(context.Context) error
// Sessions persists session metadata and conversation history.
// When set, session lifecycle commands (/new, /branch, /title,
// /undo, /retry, /compress) are available. When nil, those
// commands report "not configured".
Sessions SessionStore
Agents AgentReader // nil = /agents not configured
// Titles proposes display titles for untitled sessions (see
// TitleGenerator). Nil disables automatic title generation; when set,
// the router asks for a title after a successful turn on a session
// that still has none, in the background, and persists the result.
Titles TitleGenerator
// Log is the optional logger for the best-effort background title
// path. Nil drops those diagnostics silently; nothing on this path is
// important enough to fail the turn over.
Log *slog.Logger
// Limiter enforces a per-(gateway, sender) inbound budget when set.
// Nil disables rate limiting entirely. Messages with no SenderID
// (channels that cannot supply a stable per-sender identity) are
// never limited, since there is no key to charge them against.
Limiter *ratelimit.Limiter
sessionTracker *sessionTracker
gatewayName string
// titlingMu guards titling, the set of sessions with a title proposal
// in flight (see claimTitleInFlight). Zero value is ready to use.
titlingMu sync.Mutex
titling map[string]struct{}
}
// NewRouter returns a Router. llm is optional -- when nil, non-command
// messages get a "not configured" response.
func NewRouter(store StatusReader, llm LLMResponder, gatewayName string) *Router {
return &Router{Store: store, LLM: llm, gatewayName: gatewayName}
}
// InitSessions wires the session store and starts tracking sessions.
// Must be called before session commands are used. Idempotent.
func (r *Router) InitSessions(sessions SessionStore) {
r.Sessions = sessions
r.sessionTracker = newSessionTracker(sessions)
}
// SessionTracker exposes the session tracker so that tool constructors
// (SessionTools) can bind session_resume to the active session without
// reaching into the Router's unexported fields.
func (r *Router) SessionTracker() *sessionTracker {
return r.sessionTracker
}
// rateLimitReply is returned to a sender who has exceeded their inbound
// budget, in place of normal dispatch.
const rateLimitReply = "You're sending messages too quickly. Please wait a moment and try again."
// checkRateLimit reports whether msg is over its sender's inbound budget.
// A nil Limiter (rate limiting not configured) or an empty SenderID
// (the channel has no stable per-sender identity to charge) always
// allows.
func (r *Router) checkRateLimit(msg messaging.Message) (blocked bool) {
if r.Limiter == nil || msg.SenderID == "" {
return false
}
return !r.Limiter.Allow(r.gatewayName, msg.SenderID)
}
// Route dispatches msg and returns the reply. Gateway-local commands
// are handled directly; everything else goes to the LLM responder.
func (r *Router) Route(ctx context.Context, in Inbound) (string, error) {
if r.checkRateLimit(in.Message) {
return rateLimitReply, nil
}
return r.route(ctx, in)
}
// route is Route's continuation once the caller has already cleared the
// rate-limit check (or is deliberately skipping it, as RouteStream's
// local-command fallthrough does to avoid charging one message twice).
func (r *Router) route(ctx context.Context, in Inbound) (string, error) {
text := strings.TrimSpace(in.Message.Text)
cmd, _ := parseCmd(text, r.gatewayName)
if reply, handled, err := r.dispatchLocal(ctx, in.Message, text, cmd); handled {
return reply, err
}
if strings.HasPrefix(cmd, "/") {
return fmt.Sprintf("Unknown command %s. Try /help.", cmd), nil
}
if r.LLM == nil {
return "I'm running but LLM processing isn't wired yet. Try /status.", nil
}
reply, err := r.LLM(ctx, in)
if err == nil {
r.maybeAutoTitle(ctx, in.Message)
}
return reply, err
}
// dispatchLocal handles recognized local commands. Returns (reply,
// true) when the command was recognized and handled.
func (r *Router) dispatchLocal(ctx context.Context, msg messaging.Message, text, cmd string) (string, bool, error) {
rest := restAfter(text, cmd, r.gatewayName)
switch cmd {
case "/status":
reply, err := r.handleStatus(ctx)
return reply, true, err
case "/tasks":
reply, err := r.handleTasks(ctx)
return reply, true, err
case "/model":
_, arg := parseCmd(text, "")
reply, err := r.handleModel(ctx, arg)
return reply, true, err
case "/spawn":
reply, err := r.handleSpawn(ctx, rest)
return reply, true, err
case "/approve":
reply, err := r.handleApprove(ctx, rest)
return reply, true, err
case "/cancel":
reply, err := r.handleCancel(ctx, rest)
return reply, true, err
case "/start":
reply, err := r.handleStart()
return reply, true, err
case "/whoami":
reply, err := r.handleWhoami()
return reply, true, err
case "/profile":
reply, err := r.handleProfile()
return reply, true, err
}
return r.dispatchLocalMisc(ctx, msg, cmd, rest)
}
// dispatchLocalMisc handles the remaining recognized local commands not
// covered by dispatchLocal's first switch. Split out to keep cyclomatic
// complexity down.
func (r *Router) dispatchLocalMisc(ctx context.Context, msg messaging.Message, cmd, rest string) (string, bool, error) {
switch cmd {
case "/sessions":
reply, err := r.handleSessions(ctx, msg)
return reply, true, err
case "/resume":
reply, err := r.handleResume(ctx, msg, rest)
return reply, true, err
case "/agents":
reply, err := r.handleAgents(ctx)
return reply, true, err
case "/personality":
reply, err := r.handlePersonality(ctx, msg, rest)
return reply, true, err
case "/help":
return r.helpText(), true, nil
case "/version":
return r.handleVersion(), true, nil
case "/update":
return r.handleUpdateCheck(ctx), true, nil
case "/restart":
return r.handleRestartAdapter(ctx), true, nil
}
return r.dispatchSessionCommand(ctx, msg, cmd, rest)
}
// handleVersion reports the configured build version.
func (r *Router) handleVersion() string {
if r.Version == "" {
return "Version information is not configured."
}
return r.Version
}
// handleUpdateCheck reports the latest available update snapshot.
func (r *Router) handleUpdateCheck(ctx context.Context) string {
if r.Updates == nil {
return "Updates are not configured."
}
snapshot, err := r.Updates.Check(ctx, 0)
if err != nil {
return fmt.Sprintf("Could not check for updates: %v", err)
}
return releaseupdate.FormatSnapshot(snapshot)
}
// handleRestartAdapter reloads the chat adapter.
func (r *Router) handleRestartAdapter(ctx context.Context) string {
if r.Restart == nil {
return "Chat adapter restart is not configured."
}
if err := r.Restart(ctx); err != nil {
return fmt.Sprintf("Could not restart the chat adapter: %v", err)
}
return "Chat adapter reload requested."
}
// dispatchSessionCommand handles the session-lifecycle command group
// (/new, /topic, /retry, /undo, /title, /branch, /compress and their
// aliases). Split out from dispatchLocal to keep cyclomatic complexity
// down.
func (r *Router) dispatchSessionCommand(ctx context.Context, msg messaging.Message, cmd, rest string) (string, bool, error) {
switch cmd {
case "/new", "/reset":
reply, err := r.handleNew(ctx, msg, rest)
return reply, true, err
case "/topic":
reply, err := r.handleTopic(ctx, msg, rest)
return reply, true, err
case "/retry":
reply, err := r.handleRetry(ctx, msg)
return reply, true, err
case "/undo":
reply, err := r.handleUndo(ctx, msg, rest)
return reply, true, err
case "/title":
reply, err := r.handleTitle(ctx, msg, rest)
return reply, true, err
case "/branch", "/fork":
reply, err := r.handleBranch(ctx, msg, rest)
return reply, true, err
case "/compress", "/compact":
reply, err := r.handleCompress(ctx, msg, rest)
return reply, true, err
case "/delete":
reply, err := r.handleDelete(ctx, msg, rest)
return reply, true, err
}
return "", false, nil
}
// RouteStream is Route for adapters that can render a reply progressively.
// stream receives each new fragment of an LLM reply as it is generated, plus
// each completed tool call, in the order the model produced them; the
// complete reply is returned as usual.
//
// Only free-text messages stream. Gateway-local commands (/status, /model,
// …) answer from local state in a single step, so they return through the
// normal path with no delta callbacks. When no streaming responder is
// configured, RouteStream is exactly Route -- callers get the whole reply
// at the end and simply never see a delta, so an adapter can always call
// RouteStream without checking first.
func (r *Router) RouteStream(ctx context.Context, in Inbound, stream TurnStream) (string, error) {
if r.LLMStream == nil || stream == nil {
return r.Route(ctx, in)
}
if r.checkRateLimit(in.Message) {
return rateLimitReply, nil
}
cmd, _ := parseCmd(strings.TrimSpace(in.Message.Text), r.gatewayName)
if isLocalCommand(cmd) || strings.HasPrefix(cmd, "/") {
return r.route(ctx, in)
}
reply, err := r.LLMStream(ctx, in, stream)
if err == nil {
r.maybeAutoTitle(ctx, in.Message)
}
return reply, err
}
// isLocalCommand reports whether cmd is answered from local state by
// Route rather than handed to the LLM.
func isLocalCommand(cmd string) bool {
return slices.Contains(messaging.LocalCommands(), cmd)
}
// parseCmd extracts the command name from text, stripping an optional
// @gateway mention from the command token, and returns the command and
// its first argument.
func parseCmd(text, gatewayName string) (cmd, arg string) {
fields := strings.Fields(text)
if len(fields) == 0 {
return "", ""
}
raw := fields[0]
if gatewayName != "" {
suffix := "@" + gatewayName
raw = strings.TrimSuffix(raw, suffix)
}
if len(fields) > 1 {
return raw, fields[1]
}
return raw, ""
}
func (r *Router) handleModel(ctx context.Context, arg string) (string, error) {
if r.Models == nil {
return "Model switching is not configured.", nil
}
if arg == "" {
models := r.Models.Models()
if manager, ok := r.Models.(ProviderModelManager); ok {
models = manager.ModelsForProvider(manager.ActiveProvider())
}
if len(models) == 0 {
return "No models configured.\nUsage: /model <provider/model>", nil
}
var b strings.Builder
b.WriteString("Usage: /model <provider/model>\nAvailable models:\n")
active := r.Models.ActiveModel()
for _, m := range models {
if m == active {
fmt.Fprintf(&b, " %s (active)\n", m)
} else {
fmt.Fprintf(&b, " %s\n", m)
}
}
return b.String(), nil
}
if err := r.Models.SetActiveModel(ctx, arg); err != nil {
return fmt.Sprintf("Cannot switch: %v", err), nil
}
return fmt.Sprintf("Active model set to %s.", arg), nil
}
// restAfter returns the text after the command token, stripping the
// optional @gateway mention. E.g. for "/spawn Fix the bug", returns
// "Fix the bug".
func restAfter(text, cmd, gatewayName string) string {
s := text
if gatewayName != "" {
s = strings.TrimPrefix(s, cmd+"@"+gatewayName)
}
s = strings.TrimPrefix(s, cmd)
return strings.TrimSpace(s)
}
// handleSpawn parses optional leading identity, repo, and workflow tokens
// off rest, treating whatever remains as the task title.
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}
fields := strings.Fields(rest)
i := 0
for i < len(fields) {
if after, ok := strings.CutPrefix(fields[i], "identity="); ok {
req.Identity = after
i++
continue
}
if after, ok := strings.CutPrefix(fields[i], "repo="); ok {
req.Repo = after
i++
continue
}
if after, ok := strings.CutPrefix(fields[i], "workflow="); ok {
req.Workflow = after
i++
continue
}
break // remaining fields are all title
}
req.Title = strings.TrimSpace(strings.Join(fields[i:], " "))
if req.Title == "" {
return "Usage: /spawn [identity=name] [repo=owner/name] [workflow=name] <title>", nil
}
id, err := r.Tasks.CreateTask(ctx, req)
if err != nil {
return fmt.Sprintf("Failed to create task: %v", err), nil
}
return fmt.Sprintf("Created task %d: %s", id, req.Title), nil
}
// parseTaskID parses a chat command argument as a task database ID.
func parseTaskID(arg string) (int64, error) {
if arg == "" {
return 0, fmt.Errorf("missing task ID")
}
id, err := strconv.ParseInt(arg, 10, 64)
if err != nil {
return 0, fmt.Errorf("%q is not a valid task ID", arg)
}
return id, nil
}
func (r *Router) handleApprove(ctx context.Context, rest string) (string, error) {
if r.Controller == nil {
return "Task control is not configured.", nil
}
identity, arg := parseTaskControl(rest, r.Identity)
id, err := parseTaskID(arg)
if err != nil {
return "Usage: /approve [identity=name] <task-id>", nil //nolint:nilerr // chat commands report problems as text to the human, never as Go errors, which would surface as a gateway fault
}
if err := r.Controller.Approve(ctx, id, identity); err != nil {
return fmt.Sprintf("Cannot approve task %d: %v", id, err), nil
}
return fmt.Sprintf("Task %d approved and requeued.", id), nil
}
func (r *Router) handleCancel(ctx context.Context, rest string) (string, error) {
if r.Controller == nil {
return "Task control is not configured.", nil
}
identity, arg := parseTaskControl(rest, r.Identity)
id, err := parseTaskID(arg)
if err != nil {
return "Usage: /cancel [identity=name] <task-id>", nil //nolint:nilerr // chat commands report problems as text to the human, never as Go errors, which would surface as a gateway fault
}
if err := r.Controller.Cancel(ctx, id, identity); err != nil {
return fmt.Sprintf("Cannot cancel task %d: %v", id, err), nil
}
return fmt.Sprintf("Task %d cancelled.", id), nil
}
func parseTaskControl(rest, defaultIdentity string) (identity, taskID string) {
fields := strings.Fields(rest)
identity = defaultIdentity
if len(fields) > 0 && strings.HasPrefix(fields[0], "identity=") {
identity = strings.TrimPrefix(fields[0], "identity=")
fields = fields[1:]
}
if len(fields) != 1 {
return identity, ""
}
return identity, fields[0]
}
func (r *Router) handleStatus(ctx context.Context) (string, error) {
if r.Store == nil {
return "store not configured", nil
}
counts, err := r.Store.StatusCounts(ctx)
if err != nil {
return "", fmt.Errorf("status: %w", err)
}
return formatStatus(counts, r.Models), nil
}
// handleTasks answers /tasks: the live view of this identity's work, with
// enough identity and state to act on it. This is the division of labour
// /status used to blur -- /status now reports health, /tasks reports work.
func (r *Router) handleTasks(ctx context.Context) (string, error) {
if r.TaskLister == nil {
return "task list not configured", nil
}
tasks, err := r.TaskLister.ListChatTasks(ctx, r.Identity, defaultTaskListLimit)
if err != nil {
return "", fmt.Errorf("tasks: %w", err)
}
return formatTasks(tasks, time.Now()), nil
}
// reportLineBreak ends a line of a line-oriented report. A chat report is a
// list of facts, not prose, so every one of its newlines is a real break;
// plain "\n" is CommonMark's soft wrap, which a Markdown-rendering channel
// joins into one run-on paragraph (see the Telegram renderer's
// markdownBlockParser).
const reportLineBreak = " \n"
// parkReasonMaxRunes bounds the park reason shown per task. A reason carries
// whatever the failing stage reported, which for a lint or test gate is a
// whole tool log; unbounded, one parked task pushes every other task out of
// the reply.
const parkReasonMaxRunes = 160
// summarizeParkReason reduces a park reason to one readable line: the first
// non-empty line, bounded. The full reason stays on the task, which /task and
// the dashboard show in full -- this is the list view.
func summarizeParkReason(reason string) string {
line := reason
if first, _, ok := strings.Cut(reason, "\n"); ok {
line = first
}
line = strings.TrimSpace(line)
if line == "" {
line = strings.TrimSpace(reason)
}
runes := []rune(line)
if len(runes) <= parkReasonMaxRunes {
return line
}
return strings.TrimSpace(string(runes[:parkReasonMaxRunes])) + "..."
}
// formatTasks renders each task with enough identity and state to act on
// it: id, title, status, workflow/stage, and age since its last
// transition -- so a task that is running but stuck (old UpdatedAt) reads
// differently from one making progress (recent UpdatedAt), which a bare
// status count could never distinguish.
func formatTasks(tasks []ChatTaskSummary, now time.Time) string {
var b strings.Builder
b.WriteString("🗂 Archie tasks\n\n")
if len(tasks) == 0 {
b.WriteString("No tasks yet\n")
return strings.TrimSpace(b.String())
}
sortTasksByPriority(tasks)
for _, t := range tasks {
icon, label := "•", formatCustomStatus(t.Status)
if d, ok := taskStateDisplays[t.Status]; ok {
icon, label = d.icon, d.label
}
fmt.Fprintf(&b, "%s #%d %s%s", icon, t.ID, t.Title, reportLineBreak)
fmt.Fprintf(&b, " %s", label)
if stage := workflowStage(t.Workflow, t.Stage); stage != "" {
fmt.Fprintf(&b, " · %s", stage)
}
if t.Attempt > 1 {
fmt.Fprintf(&b, " · attempt %d", t.Attempt)
}
if age := relativeAge(t.UpdatedAt, now); age != "" {
fmt.Fprintf(&b, " · updated %s", age)
}
if t.Status == taskstate.Parked && t.ParkReason != "" {
fmt.Fprintf(&b, "%s ↳ %s", reportLineBreak, summarizeParkReason(t.ParkReason))
}
b.WriteString("\n\n")
}
return strings.TrimSpace(b.String())
}
// workflowStage joins a task's workflow and stage for display, degrading
// gracefully when either is unknown (e.g. a task that hasn't started its
// first stage yet).
func workflowStage(workflow, stage string) string {
switch {
case workflow == "" && stage == "":
return ""
case stage == "":
return workflow
case workflow == "":
return stage
default:
return workflow + "/" + stage
}
}
type taskStateDisplay struct {
icon string
label string
}
var taskStateDisplays = map[string]taskStateDisplay{
taskstate.Running: {icon: "▶", label: "Running"},
taskstate.WaitingHuman: {icon: "👤", label: "Waiting"},
taskstate.Parked: {icon: "⏸", label: "Parked"},
taskstate.Queued: {icon: "⏳", label: "Queued"},
taskstate.PROpen: {icon: "🔀", label: "PR open"},
taskstate.Merged: {icon: "✅", label: "Merged"},
taskstate.Rejected: {icon: "❌", label: "Rejected"},
taskstate.Declined: {icon: "🚫", label: "Declined"},
"declined": {icon: "🚫", label: "Declined"},
taskstate.Dead: {icon: "🛑", label: "Dead"},
}
var statusOrder = []string{
taskstate.Running,
taskstate.WaitingHuman,
taskstate.Parked,
taskstate.Queued,
taskstate.PROpen,
taskstate.Merged,
taskstate.Rejected,
taskstate.Declined,
"declined",
taskstate.Dead,
}
// sortTasksByPriority orders tasks so the ones an operator would look for
// first -- running, then waiting on them, then parked -- lead the list,
// with terminal states (merged, rejected, dead, ...) trailing. It is
// stable, so within one status group the lister's own recency order
// survives.
func sortTasksByPriority(tasks []ChatTaskSummary) {
orderMap := make(map[string]int, len(statusOrder))
for i, s := range statusOrder {
orderMap[s] = i
}
slices.SortStableFunc(tasks, func(a, b ChatTaskSummary) int {
idxA, okA := orderMap[a.Status]
idxB, okB := orderMap[b.Status]
if okA && okB {
return cmp.Compare(idxA, idxB)
}
if okA {
return -1
}
if okB {
return 1
}
return strings.Compare(a.Status, b.Status)
})
}
func formatCustomStatus(s string) string {
s = strings.TrimSpace(strings.ReplaceAll(s, "_", " "))
if s == "" {
return "Unknown"
}
r := []rune(s)
r[0] = unicode.ToUpper(r[0])
return string(r)
}
var knownProviderNames = map[string]string{
"openai": "OpenAI",
"openrouter": "OpenRouter",
"anthropic": "Anthropic",
"deepseek": "DeepSeek",
"google": "Google",
"ollama": "Ollama",
"github": "GitHub",
"gh": "GitHub",
"groq": "Groq",
"together": "Together",
"bedrock": "Bedrock",
"azure": "Azure",
}
func formatProviderName(provider string) string {
trimmed := strings.TrimSpace(provider)
if trimmed == "" {
return ""
}
if name, ok := knownProviderNames[strings.ToLower(trimmed)]; ok {
return name
}
if strings.ToLower(trimmed) == trimmed {
r := []rune(trimmed)
r[0] = unicode.ToUpper(r[0])
return string(r)
}
return trimmed
}
func extractRuntimeInfo(models ModelManager) (provider, model string) {
if models == nil {
return "", ""
}
model = strings.TrimSpace(models.ActiveModel())
if pmm, ok := models.(ProviderModelManager); ok {
provider = strings.TrimSpace(pmm.ActiveProvider())
}
if provider == "" && model != "" {
if p, _, ok := strings.Cut(model, "/"); ok {
provider = p
}
}
if pdn, ok := models.(ProviderDisplayNamer); ok && provider != "" {
if name := strings.TrimSpace(pdn.ProviderDisplayName(provider)); name != "" {
return name, model
}
}
return formatProviderName(provider), model
}
// formatRuntimeSection appends the active provider and model as two more
// report lines. They are not given a section header of their own: /status is
// four facts, and a header for the last two made a short report read like a
// document.
func formatRuntimeSection(b *strings.Builder, provider, model string) {
if provider == "" && model == "" {
b.WriteString("Runtime: not configured")
return
}
if provider == "" {
provider = "not configured"
}
if model == "" {
model = "not configured"
}
fmt.Fprintf(b, "Provider: %s%sModel: %s", provider, reportLineBreak, model)
}
// formatStatus formats daemon health into a clean, mobile-friendly summary.
// It deliberately does not itemize tasks -- that is /tasks' job -- so it
// reduces the task counts to one aggregate health signal (is work backing
// up) rather than duplicating /tasks' per-task list.
func formatStatus(counts map[string]int, models ModelManager) string {
var b strings.Builder
b.WriteString("📊 Archie status\n\n")
b.WriteString(formatQueueDepth(counts))
b.WriteString(reportLineBreak)
provider, model := extractRuntimeInfo(models)
formatRuntimeSection(&b, provider, model)
return b.String()
}
// formatQueueDepth summarizes in-flight work as one line: how many tasks
// are running, waiting on a human reply, or parked. Queued and terminal
// states are excluded -- neither is a health concern an operator needs
// /status to surface.
func formatQueueDepth(counts map[string]int) string {
running := counts[taskstate.Running]
waiting := counts[taskstate.WaitingHuman]
parked := counts[taskstate.Parked]
inFlight := running + waiting + parked
if inFlight == 0 {
return "Queue: idle"
}
var parts []string
if running > 0 {
parts = append(parts, fmt.Sprintf("%d running", running))
}
if waiting > 0 {
parts = append(parts, fmt.Sprintf("%d waiting on you", waiting))
}
if parked > 0 {
parts = append(parts, fmt.Sprintf("%d parked", parked))
}
return fmt.Sprintf("Queue: %d in flight (%s)", inFlight, strings.Join(parts, ", "))
}
func (r *Router) handleWhoami() (string, error) {
if r.Identity == "" {
return "I'm Archie, running without a configured identity.", nil
}
var b strings.Builder
fmt.Fprintf(&b, "I'm %s.", r.Identity)
if r.Models != nil {
if active := r.Models.ActiveModel(); active != "" {
fmt.Fprintf(&b, " Running %s.", active)
}
}
return b.String(), nil
}
func (r *Router) handleProfile() (string, error) {
if r.Identity == "" {
return "Profile is not configured (no identity set).", nil
}
var b strings.Builder
fmt.Fprintf(&b, "Identity: %s\n", r.Identity)
if r.Models != nil {
fmt.Fprintf(&b, "Model: %s\n", r.Models.ActiveModel())
}
return strings.TrimSpace(b.String()), nil
}
func (r *Router) handleSessions(ctx context.Context, msg messaging.Message) (string, error) {
if r.Sessions == nil {
return "Session management is not configured.", nil
}
sessions, err := r.Sessions.List(ctx)
if err != nil {
return "", fmt.Errorf("list sessions: %w", err)
}
active := ""
if r.sessionTracker != nil {
active = r.sessionTracker.getActive(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID)
}
return renderSessionList(sessions, active, time.Now()), nil
}
// renderSessionList formats sessions (already newest-first) as the
// /sessions reply: a count header, then one numbered, column-aligned row
// per session carrying an 8-character id prefix, its title, and a
// recency suffix. The active session (matched by ID) is marked.
func renderSessionList(sessions []SessionContext, active string, now time.Time) string {
if len(sessions) == 0 {
return "No sessions."
}
maxTitle := 0
for _, s := range sessions {
if l := len([]rune(sessionDisplayTitle(s))); l > maxTitle {
maxTitle = l
}
}
numW := len(strconv.Itoa(len(sessions)))
var b strings.Builder
fmt.Fprintf(&b, "Sessions (%d):\n", len(sessions))
for i, s := range sessions {
meta := relativeAge(sessionRecency(s), now)
if s.SessionID == active {
meta = "active · " + meta
}
fmt.Fprintf(&b, " %*d. %s %-*s · %s\n",
numW, i+1, shortSessionID(s.SessionID), maxTitle+1, sessionDisplayTitle(s), meta)
}
return strings.TrimSpace(b.String())
}
// shortSessionIDLen is how much of a session ID the chat surfaces show. It
// is also the shorthand /resume and /delete are given back, so every
// listing must truncate to the same width.
// UUIDv7 stores its timestamp at the front, so no fixed shorter prefix is
// guaranteed to distinguish sessions. UUID session references therefore use
// all 36 characters. The limit only abbreviates longer legacy/non-UUID keys.
const shortSessionIDLen = 36
// shortSessionID renders the abbreviated form of a session ID used
// wherever a session is listed.
//
// Truncation is on a rune boundary: slicing bytes could split a
// multi-byte channel-ID-derived session key mid-rune and emit invalid
// UTF-8. UUID keys are ASCII, so this only differs for the exotic cases --
// where it must stay well-formed.
func shortSessionID(id string) string {
if r := []rune(id); len(r) > shortSessionIDLen {
return string(r[:shortSessionIDLen])
}
return id
}
// resolveSessionRef resolves an operator-supplied session reference
// against a session list, the way /resume and /delete both accept one.
//
// An exact ID wins outright -- a full ID names one session unambiguously
// even when it is also the prefix of a longer one -- otherwise the
// reference must be a prefix of exactly one session. It returns (nil,
// false) when nothing matches and (nil, true) when more than one session
// shares the prefix.
func resolveSessionRef(sessions []SessionContext, ref string) (match *SessionContext, ambiguous bool) {
for i, s := range sessions {
if s.SessionID == ref {
return &sessions[i], false
}
}
var found *SessionContext
for i, s := range sessions {
if !strings.HasPrefix(s.SessionID, ref) {
continue
}
if found != nil {
return nil, true
}
found = &sessions[i]
}
return found, false
}
// sessionDisplayTitle is the title a session is shown under, falling
// back to the standard placeholder when none has been set or generated.
func sessionDisplayTitle(sc SessionContext) string {
if sc.Title != "" {
return sc.Title
}
return "(untitled)"
}
// relativeAge renders an instant as a short human age ("5m ago") for
// session listings. The zero time renders as an empty string.
func relativeAge(t, now time.Time) string {
if t.IsZero() {
return ""
}
d := now.Sub(t)
switch {
case d < time.Minute:
return "just now"
case d < time.Hour:
return fmt.Sprintf("%dm ago", int(d.Minutes()))
case d < 24*time.Hour:
return fmt.Sprintf("%dh ago", int(d.Hours()))
case d < 7*24*time.Hour:
return fmt.Sprintf("%dd ago", int(d.Hours()/24))
default:
return t.Format("Jan 2")
}
}
// handleResume switches the active session for the current channel+thread
// to the session whose ID matches or is uniquely prefixed by arg.
func (r *Router) handleResume(ctx context.Context, msg messaging.Message, arg string) (string, error) {
arg = strings.TrimSpace(arg)
if arg == "" {
return "Usage: /resume <session-id>", nil
}
if r.Sessions == nil {
return "Session management is not configured.", nil
}
sessions, err := r.Sessions.List(ctx)
if err != nil {
return "", fmt.Errorf("list sessions: %w", err)
}
match, ambiguous := resolveSessionRef(sessions, arg)
switch {
case ambiguous:
return fmt.Sprintf("Multiple sessions match %q; be more specific.", arg), nil
case match == nil:
return fmt.Sprintf("No session matching %q.", arg), nil
}
return r.resumeSession(msg, *match), nil
}
func (r *Router) resumeSession(msg messaging.Message, s SessionContext) string {
if r.sessionTracker != nil {
r.sessionTracker.setActive(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID, s.SessionID)
}
return fmt.Sprintf("Resumed session %s.", s.SessionID)
}
func (r *Router) handleAgents(ctx context.Context) (string, error) {
if r.Agents == nil {
return "Agent listing is not configured.", nil
}
agents, err := r.Agents.AgentList(ctx)
if err != nil {
return "", fmt.Errorf("list agents: %w", err)
}
if len(agents) == 0 {
return "No active agents.", nil
}
var b strings.Builder
b.WriteString("Active agents:\n")
for _, a := range agents {
fmt.Fprintf(&b, " #%d %s — %s (%s)\n", a.ID, a.Title, a.Status, a.Identity)
}
return strings.TrimSpace(b.String()), nil
}