remote

package
v1.18.1 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 14 Imported by: 0

README

remote — agents whose brain lives outside wick

A remote agent is a Team agent with no local CLI: each turn goes to something else (an A2A server, a person or bot in Slack) and the reply comes back as if a local provider had written it. Chat, @mention, schedules, the Slack bridge and the A2A server never learn the agent is remote.

pool ──Spawn──▶ remote.Spawner ──▶ runner (fake process, stream-json out)
                                     │ Send(turn) → Handle
                                     │ Receive (push) / Fetch (pull)
                                     │ Done: terminal event, idle, or Max
                                     ▼
                               Source (adapter)
                     a2aremote.Source    slackremote.Source

Pieces

  • Source (source.go) — one adapter per kind (a2a, slack), built on three primitives:
    • Send delivers the turn and returns a Handle (task id, thread_ts) the reply is matched by.
    • Receive — two ways, an adapter offers one or both and lists them in Listen(), preferred first:
      • push (Pusher.Receive): a channel of Events, closed when the source has no more to say. ErrPushUnavailable falls back to pull.
      • pull (Puller.Fetch): events since Handle.Cursor; the runner backs off along PullSteps (1→2→5→10 s).
    • Done — a terminal event (done / error), or the runner ends the turn: Limits.Idle after text then silence (NoteNoMarker), or Limits.Max as a timeout. End(h) is called once after every turn.
  • Runner (runner.go) — Spawner.Spawn returns a provider.Process with no OS process. Stdin takes stream-json user envelopes; stdout writes claude-shaped lines (assistant, result, system remote_status), so the claude parser, store and SSE read it unchanged.
  • Shared listener + router — push for Slack does not open a socket per agent. The Slack channel wick already runs hands every message event to slackremote.Shared.Dispatch (only while a turn waits), and the router sends it to the trackers waiting in that thread or DM. Pull (conversations.replies) covers what the app cannot see.
  • Hops (hops.go) — an A2A remote agent sends wick_hops (one more than the request that started the turn) in its message metadata; the A2A server refuses a request past MaxHops, so a remote pointing back at wick cannot loop. Slack has no such field: a Slack remote must not target a conversation wick itself answers.

Event schema v1

SchemaVersion = 1. Every adapter registers with Schema: remote.SchemaVersion; Register panics on any other value.

kind fields meaning
text_delta text append to the reply
text text the reply so far in full; runner shows the new tail
status status, detail thinking / working / input_required, short label
attachment name, url, mime a file the remote sent
done text?, note? ends the turn; text = whole reply if set
error text ends the turn as failed

Adding an optional field keeps v1. Renaming/removing a field or changing what a kind means is v2: bump SchemaVersion and move every adapter.

Adding an adapter

  1. New package under internal/agents/remote/<kind>remote/ (or next to the protocol's client, as a2aremote is).
  2. Register the kind in init:
    func init() {
        remote.Register(remote.Adapter{
            Kind: "foo", Label: "Foo", Schema: remote.SchemaVersion,
            Listen: []remote.ListenMode{remote.ListenPush, remote.ListenPull},
        })
    }
    
  3. Implement Source plus Pusher and/or Puller:
    type Source struct{ cfg Config }
    
    func (s *Source) Kind() string                { return "foo" }
    func (s *Source) Label() string               { return "foo-remote (" + s.cfg.Host + ")" }
    func (s *Source) Listen() []remote.ListenMode { return []remote.ListenMode{remote.ListenPull} }
    func (s *Source) Limits() remote.Limits       { return remote.Limits{Max: 10 * time.Minute, Idle: 30 * time.Second} }
    
    func (s *Source) Send(ctx context.Context, t remote.Turn) (remote.Handle, error) {
        id, err := s.post(ctx, t.Text) // keep per-session state under t.SessionDir
        return remote.Handle{ID: id}, err
    }
    func (s *Source) Fetch(ctx context.Context, h remote.Handle) ([]remote.Event, remote.Handle, error) {
        msgs, cursor, err := s.since(ctx, h.ID, h.Cursor)
        // map msgs to remote.Event; end with EventDone / EventError
        h.Cursor = cursor
        return evs, h, err
    }
    func (s *Source) Cancel(context.Context, remote.Handle) error { return nil }
    func (s *Source) End(remote.Handle)                           {}
    func (s *Source) Describe(context.Context) (remote.Description, error) { … }
    func (s *Source) Test(context.Context) remote.TestResult              { … }
    
    Optional: Resumer to name the chat session from saved state.
  4. Wire it into RemoteSpawnerFor and remoteProviderKey (internal/tools/agents) so a session bound to such an agent spawns remote.Spawner{Source: …}, plus the API/wizard that stores its config.
  5. Tests: drive remote.Spawner with a fake backend and read stdout, as slackremote/source_test.go does; the A2A exposure path is covered by a2aserver/remote_e2e_test.go.

Phase 3 (not built)

A generic templated HTTP adapter (URL/body/response path configured, no code), a wick-specific HTTP protocol, and a remote_source plugin kind so an adapter can ship as a plugin binary. All three slot in as a Source behind the same runner and event schema.

Documentation

Overview

Package remote runs agents whose brain lives outside wick. Each source (A2A, Slack, …) is an adapter behind one Source interface built on three primitives: Send a turn and get a handle, Receive what comes back (push: a channel of events; pull: Fetch with a cursor), and Done (a terminal event, or idle/timeout decided by the runner). The runner turns either style into the stream-json lines the rest of wick already reads.

Index

Constants

View Source
const (
	StatusThinking      = "thinking"
	StatusWorking       = "working"
	StatusInputRequired = "input_required"
	// StatusIdle: the remote no longer shows it is working (an hourglass
	// or assistant status went away). Not shown; it lets the idle window
	// run again.
	StatusIdle = "idle"
	// StatusForwarded: a message sent while the turn ran was handed to
	// the remote (Injector); the runner emits it, never a source.
	StatusForwarded = "forwarded"
)

Status values of an EventStatus.

View Source
const (
	QueueQueued    = "queued"
	QueueSent      = "sent"
	QueueCancelled = "cancelled"
	QueueForwarded = "forwarded"
)

Queue states of a remote_queue line.

View Source
const HopsKey = "wick_hops"

HopsKey is the A2A message metadata key a wick A2A call carries: how many wick A2A servers the turn has passed through, this call included. A remote agent pointing back at wick (at itself, or along a chain that loops) would otherwise call itself without end.

View Source
const MaxHops = 3

MaxHops is the most wick A2A servers one turn may pass through; a request that arrives counting more is refused before it reaches the pool, and the refusal fails every turn up the chain.

View Source
const NoteFollowUp = "follow-up"

NoteFollowUp labels a reply the remote sent or edited after its turn had ended, inside the grace window.

View Source
const NoteLate = "late reply"

NoteLate labels a reply the remote finished after its turn had timed out: a late answer to the same request, not a new message.

View Source
const NoteNoMarker = "ended without marker"

NoteNoMarker labels a turn that went quiet without its end marker.

View Source
const NoteRechecked = "rechecked"

NoteRechecked labels a reply read back by "Check again" after its turn had timed out or ended without its marker.

View Source
const SchemaVersion = 1

SchemaVersion is the version of the Event schema every adapter speaks; each adapter names it in its Adapter.Schema and Register refuses any other. v1 is the EventKind set and Event fields below. Adding an optional field is still v1; renaming or removing one, or changing what a kind means, is v2 and every adapter moves with it.

Variables

View Source
var ErrInjectUnsupported = errors.New("remote: inject not supported")

ErrInjectUnsupported is returned by Inject when this remote cannot take a message mid-turn after all (e.g. a plugin that does not declare it).

View Source
var ErrNoTurn = errors.New("this session has no remote turn to check")

ErrNoTurn: the session has posted no turn to read back.

View Source
var ErrPushUnavailable = errors.New("remote: push not available")

ErrPushUnavailable is returned by Receive when push cannot serve this turn (no live event stream); the runner falls back to pull.

View Source
var OnFollowUp func(sessionID, text, note string)

OnFollowUp, when set, also hands a follow-up reply to whoever asked the session's last turn (another agent over A2A). note is NoteFollowUp, or NoteLate for the reply to a turn that timed out. Set once at startup.

View Source
var PullSteps = []time.Duration{time.Second, 2 * time.Second, 5 * time.Second, 10 * time.Second}

PullSteps is the pull backoff: the wait before each Fetch while nothing new arrives, reset to the first step whenever something does. Pull only runs while a turn waits.

Functions

func Hops

func Hops(sessionID string) int

Hops is the hop count SetHops recorded for sessionID, 0 when none. An outgoing A2A call of that session sends Hops+1.

func HopsOf

func HopsOf(v any) int

HopsOf reads a HopsKey metadata value: a JSON number, an int, or a numeric string. Anything else is 0.

func IsTimeout

func IsTimeout(msg string) (time.Duration, bool)

IsTimeout reports whether msg is a turn's TimeoutMessage, and how long the turn waited.

func LateForward

func LateForward(handle, taskID, text string) string

LateForward is a timed-out task's reply, as handed to the agent that asked.

func PendingNotice

func PendingNotice(handle string, waited time.Duration) string

PendingNotice is what the agent that asked hears when the remote's turn timed out: not an empty answer, but that the reply will follow.

func Register

func Register(a Adapter)

Register adds an adapter kind; adapters call it from init. An adapter built against another Event schema panics at start rather than feed the runner events it would misread.

func SetHops

func SetHops(sessionID string, n int)

SetHops records the hop count of the request now running in sessionID; 0 (a turn that did not come over A2A) forgets it.

func TimeoutMessage

func TimeoutMessage(max time.Duration) string

TimeoutMessage is the error of a turn that ran past max.

func UserText

func UserText(b []byte) string

UserText pulls the text out of a stream-json user envelope; anything else is taken as raw text.

Types

type Adapter

type Adapter struct {
	Kind  string `json:"kind"`
	Label string `json:"label"`
	// Listen is the kind's listen modes, preferred first (plan 6.2c
	// "Cara listen per kanal").
	Listen []ListenMode `json:"listen"`
	// Schema is the Event schema version the adapter emits; it must be
	// SchemaVersion (see event.go).
	Schema int `json:"schema"`
}

Adapter describes one source kind in the registry.

func Adapters

func Adapters() []Adapter

Adapters lists the registered kinds, sorted.

func Lookup

func Lookup(kind string) (Adapter, bool)

Lookup returns the adapter of kind.

type Description

type Description struct {
	Name    string `json:"name"`
	Detail  string `json:"detail,omitempty"`
	Target  string `json:"target,omitempty"`
	Kind    string `json:"kind"`
	Warning string `json:"warning,omitempty"`
}

Description is what Describe shows before an agent is added.

type Event

type Event struct {
	Kind   EventKind `json:"kind"`
	Text   string    `json:"text,omitempty"`
	Status string    `json:"status,omitempty"`
	Detail string    `json:"detail,omitempty"`
	Name   string    `json:"name,omitempty"`
	URL    string    `json:"url,omitempty"`
	MIME   string    `json:"mime,omitempty"`
	Note   string    `json:"note,omitempty"`
}

Event is one thing a remote did during a turn, the same shape for every adapter, so chat, mention, schedule and the Slack bridge never learn where the agent lives.

func (Event) Terminal

func (e Event) Terminal() bool

Terminal reports whether e ends the turn.

type EventKind

type EventKind string

EventKind names what an Event carries.

const (
	// EventTextDelta appends Text to the reply.
	EventTextDelta EventKind = "text_delta"
	// EventText is the reply so far in full; the runner shows only the
	// part not shown yet.
	EventText EventKind = "text"
	// EventDraft is the reply so far in full, not shown yet: the remote
	// may still rewrite it, so the runner keeps it as the turn's result
	// and shows it when the turn ends. Added within v1: a runner that
	// does not know it only shows the reply later.
	EventDraft EventKind = "draft"
	// EventStatus reports what the remote is doing: Status is one of the
	// Status* values, Detail a short label ("Bash: ls").
	EventStatus EventKind = "status"
	// EventAttachment is a file the remote sent: Name, URL, MIME.
	EventAttachment EventKind = "attachment"
	// EventDone ends the turn. Text, when set, is the whole reply; Note
	// labels how it ended ("ended without marker").
	EventDone EventKind = "done"
	// EventError ends the turn as failed; Text is the message.
	EventError EventKind = "error"
)

type Handle

type Handle struct {
	ID     string
	Cursor string
}

Handle identifies a sent turn: what a reply is matched by (task id, thread_ts) and, for pull, the cursor of what was already read.

type Injector

type Injector interface {
	Inject(ctx context.Context, h Handle, turn Turn) error
}

Injector is a Source whose remote takes a message while a turn still runs. Inject is called for a message that arrives while h's turn is running: the remote gets it at once and its answer flows on h's stream, in the same turn. ErrInjectUnsupported (or any error) makes the runner queue the message as the next turn instead, as for a source without it.

type Limits

type Limits struct {
	Max  time.Duration
	Idle time.Duration
	Poll time.Duration
	// Ceiling > Max lets Max move on while the remote still shows life
	// (new text, an edit, a working status), up to Ceiling in all.
	Ceiling time.Duration
	// BusyFresh > 0 trusts a standing working status to move Max on only
	// while the remote said something within that long, so a remote that
	// hung after saying "working" ends at Max instead of at Ceiling. 0
	// trusts the status until it changes.
	BusyFresh time.Duration
	// Grace > 0 keeps listening that long after a turn ended, for a
	// message or an edit the remote sends late (a Reopener only).
	Grace time.Duration
}

Limits bound a turn. Max is the hard limit (a turn still running then fails); Idle > 0 ends a turn that has shown text and then went quiet for that long, labelled NoteNoMarker — never while the remote still shows it is working. Poll > 0 caps the wait between two pulls.

TODO: learn per remote (marker use, typical answer time) and adapt Idle.

type ListenMode

type ListenMode string

ListenMode is one way a source can hear its replies.

const (
	// ListenPush: the source delivers events (stream, socket, callback).
	ListenPush ListenMode = "push"
	// ListenPull: the runner asks with Fetch, backing off 1→2→5→10 s.
	ListenPull ListenMode = "pull"
)

type Puller

type Puller interface {
	Fetch(ctx context.Context, h Handle) ([]Event, Handle, error)
}

Puller returns the events since h.Cursor and the handle with the cursor moved past them.

type Pusher

type Pusher interface {
	Receive(ctx context.Context, h Handle) (<-chan Event, error)
}

Pusher delivers h's events on a channel, closed when the source has no more to say. A terminal event ends the turn.

type Recheck

type Recheck struct {
	// Text is the remote's reply as it stands now.
	Text string `json:"text"`
	// Busy: the remote still shows it works (a progress note, a status);
	// Done: its end marker or a final status is there.
	Busy bool `json:"busy"`
	Done bool `json:"done"`
	// Label is its progress note, if any.
	Label string `json:"label,omitempty"`
}

Recheck is the result of reading a turn's reply again.

func (Recheck) Settled

func (r Recheck) Settled() bool

Settled reports whether r is a reply worth keeping: finished, or text the remote no longer works on.

type Rechecker

type Rechecker interface {
	Recheck(ctx context.Context, sessionDir string) (Recheck, error)
}

Rechecker is optionally implemented by a Source: it reads the reply to the session's last turn again — for a turn that timed out or ended without its marker — sending nothing to the remote. A Source without it offers no "Check again".

type Reopener

type Reopener interface {
	Reopen(h Handle)
}

Reopener is a Source that can keep following a finished turn's thread for late messages: Reopen lets the turn's tracker report again.

type Resumer

type Resumer interface {
	ResumeID(sessionDir string) string
}

Resumer names the session to the chat (the init line's session_id) from the adapter's saved state; without it a fresh id is made per spawn.

type RetryAfterError

type RetryAfterError struct {
	After time.Duration
	Err   error
}

RetryAfterError asks the runner to wait After before the next Fetch — a rate limit's Retry-After.

func (*RetryAfterError) Error

func (e *RetryAfterError) Error() string

func (*RetryAfterError) Unwrap

func (e *RetryAfterError) Unwrap() error

type Source

type Source interface {
	// Kind is the adapter key ("a2a", "slack").
	Kind() string
	// Label names the remote for process listings ("a2a-remote (host)").
	Label() string
	// Listen lists the supported ways to hear replies, preferred first.
	Listen() []ListenMode
	Limits() Limits
	// Send delivers turn and returns the handle its reply is matched by.
	Send(ctx context.Context, turn Turn) (Handle, error)
	// Cancel asks the remote to stop h's turn, where it can.
	Cancel(ctx context.Context, h Handle) error
	// End releases what Send set up for h (router entries, timers). It is
	// called once after every turn, however it ended.
	End(h Handle)
	Describe(ctx context.Context) (Description, error)
	Test(ctx context.Context) TestResult
}

Source is one remote agent's adapter. Every source also implements Pusher, Puller or both, in the order Listen names.

type Spawner

type Spawner struct{ Source Source }

Spawner is a provider.Spawner with no process: Spawn returns a Process whose turns go to Source.

func (Spawner) Spawn

Spawn starts the turn loop.

type TestResult

type TestResult struct {
	OK        bool   `json:"ok"`
	State     string `json:"state"`
	LatencyMS int64  `json:"latency_ms"`
	Reply     string `json:"reply,omitempty"`
	Error     string `json:"error,omitempty"`
}

TestResult is a ping of the remote.

type TimeoutHinter

type TimeoutHinter interface {
	TimeoutHint() string
}

TimeoutHinter is a Source that can say why a turn may have gone unanswered ("this bot answers only when @mentioned"). "" = no hint.

type Turn

type Turn struct {
	Text string
	// SessionDir is where the adapter keeps the session's state
	// (A2A contextId, Slack thread_ts, …).
	SessionDir string
	// SessionID is the wick session the turn runs in (see Hops).
	SessionID string
}

Turn is one user message sent to the remote.

Directories

Path Synopsis
Package pluginremote is the remote.Source of a service plugin that declares remote_source: Send / Receive / Done go to the plugin's internal /_wick/remote/* paths over its unix socket, and events arrive as SSE in the v1 event schema, so nothing is converted.
Package pluginremote is the remote.Source of a service plugin that declares remote_source: Send / Receive / Done go to the plugin's internal /_wick/remote/* paths over its unix socket, and events arrive as SSE in the v1 event schema, so nothing is converted.
Package slackremote is the Slack adapter of remote.Source: an agent that lives in Slack (a third-party AI bot, an internal bot, a person) wrapped as a Team agent.
Package slackremote is the Slack adapter of remote.Source: an agent that lives in Slack (a third-party AI bot, an internal bot, a person) wrapped as a Team agent.

Jump to

Keyboard shortcuts

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