Documentation
¶
Overview ¶
Package remoteapi is aimux's API for clients on other devices (a phone, another laptop): list sessions, follow them, and continue idle ones. It is meant to sit behind `tailscale serve`, which proves who the caller is.
Index ¶
- Constants
- Variables
- func LoginFrom(ctx context.Context) string
- func RequireTailnetUser(allowed, trustedHosts []string, next http.Handler) http.Handler
- type API
- type ApprovalData
- type ApprovalNotice
- type ApprovalResolvedData
- type Broker
- func (b *Broker) Answer(approvalID, option string) error
- func (b *Broker) Approver() acprun.Approver
- func (b *Broker) AwaitingApproval(session string) bool
- func (b *Broker) Busy(session string) bool
- func (b *Broker) Cancel(session string) error
- func (b *Broker) Events(session string, after int64) []Event
- func (b *Broker) Hold(session string) (release func(), err error)
- func (b *Broker) LogID() string
- func (b *Broker) Publish(session, kind string, data any)
- func (b *Broker) Start(session, text, key string) (string, error)
- func (b *Broker) Subscribe(session string, after int64) (<-chan Event, func())
- func (b *Broker) TurnEnded(session, turn string) (ended, failed bool)
- type BrokerDeps
- type BrokerOptions
- type CreatedSession
- type CreatedStore
- type DescribeResult
- type ErrorBody
- type Event
- type EventPage
- type Handoff
- type Health
- type LastOnMac
- type Links
- type LocalIndex
- func (x *LocalIndex) Catalog() *catalog.Catalog
- func (x *LocalIndex) Lookup(id string) (history.Session, bool)
- func (x *LocalIndex) Projects(ctx context.Context) ([]Project, error)
- func (x *LocalIndex) Record(_ context.Context, id string) (history.Session, error)
- func (x *LocalIndex) RegistryStatus(sessionID string) string
- func (x *LocalIndex) Search(ctx context.Context, query string, limit int) ([]SearchHit, error)
- func (x *LocalIndex) Session(ctx context.Context, id string, turns int) (SessionDetail, error)
- func (x *LocalIndex) SessionExists(_ context.Context, id string) error
- func (x *LocalIndex) Sessions(ctx context.Context, limit int, includeAutomated bool) ([]Session, error)
- func (x *LocalIndex) SessionsAt(_ context.Context, limit int, includeAutomated bool, ...) ([]Session, error)
- func (x *LocalIndex) TerminalPID(sessionID string) (int, bool)
- func (x *LocalIndex) TerminalPIDs() map[string]int
- func (x *LocalIndex) Title(ctx context.Context, id string) (string, error)
- type MetaResult
- type Naming
- type NamingHealth
- type OpenOnMacResult
- type Project
- type ProjectList
- type Provider
- type QueueACP
- type QueueInput
- type QueueItem
- type QueueStatus
- type QueueTerminal
- func (q QueueTerminal) LeftInBox(session string) bool
- func (q QueueTerminal) Open(session string) (string, bool)
- func (q QueueTerminal) Send(ctx context.Context, session, text, key string) error
- func (q QueueTerminal) Status(ctx context.Context, session, registryStatus string) terminput.Status
- func (q QueueTerminal) Submit(ctx context.Context, session, text string) error
- func (q QueueTerminal) Turns(ctx context.Context, session string) ([]chatqueue.Turn, error)
- type Repo
- type SearchHit
- type SearchResults
- type Session
- type SessionDetail
- type SessionList
- type SessionStats
- type Status
- type StatusCache
- type Store
- type TerminalInput
- type TerminalOption
- type TerminalPrompt
- type TerminalStatus
- type TerminalStatusReader
- type ToolDetail
- type Turn
- type TurnAccepted
- type TurnDoneData
- type TurnErrorData
- type TurnStartedData
- type TurnTool
Constants ¶
const ( StateIdle = catalog.StateIdle // can be continued from here StateOpenInTerminal = catalog.StateOpenInTerminal // follow only StateBusy = catalog.StateBusy // aimux is running a turn // agent wrote the session, so there is nothing to continue. StateUnavailable = catalog.StateUnavailable )
Session states as clients see them: the catalog's.
const ( KindTurnStarted = "turn_started" // {"text"} KindTurnDone = "turn_done" // {"stopReason"} KindTurnError = "turn_error" // {"error"} KindApproval = "approval" // {"approvalId","title","options"} KindApprovalResolved = "approval_resolved" // {"approvalId","outcome": allowed|denied|expired} // KindQueue: the session's chat queue changed; data is QueueStatus and // turn is "". Only clients that ask (events?queue=1) see it. KindQueue = "queue" )
Event kinds beyond acprun.KindUpdate, which the broker passes through.
const ( CapSessions = "sessions" // list, detail, send, events, cancel, approvals CapSearch = "search" // GET /v1/search CapNewSessions = "new_sessions" // GET /v1/projects, POST /v1/sessions CapPush = "push" // POST /v1/devices, DELETE /v1/devices/{token}: approval notifications over APNs // CapTerminalInput: POST /v1/sessions/{id}/terminal/messages and // /terminal/keys type into sessions open in a terminal on the Mac. CapTerminalInput = "terminal_input" // CapDeviceLogin: every route but health, the contract, /app and // /v1/auth/{pair,challenge,login} needs a paired device's session. CapDeviceLogin = "device_login" // CapQueue: /v1/sessions/{id}/queue holds messages the Mac sends one // turn at a time; SessionDetail.Queue and queue events (events?queue=1). CapQueue = "queue" // CapDescribe: PATCH /v1/sessions/{id}/meta (title, description, pin) // and POST /v1/sessions/{id}/describe ("Update summary"); Health.Naming. CapDescribe = "describe" // CapSendNow: `now` on terminal messages and POST // /v1/sessions/{id}/queue/{item}/send-now (Send now, mid-turn); offered // with terminal input. CapSendNow = "send_now" )
Capabilities a server may report in Health; clients use them instead of probing endpoints.
const ( OutcomeAllowed = "allowed" OutcomeDenied = "denied" OutcomeExpired = "expired" )
Approval outcomes in ApprovalResolvedData.
Variables ¶
var ( ErrNoSuchApproval = errors.New("no pending approval with that id") ErrInvalidOption = errors.New("that option was not offered for this approval") )
Broker errors.
var ( // ErrNotStarted: the session has no transcript yet, so there is nothing // to resume in a terminal (409 not_started). ErrNotStarted = errors.New("the session has no messages yet") // ErrHandoffTimeout: the tab opened but the session did not show as // open in a terminal within Handoff.Wait (504 timeout). ErrHandoffTimeout = errors.New("the terminal did not pick up the session in time") // ErrNoTerminal: this server cannot open a terminal tab (503 no_terminal). ErrNoTerminal = errors.New("no terminal app to open the session in") // ErrNotAuthorized: macOS refused aimux control of the terminal app // (403 not_authorized). Handoff.Open returns it (wrapped or not). ErrNotAuthorized = errors.New("aimux may not control the terminal app") )
Refusals of Open on Mac, mapped to codes by writeFailure.
Functions ¶
func RequireTailnetUser ¶
RequireTailnetUser admits only requests that `tailscale serve` forwarded for an allowlisted user:
- the Host is one of trustedHosts, this machine's tailnet names, which tailscale serve passes through. A DNS-rebinding page reaches loopback with its own Host (and may set any header), so loopback alone is not proof of proxying. An empty list admits nobody;
- the connection comes from loopback, where tailscale serve connects from (the listener must also bind to loopback only);
- Tailscale-User-Login, which tailscale serve sets and strips from client input, names a login in allowed (an empty list admits nobody);
- no web page but aimux's own: a request with an Origin must come from the very origin it is sent to (a browser client at /app, served from here), and a browser's Sec-Fetch-Site, when sent, must be same-origin or none (typed into the address bar). Cross-site pages, including a plain <img> or <script> GET that carries no Origin, are refused.
Types ¶
type API ¶
type API struct {
Version string // reported by /v1/health
Broker *Broker
Sessions func(ctx context.Context, limit int, includeAutomated bool) ([]Session, error)
Session func(ctx context.Context, id string, turns int) (SessionDetail, error)
// SessionsAt, if set with States, serves the list instead of Sessions,
// given the state service's open-sessions read (LocalIndex.SessionsAt),
// so `state`, `working` and `activity` come from one read.
SessionsAt func(ctx context.Context, limit int, includeAutomated bool, open map[string]harness.Holder) ([]Session, error)
// SessionExists, if set, is the queue routes' check that a session is
// known, without reading its detail; nil falls back to Session.
SessionExists func(ctx context.Context, id string) error
Search func(ctx context.Context, query string, limit int) ([]SearchHit, error)
// Projects lists the folders a new session may start in; Create starts
// one there and returns its id.
Projects func(ctx context.Context) ([]Project, error)
Create func(ctx context.Context, cwd, text string) (string, error)
// Places, if set, gives the iTerm2 pane of each open session by id, and
// Folder the named folder of a session's project path; both fill the
// session list only. Nil leaves the fields absent.
Places func(ctx context.Context) map[string]terminput.MacPlace
Folder func(path string) folders.Folder
// Client, if set, is a browser client served at /app/ behind the same
// identity check as /v1. It is any handler; the server knows nothing
// else about it.
Client http.Handler
// RegisterDevice and UnregisterDevice, if set, let a native app sign a
// phone up for approval notifications (APNs) and off again.
RegisterDevice func(push.Device) error
UnregisterDevice func(token string) error
// TerminalInput, with TerminalEnabled (remote_access.terminal_input.enabled),
// serves /terminal/messages and /terminal/keys; otherwise both answer
// 403 disabled.
TerminalInput TerminalInput
TerminalEnabled bool
// Links, if it names a Jira base, is reported in /v1/health.
Links *Links
// TerminalTyped, if set, is told after a successful send or key press,
// so a cached terminal status of that session is dropped.
TerminalTyped func(sessionID string)
// Log, if set, receives details the server keeps from clients, such as
// a terminal driver's error text.
Log io.Writer
// DeviceLogin, if set (remote_access.device_login), serves /v1/auth,
// requires a paired device's session on every other route but the open
// ones, ends event streams with their session and audits each action.
// Nil keeps the tailnet check alone.
DeviceLogin *devicelogin.Server
// Queue, if set, serves /v1/sessions/{id}/queue. QueueKick (the
// dispatcher's Kick) is called after each change; QueueNote gives a
// session's waiting line. QueueSentNow (the dispatcher's NoteSentNow)
// is told the text of each Send now before it is typed, so its history
// turn is not taken for the owner's; the func it returns is called when
// the send fails. Any of them may be nil.
Queue *chatqueue.Store
QueueKick func()
QueueNote func(session string) string
QueueSentNow func(session, text string) (forget func())
// Record, if set, gives a session's history record (its file and
// metadata) and serves PATCH /v1/sessions/{id}/meta; with Naming it also
// serves POST /v1/sessions/{id}/describe.
Record func(ctx context.Context, id string) (history.Session, error)
// Naming, if set, makes titles and descriptions ("Update summary") and
// reports its state in health. With AutoName (sessions.auto_title) it is
// also told which sessions clients show, to name them automatically.
Naming Naming
AutoName bool
// LastOnMac, if set, is the session last in front on the Mac
// (terminput.LastFocus.Last).
LastOnMac func() (id string, at time.Time, ok bool)
// States, if set, is the session state service: it fills `activity`
// and `waiting` on the list and detail, and `working` on the list.
States *sessionstate.Service
// Handoff, if set, serves POST /v1/sessions/{id}/open-on-mac (health
// openOnMac); nil answers 503 no_terminal.
Handoff *Handoff
// contains filtered or unexported fields
}
API serves /v1. Sessions and Session read aimux's session index.
func (*API) Handler ¶
Handler returns the /v1 routes, admitting only allowed Tailscale logins arriving through tailscale serve for one of trustedHosts.
func (*API) PublishQueue ¶
PublishQueue publishes session's queue as a queue event: after a change, and when the dispatcher's waiting line changes.
func (*API) QueueEvents ¶
QueueEvents publishes a queue event on a session's log after each change to its queue, until ctx ends or the store closes. Run it once (the store's Changes has one reader).
type ApprovalData ¶
type ApprovalData struct {
ApprovalID string `json:"approvalId"`
Title string `json:"title"`
Options []acp.PermissionOption `json:"options"`
ToolCall acp.ToolCallUpdate `json:"toolCall"`
}
ApprovalData is the data of an approval event: answer it with one of Options' optionId at POST /v1/approvals/{approvalId}.
type ApprovalNotice ¶
type ApprovalNotice struct {
ApprovalID string
Session string
Title string // the tool call's title
Expires time.Time // denied after this unless answered
Outcome string // OnApprovalResolved only: allowed, denied or expired
}
ApprovalNotice describes a new permission request for a notification.
type ApprovalResolvedData ¶
type ApprovalResolvedData struct {
ApprovalID string `json:"approvalId"`
Outcome string `json:"outcome"`
}
ApprovalResolvedData is the data of an approval_resolved event.
type Broker ¶
type Broker struct {
// contains filtered or unexported fields
}
Broker runs turns in the background, keeps each session's event log, and holds permission requests until a client answers them.
func NewBroker ¶
func NewBroker(deps BrokerDeps, opt BrokerOptions) *Broker
NewBroker returns a Broker.
func (*Broker) Answer ¶
Answer resolves a pending approval with one of its option ids, or denies it when option is empty.
func (*Broker) Approver ¶
Approver is the acprun.Approver for runs started on the broker's behalf: it posts an approval event and waits for Answer, the timeout, or the end of the turn.
func (*Broker) AwaitingApproval ¶
AwaitingApproval reports whether one of the session's permission requests waits for an answer (sessionstate.ApprovalReader).
func (*Broker) Busy ¶
Busy reports whether the session has a running turn or is held. The session state service reads a held session (an Open on Mac handoff) as working in the background, on purpose.
func (*Broker) Cancel ¶
Cancel stops the session's running turn wherever it is: before the agent has the prompt, or during it. With no turn running it returns acprun.ErrNotRunning.
func (*Broker) Hold ¶
Hold keeps the session from starting a turn, for handoff between environments. It refuses with acprun.ErrBusy when a turn is running or another hold exists. While held, Busy returns true and Start returns ErrBusy. The release function is idempotent.
func (*Broker) LogID ¶
LogID names this broker's event log. Sequence numbers start over in a new log, so a cursor is only meaningful with the log it came from.
func (*Broker) Start ¶
Start begins a turn and returns its id. The same non-empty key returns the same turn, so a client may retry a send safely. It fails fast with acprun.ErrBusy while the session has a running turn or is held, or with Check's error.
type BrokerDeps ¶
type BrokerDeps struct {
Check func(session string) error
Send func(ctx context.Context, session, text string, onEvent func(acprun.Event)) (string, error)
Cancel func(session string) error
}
BrokerDeps is what the broker drives. Check rejects a session quickly (unknown, open in a terminal); Send runs one turn; Cancel stops it.
type BrokerOptions ¶
type BrokerOptions struct {
// ApprovalTimeout is how long a permission request waits for an answer
// before it is denied. Default 10 minutes.
ApprovalTimeout time.Duration
// OnApproval, if set, is told about each new permission request, in a
// goroutine of its own, so a person not watching can be notified.
OnApproval func(ApprovalNotice)
// OnApprovalResolved, if set, is told when one is answered, expires or
// its turn ends (Outcome set), so the notification can be taken back.
OnApprovalResolved func(ApprovalNotice)
// OnTurnEnd, if set, is told the session once a turn has ended (done or
// error) and the session can take the next one. It must not block.
OnTurnEnd func(session string)
}
BrokerOptions configures a Broker.
type CreatedSession ¶
type CreatedSession = catalog.CreatedSession
CreatedSession is a session started through the remote API (catalog.CreatedSession).
type CreatedStore ¶
type CreatedStore = catalog.CreatedStore
CreatedStore remembers the sessions aimux started (catalog.CreatedStore).
type DescribeResult ¶
type DescribeResult struct {
Title string `json:"title"`
Description string `json:"description,omitempty"`
Changed []string `json:"changed"`
Kept []string `json:"kept"`
}
DescribeResult answers POST /v1/sessions/{id}/describe: what clients now show, and which fields the model changed or left (owner-set, or nothing usable came back).
type Event ¶
type Event struct {
Seq int64 `json:"seq"`
Turn string `json:"turn"`
Kind string `json:"kind"`
Time time.Time `json:"time"`
Data json.RawMessage `json:"data"`
}
Event is one entry in a session's log, numbered per session so a client can reconnect and ask for everything after the last number it saw.
type EventPage ¶
EventPage is GET /v1/sessions/{id}/events?wait=0: the events after the cursor and the log they belong to (pass it back as ?log=).
type Handoff ¶
type Handoff struct {
// Hold keeps turns out of the session until release (Broker.Hold).
Hold func(session string) (release func(), err error)
// Drop closes the session's idle run (acprun.Manager.Drop).
Drop func(session string) error
// State is the session's catalog state: idle, busy, open_in_terminal.
State func(ctx context.Context, session string) (state string, err error)
// Target is the tab's title and the command resuming the session there;
// ErrNotStarted when the session has no transcript.
Target func(ctx context.Context, session string) (title string, argv []string, dir string, err error)
// Open opens the tab; ErrNotAuthorized when macOS refuses, ErrNoTerminal
// when there is no terminal app.
Open func(ctx context.Context, title string, argv []string, dir string) error
Wait time.Duration
Poll time.Duration
}
Handoff moves a session the Mac runs in the background (through ACP) into a new terminal tab: the run is closed and the harness resumes the session in the tab. Every func is required; Wait and Poll default to 20 s and 500 ms.
func (*Handoff) Run ¶
Run hands session to a terminal tab and returns once the terminal holds it. Steps, in order: refuse a session already open in a terminal or running a turn, build the command, hold the session, look again (a terminal may have taken it meanwhile), close its run, open the tab, then wait until the session shows as open in a terminal. The hold is released on every path; a closed run is not restarted after a failed open or a timeout (sending from the phone starts a new one).
Once the session is held, the handoff no longer follows ctx's cancellation: a client that goes away while the tab starts must not release the hold halfway. It still ends within the open deadline and Wait.
type Health ¶
type Health struct {
Status string `json:"status"`
Login string `json:"login"`
Version string `json:"version"`
// ACPProtocolVersion is the Agent Client Protocol version that `update`
// events follow: their data is an ACP SessionUpdate, passed through.
ACPProtocolVersion int `json:"acpProtocolVersion"`
Capabilities []string `json:"capabilities"`
// Links is present only when remote_access.links.jira_base is set.
Links *Links `json:"links,omitempty"`
// Session is present only with device login: "live" when the request
// carries a live session, else "none". Reading it never counts as use.
Session string `json:"session,omitempty"`
// Naming is present when the server makes titles and descriptions.
Naming *NamingHealth `json:"naming,omitempty"`
// OpenOnMac: POST /v1/sessions/{id}/open-on-mac can open a terminal tab.
OpenOnMac bool `json:"openOnMac"`
}
Health is GET /v1/health: who the caller is and what this server offers.
type LastOnMac ¶
LastOnMac is SessionList.LastOnMac: the session last in front on the Mac and when. Clients hide it after 12 hours.
type LocalIndex ¶
type LocalIndex struct {
// Providers are the harnesses listed, in order; a session belongs to
// the first whose store has its file.
Providers []Provider
// NewProvider is the Provider of sessions created here (Created
// records without a file yet): the harness acprun starts them with.
// "": the first provider's name.
NewProvider string
Broker *Broker
// Owned reports aimux's own adapter processes, which hold a session in
// a harness's registry without it being open in a terminal.
Owned func(pid int) bool
// Created is the sessions aimux started; they are listed although the
// agent SDK marks them automated. Nil: none.
Created *CreatedStore
// Running reports whether aimux has a run for a session: a created
// session without a file is usable only while it does.
Running func(id string) bool
// SearchIndex ranks sessions for a query (aimux's session search),
// among the given sessions only.
SearchIndex func(ctx context.Context, query string, limit int, ids []string) ([]search.Result, error)
// Terminal, if set, gives the detail of a session open in a terminal its
// terminal status (terminput.Service).
Terminal TerminalStatusReader
// Repo gives the web address and branch of the git repository in a
// folder (gitremote.Lookup). Nil: details carry no repo.
Repo func(dir string) (web, branch, root string, ok bool)
// contains filtered or unexported fields
}
LocalIndex answers the session list and detail from this machine's sessions of the registered providers: the HTTP- and contract-shaped layer over internal/catalog, which owns the listing, visibility, state and lookup cache. Every provider's sessions are listed; the default, NewProvider, is the one that can be continued today, since the router (SessionLookup) and the chat manager's Fingerprint serve one provider (catalog.Providers, which remote serve lists).
func (*LocalIndex) Catalog ¶
func (x *LocalIndex) Catalog() *catalog.Catalog
Catalog is the session catalog over the index's providers and live state, sharing the index's scan cache (Lookup). It reads the fields as they are at the call.
func (*LocalIndex) Lookup ¶
func (x *LocalIndex) Lookup(id string) (history.Session, bool)
Lookup is a session's history record from the latest scan, without scanning again (the namer's Lookup).
func (*LocalIndex) Projects ¶
func (x *LocalIndex) Projects(ctx context.Context) ([]Project, error)
Projects lists the folders of recent interactive sessions, most recent first: the only places a client may start a new session.
func (*LocalIndex) Record ¶
Record is a session's history record (its file and metadata), freshly scanned; acprun.ErrUnknownSession when the history has none.
func (*LocalIndex) RegistryStatus ¶
func (x *LocalIndex) RegistryStatus(sessionID string) string
RegistryStatus is the session's status in its harness's registry ("busy", "idle" or ""), "" when no terminal process holds it (terminput.RegistryStatuses).
func (*LocalIndex) Search ¶
Search ranks this machine's sessions for query. Like the list, it leaves out automated sessions (unless aimux created them) and sessions that are only in aimux's archive, which cannot be continued.
func (*LocalIndex) Session ¶
func (x *LocalIndex) Session(ctx context.Context, id string, turns int) (SessionDetail, error)
Session returns one session and its last turns.
func (*LocalIndex) SessionExists ¶
func (x *LocalIndex) SessionExists(_ context.Context, id string) error
SessionExists answers acprun.ErrUnknownSession for a session aimux does not know: neither a session file nor one created here. It reads no terminal, history or repository.
func (*LocalIndex) Sessions ¶
func (x *LocalIndex) Sessions(ctx context.Context, limit int, includeAutomated bool) ([]Session, error)
Sessions lists the most recently active sessions; automated ones only when includeAutomated is set.
func (*LocalIndex) SessionsAt ¶
func (x *LocalIndex) SessionsAt(_ context.Context, limit int, includeAutomated bool, open map[string]harness.Holder) ([]Session, error)
SessionsAt is Sessions with the open sessions given (catalog.ListWith): the remote list passes the state service's read, so each session's state and working match its activity.
func (*LocalIndex) TerminalPID ¶
func (x *LocalIndex) TerminalPID(sessionID string) (int, bool)
TerminalPID is the pid of the terminal process holding the session, by the same rule that makes a session open_in_terminal (terminput.Sessions).
func (*LocalIndex) TerminalPIDs ¶
func (x *LocalIndex) TerminalPIDs() map[string]int
TerminalPIDs maps every session open in a terminal to the pid holding it, by the rule TerminalPID uses.
type MetaResult ¶
type MetaResult struct {
Title string `json:"title"`
Description string `json:"description,omitempty"`
Pinned bool `json:"pinned"`
}
MetaResult answers PATCH /v1/sessions/{id}/meta: what clients now show.
type Naming ¶
type Naming interface {
// Want queues sessions a client shows; those that need a name get one.
Want(ids []string)
// UpdateSummary writes a new title and description now ("Update
// summary"); owner values stay.
UpdateSummary(ctx context.Context, s history.Session) (history.SummaryResult, error)
Status() history.NamingStatus
}
Naming makes session titles and descriptions (history.Namer).
type NamingHealth ¶
type NamingHealth struct {
Today int `json:"today"` // sessions named automatically today
Limit int `json:"limit"` // sessions.naming_daily_limit
Failing bool `json:"failing"` // the last calls failed
Reason string `json:"reason,omitempty"` // a fixed reason, while failing
Paused bool `json:"paused,omitempty"` // automatic naming waits after repeated failures
}
NamingHealth is Health.Naming: today's automatic naming and its state.
type OpenOnMacResult ¶
type OpenOnMacResult struct {
State string `json:"state"` // always open_in_terminal
}
OpenOnMacResult answers POST /v1/sessions/{id}/open-on-mac.
type Project ¶
type Project struct {
Path string `json:"path"`
Name string `json:"name"`
LastActive time.Time `json:"lastActive"`
}
Project is a folder recent sessions ran in.
type ProjectList ¶
type ProjectList struct {
Projects []Project `json:"projects"`
}
ProjectList is GET /v1/projects.
type QueueACP ¶
type QueueACP struct{ Broker *Broker }
QueueACP is the chat queue dispatcher's way into sessions started from the phone: the broker's own send path (the one POST …/messages uses).
type QueueInput ¶
type QueueInput interface {
Status(ctx context.Context, sessionID, registryStatus string) terminput.Status
Send(ctx context.Context, sessionID, text, idemKey string) error
Submit(ctx context.Context, sessionID, text string) error
LeftInBox(sessionID string) bool
}
QueueInput is what the dispatcher types with (terminput.Service).
type QueueItem ¶
type QueueItem struct {
ID string `json:"id"`
Text string `json:"text"`
State string `json:"state"` // waiting, sending, answering; done only in an add's answer
Created time.Time `json:"created"`
}
QueueItem is one queued message. Its idempotency key stays on the Mac.
type QueueStatus ¶
type QueueStatus struct {
State string `json:"state"` // running or paused
Reason string `json:"reason,omitempty"`
Note string `json:"note,omitempty"`
Items []QueueItem `json:"items"`
}
QueueStatus is a session's chat queue (GET /v1/sessions/{id}/queue, SessionDetail.Queue, and the data of a queue event). Reason is set while paused; Note is the dispatcher's waiting line while it runs.
type QueueTerminal ¶
type QueueTerminal struct {
Index *LocalIndex
Input QueueInput
}
QueueTerminal is the dispatcher's way into sessions open in a terminal: Claude's registry and the session history as GET /v1/sessions/{id} reads them, and the terminal input service the API types with.
func (QueueTerminal) LeftInBox ¶
func (q QueueTerminal) LeftInBox(session string) bool
LeftInBox reports whether the box holds a message a send left unsent, as of the latest screen read, without reading it again (terminput.Service.LeftInBox).
func (QueueTerminal) Open ¶
func (q QueueTerminal) Open(session string) (string, bool)
Open reports whether a terminal process holds session (the rule that makes it open_in_terminal) and its registry status.
func (QueueTerminal) Send ¶
func (q QueueTerminal) Send(ctx context.Context, session, text, key string) error
Send types text and presses Enter (terminput.Service.Send).
type Repo ¶
type Repo struct {
Web string `json:"web"` // https address, no ".git", no credentials
Branch string `json:"branch"` // checked out in the session's folder
// Root is the repository's top folder on the Mac; clients make absolute
// paths in a reply relative to it.
Root string `json:"root"`
}
Repo is SessionDetail.Repo: the session's git repository on the web, so clients can link commits, issues and files in a reply.
type SearchResults ¶
type SearchResults struct {
Results []SearchHit `json:"results"`
}
SearchResults is GET /v1/search.
type Session ¶
type Session struct {
ID string `json:"id"`
Provider string `json:"provider"`
Title string `json:"title"`
Project string `json:"project"`
LastActive time.Time `json:"lastActive"`
State string `json:"state"`
LastPrompt string `json:"lastPrompt,omitempty"` // the latest message the user sent
// Description is the shown description (history.ShownDescription): the
// owner's, else Claude Code's away summary, else aimux's.
Description string `json:"description,omitempty"`
Pinned bool `json:"pinned"` // the session's star
// Folder, Mac and Working are filled for the session list only.
Folder *folders.Folder `json:"folder,omitempty"` // where the session ran, named once per path
// Mac is set when the running claude is in an iTerm2 pane.
Mac *terminput.MacPlace `json:"mac,omitempty"`
// Working: the session is open in a terminal and Claude's registry calls it busy.
Working bool `json:"working,omitempty"`
// Waiting is set while a session open in a terminal shows a permission
// prompt, from the marker its Claude Code hook wrote (internal/waiting).
Waiting *waiting.Waiting `json:"waiting,omitempty"`
// Activity is what the session is doing now (sessionstate): working,
// needs_you, idle or gone. Set on the list and the detail.
Activity sessionstate.Activity `json:"activity,omitempty"`
}
Session is one entry in the session list. Automated sessions (started by a program, e.g. `claude -p`) are left out unless include_automated=1.
type SessionDetail ¶
type SessionDetail struct {
Session
Turns []Turn `json:"turns"`
// Stats is absent while the session is not in the index yet.
Stats *SessionStats `json:"stats,omitempty"`
// Terminal is set only for sessions open in a terminal on the Mac.
Terminal *TerminalStatus `json:"terminal,omitempty"`
// Repo is set only when the session's folder is a git repository on a
// known host (GitHub or GitLab).
Repo *Repo `json:"repo,omitempty"`
// Queue is set only when the session's chat queue holds items.
Queue *QueueStatus `json:"queue,omitempty"`
}
SessionDetail is a session plus its most recent turns.
type SessionList ¶
type SessionList struct {
Sessions []Session `json:"sessions"`
// LastOnMac is absent when unknown, or when that session is gone.
LastOnMac *LastOnMac `json:"lastOnMac,omitempty"`
}
SessionList is GET /v1/sessions.
type SessionStats ¶
type SessionStats struct {
CostUSD float64 `json:"costUsd"`
TokensIn int64 `json:"tokensIn"`
TokensOut int64 `json:"tokensOut"`
CacheReadTokens int64 `json:"cacheReadTokens"`
CacheWriteTokens int64 `json:"cacheWriteTokens"`
Turns int `json:"turns"`
StartTime *time.Time `json:"startTime,omitempty"` // nil when the index has none
DurationMin float64 `json:"durationMin"`
Model string `json:"model,omitempty"`
GitBranch string `json:"gitBranch,omitempty"`
}
SessionStats is what a session has cost and used so far, from the index.
type Status ¶
type Status struct {
Status string `json:"status"`
}
Status answers cancel and approval requests.
type StatusCache ¶
type StatusCache struct {
// contains filtered or unexported fields
}
StatusCache shares a terminal status between detail reads for ttl, so several polling clients do not repeat the ps, ioreg and Apple Event work. A read while one is computing waits for it. It is for the detail only: Send and Press read the screen fresh.
func NewStatusCache ¶
func NewStatusCache(inner TerminalStatusReader, ttl time.Duration) *StatusCache
NewStatusCache wraps inner, reusing each result for ttl.
func (*StatusCache) Invalidate ¶
func (c *StatusCache) Invalidate(sessionID string)
Invalidate drops every cached status of sessionID, after a send or key press changed its screen. A computation in flight still answers its own waiters; later reads compute afresh.
type TerminalInput ¶
type TerminalInput interface {
Send(ctx context.Context, sessionID, text, idemKey string) error
// SendReplacing clears the input box first (the owner asked to replace
// its text); terminput.ErrNotCleared when it would not empty.
SendReplacing(ctx context.Context, sessionID, text, idemKey string) error
// SendNow is Send allowed while Claude works on a turn (Send now): the
// harness takes the message during the turn; every other check stays.
SendNow(ctx context.Context, sessionID, text, idemKey string) error
Press(ctx context.Context, sessionID, promptID string, option terminput.Key, idemKey string) error
}
TerminalInput types into sessions open in a terminal on the Mac, after its own safety checks (terminput.Service).
type TerminalOption ¶
TerminalOption is one numbered choice; Key is what to press.
type TerminalPrompt ¶
type TerminalPrompt struct {
PromptID string `json:"promptId"`
Question string `json:"question"`
Detail string `json:"detail,omitempty"` // what is being approved, e.g. the command; monospace
Options []TerminalOption `json:"options"`
}
TerminalPrompt is a permission prompt read from the terminal's screen. PromptID stays the same while the same prompt shows; Detail is the prompt's body (the command, or the file and its preview).
type TerminalStatus ¶
type TerminalStatus struct {
Status string `json:"status"` // busy, idle or unknown, from Claude's registry
CanType bool `json:"canType"`
// Working: Claude Code is working on a turn; a message is refused with
// busy (CanType leaves it out), so clients offer the queue.
Working bool `json:"working"`
Reason string `json:"reason,omitempty"` // why CanType is false
Prompt *TerminalPrompt `json:"prompt,omitempty"`
// BoxHasText: the input box holds text (a draft, or Claude Code's grey
// suggestion); a message with replace: true clears it first.
BoxHasText bool `json:"boxHasText,omitempty"`
// WorkingSeconds: while working, how long Claude Code's working line says
// the turn has run; absent when it shows no time.
WorkingSeconds int `json:"workingSeconds,omitempty"`
}
TerminalStatus is SessionDetail.Terminal: what a session open in a terminal on the Mac is doing and whether the phone may type into it.
type TerminalStatusReader ¶
type TerminalStatusReader interface {
Status(ctx context.Context, sessionID, registryStatus string) terminput.Status
}
TerminalStatusReader reports a terminal session's status; registryStatus is the session's status in its harness's registry.
type ToolDetail ¶
type ToolDetail struct {
Input string `json:"input,omitempty"`
Error string `json:"error,omitempty"`
Old string `json:"old,omitempty"`
New string `json:"new,omitempty"`
}
ToolDetail is what a client shows when a step is opened: the full input, the error and, for an edit or a write, the changed text. Capped, see maxDetailInput and friends.
type Turn ¶
type Turn struct {
Number int `json:"number"`
Time time.Time `json:"time"`
User string `json:"user"`
Reply string `json:"reply"`
Tools []TurnTool `json:"tools"`
}
Turn is one exchange in a session's history: the user's message, the reply text, and the tools it used.
type TurnAccepted ¶
type TurnAccepted struct {
ID string `json:"id"`
Turn string `json:"turn"`
After int64 `json:"after"`
Events string `json:"events"`
}
TurnAccepted answers POST /v1/sessions and POST /v1/sessions/{id}/messages: the session, the new turn, and where to follow it (Events is the events URL with ?after= set just before the turn).
type TurnDoneData ¶
type TurnDoneData struct {
StopReason string `json:"stopReason"`
}
TurnDoneData is the data of a turn_done event; StopReason is ACP's (end_turn, cancelled, max_tokens, ...).
type TurnErrorData ¶
type TurnErrorData struct {
Error string `json:"error"`
}
TurnErrorData is the data of a turn_error event.
type TurnStartedData ¶
type TurnStartedData struct {
Text string `json:"text"`
}
TurnStartedData is the data of a turn_started event.
type TurnTool ¶
type TurnTool struct {
Name string `json:"name"`
Snippet string `json:"snippet,omitempty"`
OK bool `json:"ok"`
// Detail is the step's full text; omitted when there is none.
Detail *ToolDetail `json:"detail,omitempty"`
}
TurnTool is a tool call in a turn: its name, a short target (a path, a command) and whether it succeeded.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package chatqueue holds each session's queue of messages waiting to be sent from the phone, persisted on the Mac, and the rules for how an item moves from waiting to sent.
|
Package chatqueue holds each session's queue of messages waiting to be sent from the phone, persisted on the Mac, and the rules for how an item moves from waiting to sent. |
|
Package devicelogin keeps the devices paired with the remote API and the pending pairing code.
|
Package devicelogin keeps the devices paired with the remote API and the pending pairing code. |