command

package
v0.16.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 8, 2026 License: MIT Imports: 9 Imported by: 2

Documentation

Overview

This file is the session-control surface as ACTIONS rather than as chat text.

Why it exists

The relay now has two front ends onto the same controls: the `!command` a human types, and the self-hosted MCP tools an agent calls mid-turn (see acp-kit/relaytool). If those two grew their own implementations they would drift — which is exactly the mistake the pre-v0.6.0 relays made with the command surface itself, and exactly what this package was created to correct. So there is one implementation: the exported methods below. The `!` handlers in command.go render their results as chat prose; relaytool hands the same results to the agent. Neither reaches the Controller directly.

The rule to keep: nothing in command.go may call b.ctrl for anything an action here already does.

Package command is the shared chat-command surface every relay puts in front of an ACP agent: it brokers interactive OAuth login (bridging one chat turn into the agent's _meta.auth.interactive two-call protocol) and the session-control commands (!status, !model, !new, !stop, !help).

The user-facing surface is deliberately small: !help, !status, !model [filter|id], !new, !stop, !schedules, !unschedule <id>, !login [provider|cancel]. Older spellings (!models, !relay, !bot, !cancel-login, !whoami, !reset) still work as undocumented aliases so nothing a user has learned ever breaks.

Two front ends, one implementation

The same session controls are reachable two ways: the `!command` a human types, and the self-hosted MCP tools an agent calls mid-turn (acp-kit/relaytool). Both go through the exported ACTIONS in actions.go — Status, ModelList, SelectModel, NewSession, Post, Schedule, ScheduleList, Unschedule. The `!` handlers are renderers over those actions and nothing more. Do not add a command that talks to the Controller directly: that is how the two surfaces drift, which is the exact failure this package was created to fix.

What lives here and what does not

Everything surface-independent: sigil handling, command classification, the login state machine, the passthrough allowlist, and the rendering — which stays shared because Poe, Zulip and Slack all read CommonMark-ish markdown and the strings are legal in all three verbatim. Duplicating identical prose per relay would recreate exactly the fork this package exists to remove. When a surface genuinely needs different markup, THAT is the moment to introduce a renderer interface, and not before.

What does not live here: anything that knows how a message arrives or is posted. The relay owns delivery, gating (who may speak to the bot), and any surface-specific pre-filter — e.g. zulip-acp must let Zulip's own /me, /poll and /todo widgets through untouched before the broker ever sees them, using the exported StripSigil helper.

Login

Each conversation can have at most one in-flight login. The first login command (e.g. "!login anthropic") calls the agent's authenticate to produce a URL; the next user turn from the same conversation submits the pasted redirect URL. The broker holds no goroutines — the actual blocking on user input happens inside the agent, parked across turns. The relay only remembers which conversation has a pending login for which method.

Sigils

Commands accept the sigils "/", "!", and "." but user-facing prose suggests "!" (DisplaySigil). Poe's chat client intercepts "/"-prefixed messages as native slash commands and rejects unknown ones before they reach the bot; Zulip's slash commands are handled client-side against /json/command and never reach a bot at all, while /me, /poll and /todo DO arrive as messages or widgets. So "/" is unsafe to advertise on either surface, and "!"/"." pass straight through on both.

Index

Constants

View Source
const DisplaySigil = "!"

DisplaySigil is the command prefix shown in user-facing messages. It is deliberately not "/" so the suggested commands survive Poe's client-side slash-command interceptor.

Variables

View Source
var ErrNoController = errors.New("session control is unavailable")

ErrNoController is returned by every action when the relay wired no Controller. The chat front end renders it as prose; the MCP front end surfaces it as a tool error.

Functions

func IsLoginCommand

func IsLoginCommand(text string) bool

IsLoginCommand reports whether text is a login/logins/cancel-login command under any accepted sigil (/, !, .). Trims leading whitespace so users can paste the command after a thought.

func RenderSchedules added in v0.9.0

func RenderSchedules(items []schedule.Item) string

RenderSchedules renders an armed-schedule listing for a human.

Times are absolute UTC rather than relative ("in 12m") on purpose: the listing is also what the agent reads back through list_schedules, and a relative time is only true at the instant it is rendered.

func StripSigil

func StripSigil(t string) (body string, ok bool)

StripSigil removes a single leading command sigil from t and reports whether one was present. Exported for relays that must apply a surface-specific policy BEFORE the broker sees a message — e.g. zulip-acp has to recognise Zulip's own /me, /poll and /todo, which unlike Zulip's client-side slash commands do arrive as real messages and widgets, and pass them through untouched.

Whitespace is trimmed here, so callers need not.

Types

type Authenticator

type Authenticator interface {
	AuthMethods() []client.AuthMethod
	Authenticate(ctx context.Context, methodID, id, redirect string, cancel bool) (client.AuthResult, error)
}

Authenticator is the agent-side surface the broker depends on. The full *client.AgentProc satisfies it.

type Broker

type Broker struct {
	// contains filtered or unexported fields
}

Broker tracks per-conversation pending logins.

func New

func New(a Authenticator) *Broker

New constructs a Broker.

func (*Broker) CanPost added in v0.9.0

func (b *Broker) CanPost() bool

CanPost reports whether the relay can post out of band.

func (*Broker) CanSchedule added in v0.9.0

func (b *Broker) CanSchedule() bool

CanSchedule reports whether the relay can schedule prompts.

func (*Broker) Handle

func (b *Broker) Handle(ctx context.Context, convID, text string) (*Outcome, error)

Handle dispatches one user turn. Behaviour:

  1. If the conversation has a pending login, treat any non-command text as the pasted redirect URL.
  2. Otherwise interpret !login [provider|cancel] (and the older !logins / !cancel-login spellings).

Returns (nil, nil) if the turn is not auth-related and should be forwarded to the normal prompt path.

func (*Broker) HasPending

func (b *Broker) HasPending(convID string) bool

HasPending reports whether the conversation is waiting for a pasted redirect URL.

func (*Broker) IsCommand

func (b *Broker) IsCommand(text string) bool

IsCommand reports whether text is any relay command THIS broker handles (the login family, "help", or a session command), under any accepted sigil. A relay uses it to decide whether to route a turn to the broker instead of forwarding it to the agent.

It is a method rather than a package function because the answer depends on the wired Controller: `!stop` is a command only where the relay can actually stop a turn.

func (*Broker) ModelList added in v0.9.0

func (b *Broker) ModelList(filter string) (string, error)

ModelList renders the available model ids, optionally filtered by substring.

func (*Broker) NewSession added in v0.9.0

func (b *Broker) NewSession(convID string) error

NewSession drops the conversation's live session so the next turn starts fresh.

func (*Broker) OfferLogin

func (b *Broker) OfferLogin() string

OfferLogin renders the onboarding message shown when the agent reports that no usable provider is connected (an "Authentication required" prompt error). It lists the loginable providers using the Poe-safe DisplaySigil. Safe for concurrent use. Returned text is empty-safe: it always yields actionable guidance, even with no OAuth methods.

func (*Broker) Passthrough

func (b *Broker) Passthrough(text string) (rewritten string, ok bool)

Passthrough decides whether text is an allowlisted agent command and, if so, returns the prompt text to forward to the agent (e.g. "!reload" → "/reload"). ok=false means the turn is not a passthrough command and should be handled normally. The command must be both allowlisted and actually advertised by the agent. Requires a wired Controller.

func (*Broker) Post added in v0.9.0

func (b *Broker) Post(convID, text string) error

Post sends a message into the conversation out of band. See Poster for why there is no target.

func (*Broker) Schedule added in v0.9.0

func (b *Broker) Schedule(convID, text string, at time.Time, every time.Duration) (schedule.Item, error)

Schedule arms a prompt to be injected into the conversation later.

func (*Broker) ScheduleList added in v0.9.0

func (b *Broker) ScheduleList(convID string) ([]schedule.Item, error)

ScheduleList returns the conversation's armed schedules.

func (*Broker) SelectModel added in v0.9.0

func (b *Broker) SelectModel(convID, modelID string) error

SelectModel switches the sticky model for the conversation.

func (*Broker) SetController

func (b *Broker) SetController(c Controller)

SetController wires the session-control surface (the router) used by !status/!model/!new. Call once at startup, after construction, to break the broker↔router construction cycle. Safe before any turns.

func (*Broker) Status added in v0.9.0

func (b *Broker) Status(convID string) (string, error)

Status renders one compact snapshot of everything a caller might ask about: the conversation's model / thinking / session plus the relay process's version / uptime / conversations.

Rendered as a short bullet list — it has to read well on a phone, so no tables and no wide lines; conversation state first, relay after. The agent reads the same markdown, which is fine: it is the same facts, and a second "structured" rendering would be a second thing to keep in step.

func (*Broker) Unschedule added in v0.9.0

func (b *Broker) Unschedule(convID, id string) error

Unschedule disarms one of the conversation's schedules.

type Controller

type Controller interface {
	AvailableModels() (models []client.ModelInfo, currentID string)
	SetModelOverride(convID, modelID string) error
	ResetSession(convID string) error
	StatusFor(convID string) SessionStatus
	AgentCommands() []client.CommandInfo
	RelayInfo(convID string) RelayInfo
}

Controller is the per-conversation session-control surface used by the non-auth commands (!status, !model, !new). Each relay implements it over whatever it uses for session state. Optional: if nil, those commands report unavailable. The dependency edge is one-way — a relay's session layer never imports this package.

convID is an OPAQUE, relay-chosen conversation token. The broker only ever hands it back; it never parses it and never assumes it is stable. Implementations are free to re-key the underlying session or identity behind it — zulip-acp's ResetSession retires a journal entry and allocates a fresh conversation id, which the broker neither sees nor needs to.

type Outcome

type Outcome struct {
	// Text is a plain message to stream as a Poe `text` event.
	Text string
	// URL, if non-empty, is the auth URL to surface to the user. Text
	// may also be set with prose preceding/following the URL.
	URL string
	// Instructions accompany URL.
	Instructions string
}

Outcome is what the HTTP handler should render to the user. Exactly one of Text / URL / Error is set; Done is always implied (the auth turn never streams further chunks).

type Poster added in v0.9.0

type Poster interface {
	PostTo(convID, text string) error
}

Poster is the OPTIONAL capability behind the agent-facing `post` tool: it sends a message into a conversation OUT OF BAND, outside any turn's streamed answer. It is what makes "go do X and tell me when it lands" expressible — progress on a long turn, or a result that arrives after the turn that started it has ended.

It is optional because not every relay can do it. A relay that answers one HTTP request per turn (poe-acp) has no channel to speak on once that request is over, so it must not advertise the tool.

Blast radius

PostTo takes the conversation token the tool call was bound to and NOTHING else. There is deliberately no target parameter: an agent that can post into arbitrary channels is a new and serious capability — a prompt-injected agent would gain a realm-wide megaphone — so in v1 it is not gated behind config, it is simply not expressible. Widening this later means adding a parameter, a config allowlist and a threat model, in that order.

type RelayInfo

type RelayInfo struct {
	Version         string
	Uptime          string // pre-formatted (e.g. "3h2m1s"); "" if unknown
	AgentCmd        string
	ModelsAvailable int
	ActiveSessions  int    // live conv sessions tracked by the router
	SessionID       string // this conv's live agent session id; "" if none
	EffectiveModel  string // override if set, else configured default
}

RelayInfo is a snapshot of relay-process realtime state, surfaced by the !relay chat command.

type Scheduler added in v0.9.0

type Scheduler interface {
	// CanSchedule reports whether scheduling is available RIGHT NOW.
	//
	// A type assertion can only answer "this relay could schedule";
	// it cannot answer "and the operator turned it on". zulip-acp
	// implements Scheduler unconditionally but only has a store when
	// `relay_mcp` is set, and without this the chat surface would
	// advertise `!schedules` on a relay where nothing can ever be
	// armed. Everything gates on it in one place — see Broker.scheduler
	// — so `!help`, the commands, Status and the MCP tools appear and
	// disappear together.
	CanSchedule() bool
	// Schedule arms a prompt. Depth and the caps are enforced by the
	// store, not by the caller.
	Schedule(convID, text string, at time.Time, every time.Duration) (schedule.Item, error)
	// Schedules lists what is armed for the conversation.
	Schedules(convID string) []schedule.Item
	// Unschedule disarms one item, scoped to the conversation.
	Unschedule(convID, id string) error
}

Scheduler is the OPTIONAL capability behind scheduled prompts. A relay implements it over acp-kit/schedule; see that package for the runaway bounds, which are the reason this is not simply a timer.

Optional for the same reason as Poster: firing a schedule means injecting a prompt into a conversation unprompted, which a request/response relay cannot do.

type SessionStatus

type SessionStatus struct {
	EffectiveModel  string // override if set, else the configured default
	DefaultModel    string
	OverrideModel   string // "" when no !model override is active
	Thinking        string
	HasSession      bool
	ModelsAvailable int

	// ConvID is the relay's own identifier for this conversation,
	// shown so a human can find its state on disk. Empty when the
	// relay has no such notion, or has not allocated one yet.
	ConvID string
	// StateDir is the conversation's working directory. Empty when the
	// relay does not give a conversation its own directory.
	StateDir string
	// Where renders the conversation in human terms — "#fleet >
	// \"hacking\"", "DM with Kfet". Empty when the surface has only one
	// place for a conversation to be.
	Where string
	// TurnRunning reports whether a turn is in flight right now. Only
	// meaningful on a relay that can tell; see TurnStopper.
	TurnRunning bool
}

SessionStatus is a race-free snapshot of a conversation's relay state. Every field is optional: the renderer prints only what is set, so a relay reports what it actually knows rather than padding the rest with plausible-looking blanks.

type TurnStopper

type TurnStopper interface {
	StopTurn(convID string) bool
}

TurnStopper is the OPTIONAL capability behind `!stop`. A Controller that implements it enables the command; one that does not leaves `!stop` unrecognised, so the text forwards to the agent as ordinary prose exactly as before.

That conditionality is the point. Only a relay that streams a turn has anything to interrupt: poe-acp answers one HTTP request per turn and has no in-flight turn a later message could reach, while zulip-acp streams into an editable message and very much does. Advertising a command that cannot work on half the relays would be worse than not having it.

StopTurn reports whether it actually stopped something, so the reply can tell interrupting from doing nothing.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL