command

package
v0.49.0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 16 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], and — where the agent and relay support it — !mcp login <server>|cancel (see mcplogin.go). 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.

View Source
const MCPMethodPrefix = "mcp:"

MCPMethodPrefix prefixes an MCP server name to form its authenticate methodId ("mcp:github"). Such ids are dynamic: the agent never lists them in initialize, and the broker never checks them against AuthMethods.

View Source
const SkillName = "relay-commands"

SkillName is the name of the built-in relay-commands skill.

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 FormatTokens added in v0.21.0

func FormatTokens(n int) string

FormatTokens renders a token count compactly for a phone screen: 950, 12.3k, 1.2M.

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 MatchModels added in v0.17.1

func MatchModels(all []client.ModelInfo, filter string) []client.ModelInfo

MatchModels selects the models a `!model <filter>` listing names, in ranked order. An empty filter matches everything (agent order); otherwise the top-tier fuzzy ResolveModel candidates come first, then every other model whose ID or Name holds the filter as a case-insensitive substring, in agent order. The result is always a fresh slice, never an alias of all.

Exported because a relay may render the SAME selection onto a surface this package cannot know about — zulip-acp narrows its votable model poll with it (internal/handler/opts.go). If a relay re-implemented the rule, the poll and this listing's prose would disagree about what "opus" matches, and a user would be told two different things about one filter. There is one matcher, here, and ModelList itself uses it.

func PassthroughCommands added in v0.36.0

func PassthroughCommands() []string

PassthroughCommands returns the sorted passthrough allowlist: the agent commands a user may send as `!<cmd> args`, forwarded as `/<cmd> args`.

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 ResolveModel added in v0.28.0

func ResolveModel(all []client.ModelInfo, q string) (exact bool, cands []client.ModelInfo)

ResolveModel fuzzily resolves a user's model query against the available ids, returning whether the query is an exact id and the candidates of the best tier reached, best first.

The query splits on its last '/' into provider and model parts (a single part is matched against the model part under any provider). Each part is lower-cased, stripped of - _ . and spaces, and cut into letter runs and digit runs. A letter run matches as an ordered subsequence of adjacent letter runs ("anth" ~ anthropic, "opus" ~ claude-opus); a digit run must equal or prefix one whole digit run of the id, where separated digits merge ("55" ~ 5-5, but not 4-5). Date-like digit runs are skipped, never matched.

Ties inside a tier break on the tightest token span, then the shortest id, then the agent's order.

Policy for callers: exact → switch; exactly one candidate → switch and echo the full id; several → list them; none → fall back to a plain substring filter (MatchModels does this).

func SafeFileName added in v0.44.0

func SafeFileName(name string) string

SafeFileName reduces an untrusted file name to a base name a relay can show and store: path separators, control and format characters (including bidi overrides that could spoof an extension) go, and an empty, "." or ".." result becomes "file".

func SkillBundle added in v0.36.0

func SkillBundle() fs.FS

SkillBundle returns an fs.FS laid out for skills.LoadBuiltinIn (bundle/<name>/SKILL.md) holding the generated relay-commands skill. Load it under its own appPrefix, distinct from the relay's own bundle.

func SkillMarkdown added in v0.36.0

func SkillMarkdown() string

SkillMarkdown renders the relay-commands SKILL.md. It is GENERATED from brokerCommands and passthroughAllow so it cannot drift from the code that actually handles the commands.

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) AddHelp added in v0.22.0

func (b *Broker) AddHelp(lines ...string)

AddHelp appends relay-supplied bullets (each a full "- `!x` — …\n" line) to !help, listed with the relay commands. Used for optional commands the broker does not own, e.g. acp-kit/update's HelpLine. Call at startup, before any turns.

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) CanPostFile added in v0.44.0

func (b *Broker) CanPostFile() bool

CanPostFile reports whether the relay can deliver files 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) DownloadLinker added in v0.45.0

func (b *Broker) DownloadLinker() (DownloadLinker, bool)

DownloadLinker returns the relay's DownloadLinker, if any.

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) PostFile added in v0.44.0

func (b *Broker) PostFile(convID string, f OutFile) ([]string, error)

PostFile delivers f into the conversation as an attachment. The name is reduced to a safe base name (no directories, no control characters) and an empty media type becomes "application/octet-stream". An empty file is refused: no chat surface renders one usefully.

func (*Broker) PostIDs added in v0.35.0

func (b *Broker) PostIDs(convID, text string) ([]string, error)

PostIDs is Post, but returns the ids of the posted messages when the relay's Poster is an IDPoster. Otherwise it posts with PostTo and returns no ids.

func (*Broker) PostUploaded added in v0.45.0

func (b *Broker) PostUploaded(convID string, f mcphost.UploadedFile, caption string) ([]string, error)

PostUploaded posts a file stored by an out-of-band upload, with its name reduced to a safe base name and its media type normalised.

func (*Broker) Rekey added in v0.43.0

func (b *Broker) Rekey(from, to string)

Rekey moves the conversation's pending login from token from to token to. A relay whose conversation token can change — zulip-acp keys a conversation by its topic, and a topic can be renamed — calls it when the token changes, so the paste that finishes the login is still recognised where the conversation now is.

When to already waits for a login, that one is kept and the one under from is cancelled, best effort: one conversation has one pending login. from == to is a no-op.

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) SetDownloadLinker added in v0.45.0

func (b *Broker) SetDownloadLinker(d DownloadLinker)

SetDownloadLinker supplies DownloadLinker separately; it takes precedence over one implemented by the Poster or the Controller.

func (*Broker) SetFilePoster added in v0.44.0

func (b *Broker) SetFilePoster(p FilePoster)

SetFilePoster supplies the FilePoster capability separately from the Controller; see SetPoster. It takes precedence over a FilePoster implemented by the Poster or by the Controller.

func (*Broker) SetPoster added in v0.24.0

func (b *Broker) SetPoster(p Poster)

SetPoster supplies the Poster capability separately from the Controller, for a relay whose Controller is not its own type (a convo.Manager's). It takes precedence over the Controller's own.

func (*Broker) SetScheduler added in v0.24.0

func (b *Broker) SetScheduler(s Scheduler)

SetScheduler supplies the Scheduler capability separately from the Controller; see SetPoster.

func (*Broker) SetUploadTargeter added in v0.45.0

func (b *Broker) SetUploadTargeter(u UploadTargeter)

SetUploadTargeter supplies UploadTargeter separately; it takes precedence over one implemented by the Poster or the Controller.

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) StatusContext added in v0.41.0

func (b *Broker) StatusContext(ctx context.Context, convID string) (string, error)

StatusContext is Status with the caller's context, handed to a Controller that implements ContextStatusReporter.

func (*Broker) Unschedule added in v0.9.0

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

Unschedule disarms one of the conversation's schedules.

func (*Broker) UploadTargeter added in v0.45.0

func (b *Broker) UploadTargeter() (UploadTargeter, bool)

UploadTargeter returns the relay's UploadTargeter, if any.

type BrokerCommand added in v0.36.0

type BrokerCommand struct {
	Verb  string // command word, without sigil
	Args  string // argument synopsis, "" if none
	Alias string // short alias, "" if none
	Help  string
	Need  Need
}

BrokerCommand documents one command the broker itself answers (as opposed to a passthrough command forwarded to the agent).

func BrokerCommands added in v0.36.0

func BrokerCommands() []BrokerCommand

BrokerCommands returns a copy of the broker's own command table.

func (BrokerCommand) Usage added in v0.36.0

func (c BrokerCommand) Usage() string

Usage renders the command as the user types it, e.g. "`!model [filter|id]` (or `!m`)".

type ContextSessionLocator added in v0.41.0

type ContextSessionLocator interface {
	ACPSessionIDContext(ctx context.Context, convID string) (sessionID string, ok bool)
}

ContextSessionLocator is the OPTIONAL SessionLocator refinement that sees the command's context. A relay can carry the sender there, so the lookup can find the sender's own session when a conversation has one session per user (zulip-acp's session_scope "thread_user"). It only takes effect on a Controller that is also a SessionLocator (which enables `!mcp login`); the broker then calls it in place of ACPSessionID. acp-kit/convo's Controller implements it.

type ContextStatusReporter added in v0.41.0

type ContextStatusReporter interface {
	StatusForContext(ctx context.Context, convID string) SessionStatus
	RelayInfoContext(ctx context.Context, convID string) RelayInfo
}

ContextStatusReporter is the OPTIONAL Controller refinement behind `!status` that sees the command's context. A relay can carry the sender there, so the status can show the sender's own session when a conversation has one session per user (zulip-acp's session_scope "thread_user"). When the Controller implements it, the broker calls it in place of StatusFor and RelayInfo. acp-kit/convo's Controller implements it.

type ContextTurnStopper added in v0.41.0

type ContextTurnStopper interface {
	StopTurnContext(ctx context.Context, convID string) bool
}

ContextTurnStopper is the OPTIONAL TurnStopper refinement that sees the command's context, so `!stop` can stop the sender's own turn when a conversation has one session per user. It only takes effect on a Controller that is also a TurnStopper (which enables `!stop`); the broker then calls it in place of StopTurn. acp-kit/convo's Controller implements it.

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 DownloadLinker added in v0.45.0

type DownloadLinker interface {
	// AttachmentsIn lists the conversation's recent inbound attachments,
	// newest first.
	AttachmentsIn(convID string) ([]InboundAttachment, error)
	// DownloadLinkFor returns a download target for one of them. Size
	// must be exact; a link should be single-use or expire quickly.
	DownloadLinkFor(convID, attachmentID string) (mcphost.DownloadTarget, error)
}

DownloadLinker is the OPTIONAL capability behind the `list_attachments` / `fetch_attachment` tools: it exposes files users attached in the conversation as MCP download targets — absolute https URLs the platform already serves (a temporary signed URL, a relay-hosted proxy link), never one that needs the relay's credentials.

type FilePoster added in v0.44.0

type FilePoster interface {
	PostFileTo(convID string, f OutFile) ([]string, error)
}

FilePoster is the OPTIONAL capability behind the agent-facing `send_file` tool: it delivers a file into a conversation as an attachment, out of band, exactly like Poster does for text.

The blast radius is Poster's: PostFileTo takes the conversation token the tool call was bound to and nothing else, so an agent can only ever send a file to the conversation that is talking to it. It returns the ids of the messages it put on the surface, oldest first, or nil when the relay has no such ids.

type IDPoster added in v0.35.0

type IDPoster interface {
	PostToIDs(convID, text string) ([]string, error)
}

IDPoster is an OPTIONAL refinement of Poster for a relay whose posts have message ids the agent can act on later — for example to add a reaction to the message it just posted. PostToIDs returns the ids of every message the post put on the surface, oldest first. A relay that has no such ids implements only Poster.

type InboundAttachment added in v0.45.0

type InboundAttachment struct {
	ID       string // relay-chosen, stable within the conversation
	Name     string
	MimeType string
	Size     int64 // -1 when unknown
}

InboundAttachment is a file a user attached in the conversation.

type Need added in v0.36.0

type Need int

Need names the relay capability a broker command depends on.

const (
	// Always: the command is available on every broker.
	Always Need = iota
	// NeedController: requires a wired Controller.
	NeedController
	// NeedStopper: requires a Controller implementing TurnStopper.
	NeedStopper
	// NeedScheduler: requires a Controller and a Scheduler.
	NeedScheduler
	// NeedMCPLogin: requires a SessionAuthenticator and a Controller
	// implementing SessionLocator.
	NeedMCPLogin
)

type OutFile added in v0.44.0

type OutFile struct {
	// Name is the file name shown in the chat. Broker.PostFile reduces
	// it to a safe base name before the relay sees it.
	Name string
	// MimeType is the declared media type, "application/octet-stream"
	// when unknown. Untrusted: it is whatever the agent claimed.
	MimeType string
	// Data is the file content.
	Data []byte
	// Caption is optional text to accompany the file. A relay that
	// cannot attach text to a file may post it separately or drop it.
	Caption string
}

OutFile is a file the agent hands to the relay to deliver into a conversation. The bytes are already in memory: the relay decides how they reach the chat (an upload API, a message attachment, ...).

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
	// AgentName and AgentVersion identify the agent, from the ACP
	// initialize response (agentInfo) or another source the relay
	// trusts. "" when unknown.
	AgentName       string
	AgentVersion    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 SessionAuthenticator added in v0.40.0

type SessionAuthenticator interface {
	AuthenticateSession(ctx context.Context, sessionID, methodID, id, redirect string, cancel bool) (client.AuthResult, error)
}

SessionAuthenticator is the OPTIONAL Authenticator capability behind `!mcp login`: authenticate within one ACP session. *client.AgentProc implements it.

type SessionLocator added in v0.40.0

type SessionLocator interface {
	ACPSessionID(convID string) (sessionID string, ok bool)
}

SessionLocator is the OPTIONAL Controller capability behind `!mcp login`: the conversation's live ACP session id, without creating one. acp-kit/convo's Controller implements it.

It is deliberately a lookup and not a get-or-create: opening a session outside a turn would register a sink as the side effect of a command. With no live session the broker asks the user to send a message first.

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
	// ContextUsed and ContextSize are the tokens in the agent's
	// context window and its size, as the agent last reported them
	// (ACP usage_update). Zero when not reported.
	ContextUsed int
	ContextSize int
	// Cost is the cumulative session cost, pre-formatted (e.g.
	// "0.42 USD"); "" when the agent did not report one.
	Cost string
	// LastActivity is how long ago the conversation's session was last
	// used, pre-formatted (e.g. "4m10s"); "" when unknown.
	LastActivity string
}

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.

type UploadTargeter added in v0.45.0

type UploadTargeter interface {
	// UploadTargetFor mints a target for one file.
	UploadTargetFor(convID string, spec mcphost.UploadSpec) (mcphost.UploadTarget, error)
	// FinishUploadFor confirms the upload behind ref and reports what
	// the platform stored. It must fail when nothing arrived.
	FinishUploadFor(convID string, spec mcphost.UploadSpec, ref string) (mcphost.UploadedFile, error)
	// PostUploadedTo posts the stored file into the conversation, with
	// an optional caption, and returns the message ids it created.
	PostUploadedTo(convID string, f mcphost.UploadedFile, caption string) ([]string, error)
}

UploadTargeter is the OPTIONAL capability behind out-of-band uploads for `send_file`: instead of the agent's client pushing file bytes through the relay's MCP socket, the relay hands it a target on the chat platform's own https upload endpoint, the client uploads there, and the relay posts the already-stored file.

Every method is bound to the conversation the tool call came from. UploadTargetFor must mint a SCOPED, short-lived target: it is sent to the agent's client verbatim, so it must never carry the relay's own API credentials (mcphost refuses Authorization and Cookie headers). A platform whose upload API needs the bot token must be fronted by a one-shot relay-hosted endpoint instead; see docs/files-oob.md.

Jump to

Keyboard shortcuts

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