api

package
v0.0.0-...-e35d089 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: MIT Imports: 28 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package api implements argus's client↔node protocol: newline-delimited JSON-RPC 2.0 over a stream connection. The same message types serve both the unix socket (local) and WebSocket+TLS (remote/gateway) transports.

Index

Constants

View Source
const (
	ActorOwner = "owner"
	ActorArgus = "argus"
)
View Source
const (
	MethodMessageList    = "message.list"    // request: no params; result: MessagesListResult
	MethodMessageSend    = "message.send"    // request: OwnerSendParams; result: OrchSendResult
	MethodMessageChanged = "message.changed" // notification: empty params; clients refetch message.list
)

Method names for the owner's message view. Message IDs are the node ID, ":m-", and 16 hex characters.

View Source
const (
	MethodOrchSessionCurrent     = "orch.session.current"     // request: CallerParams; result: session.Session
	MethodOrchSessionList        = "orch.session.list"        // request: OrchListParams; result: OrchListResult
	MethodOrchSessionGet         = "orch.session.get"         // request: OrchTargetParams; result: OrchGetResult
	MethodOrchSessionSpawn       = "orch.session.spawn"       // request: OrchSpawnParams; result: OrchSpawnResult
	MethodOrchMessageSend        = "orch.message.send"        // request: OrchSendParams; result: OrchSendResult
	MethodOrchMessageReply       = "orch.message.reply"       // request: OrchReplyParams; result: OrchSendResult
	MethodOrchInteractionRespond = "orch.interaction.respond" // request: OrchRespondParams; result: nil
	MethodOrchSessionOutput      = "orch.session.output"      // request: OrchTargetParams; result: OrchOutputResult
	MethodOrchSessionTranscript  = "orch.session.transcript"  // request: OrchTranscriptParams; result: OrchTranscriptResult
	MethodOrchSessionKill        = "orch.session.kill"        // request: OrchKillParams; result: OrchKillResult
	MethodOrchSessionRename      = "orch.session.rename"      // request: OrchRenameParams; result: SessionRenameResult
)

Method names for orch.* calls. Session IDs in their params and results are agent IDs.

View Source
const (
	MethodOrchPeerDeliver   = "orch.peer.deliver"    // request: OrchPeerDeliverParams; result: nil
	MethodOrchPeerWithdraw  = "orch.peer.withdraw"   // request: OrchPeerWithdrawParams; result: nil
	MethodOrchPeerLinkEnded = "orch.peer.link_ended" // request: OrchPeerLinkEndedParams; result: nil
	// request: OrchPeerParentEndedParams; result: nil
	MethodOrchPeerParentEnded = "orch.peer.parent_ended"
	// request: OrchPeerStateParams; result: nil. Needs cross_node_orch 2.
	MethodOrchPeerState = "orch.peer.state"
)

Methods one node pushes to another over its peer channel; a node accepts them only from a peer node, and only about that node's own actors. Each is idempotent, so a push retried after a lost reply is harmless.

View Source
const (
	DefaultKeepaliveInterval = 15 * time.Second
	DefaultKeepaliveTimeout  = 5 * time.Second
	DefaultKeepaliveFailures = 2
)

Link keepalive defaults, shared by every long-lived connection (node uplinks in both directions, client<->gateway) so all sides agree on how fast a half-open link is detected. Two failures ride out a transient blip.

View Source
const (
	MethodPing                  = "ping"                    // request: no params; result: nil (latency probe)
	MethodSessionsList          = "sessions.list"           // request: no params; result: []session.Session
	MethodSessionsRefresh       = "sessions.refresh"        // request: no params; rescans, result: []session.Session
	MethodSessionEvent          = "session.event"           // notification: registry.Event
	MethodSessionTranscriptView = "sessions.transcriptView" // request: TranscriptParams; result: transcript.TranscriptView
	MethodSessionToolDetail     = "sessions.toolDetail"     // request: ToolDetailParams; result: ToolDetail
	MethodSessionCapture        = "sessions.capture"        // request: SessionRef; result: CaptureResult
	MethodSessionInput          = "sessions.input"          // request: InputParams; result: nil
	MethodSessionKey            = "sessions.key"            // request: KeyParams; result: nil
	MethodSessionRespond        = "sessions.respond"        // request: RespondParams; result: nil
	MethodSessionSpawn          = "sessions.spawn"          // request: SpawnParams; result: SpawnResult
	MethodSessionResume         = "sessions.resume"         // request: ResumeParams; result: ResumeResult (reuses/adopts/launches a pane, waits until openable)
	// Probed live per call.
	MethodAgentsList             = "agents.list"              // request: AgentsListParams; result: AgentsListResult
	MethodAgentModelList         = "agent.model.list"         // request: AgentModelListParams; result: AgentModelListResult
	MethodSessionKill            = "sessions.kill"            // request: SessionRef; result: SessionKillResult (kills the tmux pane, or dismisses a paneless presence card)
	MethodSessionFocus           = "sessions.focus"           // request: SessionRef; result: nil (focus the session's tmux pane on its owning node)
	MethodSessionRename          = "session.rename"           // request: SessionRenameParams; result: SessionRenameResult
	MethodSessionPromptComplete  = "session.prompt.complete"  // request: PromptCompleteParams; result: PromptCompleteResult
	MethodSessionDescendantCount = "session.descendant.count" // request: SessionRef; result: DescendantCountResult
	// History (read-only, past sessions discovered on disk). Projects are aggregated
	// across nodes by the gateway; sessions/transcript are routed to the owning node.
	MethodSessionsHistoryProjects   = "sessions.historyProjects"   // request: no params; result: []session.HistoryProject
	MethodSessionsHistorySessions   = "sessions.historySessions"   // request: HistorySessionsParams; result: session.HistorySessionPage
	MethodSessionsHistoryTranscript = "sessions.historyTranscript" // request: HistoryTranscriptParams; result: transcript.TranscriptView
	MethodSessionHistoryToolDetail  = "sessions.historyToolDetail" // request: HistoryToolDetailParams; result: ToolDetail
	MethodNodeIdentify              = "node.identify"              // request: IdentifyParams (optional); result: IdentifyResult
	MethodServerInfo                = "server.info"                // request: no params; result: ServerInfo
	MethodServerCheckUpgrade        = "server.checkUpgrade"        // request: UpgradeParams; result: CheckUpgradeResult
	MethodServerUpgrade             = "server.upgrade"             // request: UpgradeParams; result: UpgradeResult (swaps the binary, no restart)
	MethodServerRestart             = "server.restart"             // request: ServerTargetParams; result: nil (execs the binary on disk after replying)
	MethodServerStop                = "server.stop"                // request: no params; result: nil (shuts down after replying)
	MethodNodesList                 = "nodes.list"                 // request: no params; result: NodesListResult
	MethodNodeEvent                 = "node.event"                 // notification: NodeEvent
	MethodTranscriptSubscribe       = "transcript.subscribe"       // request: TranscriptSubscribeParams; result: TranscriptDelta
	MethodTranscriptUnsubscribe     = "transcript.unsubscribe"     // request: TranscriptUnsubscribeParams; result: nil
	// Server→client push.
	MethodTranscriptDelta = "transcript.delta" // notification: TranscriptDelta
	MethodTerminalOpen    = "terminal.open"    // request: TerminalOpenParams; result: nil
	MethodTerminalOutput  = "terminal.output"  // notification: TerminalOutput
	MethodTerminalInput   = "terminal.input"   // request: TerminalInputParams; result: nil
	MethodTerminalResize  = "terminal.resize"  // request: TerminalResizeParams; result: nil
	MethodTerminalClose   = "terminal.close"   // request: TerminalCloseParams; result: nil
	MethodTerminalExited  = "terminal.exited"  // notification: TerminalExited (server→client, PTY ended)
	MethodTerminalList    = "terminal.list"    // request: no params; result: TerminalListResult (node-local)
	MethodTerminalCreate  = "terminal.create"  // request: TerminalCreateParams; result: Terminal
	MethodTerminalKill    = "terminal.kill"    // request: TerminalRef; result: nil
	MethodTerminalRename  = "terminal.rename"  // request: TerminalRenameParams; result: nil
	MethodTerminalChanged = "terminal.changed" // notification: TerminalChanged (server→client); refetch terminal.list
	// Client-token management (gateway only, admin/master-token connections).
	// MethodClientsPairStart mints a temporary token + public URL for a pairing QR.
	MethodClientsPairStart = "clients.pairStart" // request: no params; result: PairStartResult
	// MethodClientsPairAwait blocks until the minted token's device connects, or the deadline elapses.
	MethodClientsPairAwait = "clients.pairAwait" // request: PairAwaitParams; result: PairAwaitResult
	// MethodClientsList returns the persisted client tokens.
	MethodClientsList = "clients.list" // request: no params; result: []ClientTokenInfo
	// MethodClientsRemove revokes a client token by deleting its record.
	MethodClientsRemove = "clients.remove" // request: ClientRemoveParams; result: nil
	// MethodPushRegister records (or refreshes) a device's push target, keyed by
	// device_id (so re-registration replaces the prior endpoint).
	MethodPushRegister = "push.register" // request: PushRegisterParams; result: nil
	// MethodPushUnregister drops a device's push target (called on unpair).
	MethodPushUnregister = "push.unregister" // request: PushDeviceRef; result: nil
	// MethodPushTest sends a test notification through the real backend to verify delivery.
	MethodPushTest = "push.test" // request: PushDeviceRef; result: nil
	// MethodPushSetPause pauses or resumes broadcasts to a device without re-registering.
	MethodPushSetPause = "push.setPause" // request: PushSetPauseParams; result: nil
	// MethodPushVAPIDKey returns the gateway's VAPID public key for a device to
	// subscribe with. Empty Key means Web Push is unavailable.
	MethodPushVAPIDKey = "push.vapidKey" // request: no params; result: PushVAPIDKey
	// MethodPushDeliver is a node->gateway request carrying an opaque, pre-encrypted
	// Web Push body for the gateway to VAPID-sign and POST. The gateway never sees
	// cleartext notification content.
	MethodPushDeliver = "push.deliver" // node->gateway request: PushDeliverParams; result: PushDeliverResult
	// MethodPushPortSetToken stores the PushPort instance token on the gateway
	// (admin only) and applies it live.
	MethodPushPortSetToken = "pushport.setToken"     // admin request: PushPortSetTokenParams; result: nil
	MethodSessionExport    = "sessions.exportBundle" // request: ExportBundleParams; result: ExportBundleResult
	// Changed-files review for a live session's working directory (vs HEAD).
	MethodSessionChangedFiles = "sessions.changedFiles" // request: SessionRef; result: ChangedFilesResult
	MethodSessionFileDiff     = "sessions.fileDiff"     // request: FileDiffParams; result: FileDiffResult
	MethodSessionCommits      = "sessions.commits"      // request: SessionRef; result: CommitsResult
	MethodSessionCommitFiles  = "sessions.commitFiles"  // request: CommitFilesParams; result: ChangedFilesResult
	// relay.open pairs a client with a node into a chan_id E2E channel.
	MethodRelayOpen  = "relay.open"  // request: RelayOpenParams; result: RelayOpenResult
	MethodRelayClose = "relay.close" // request: RelayCloseParams; result: nil
	// relay.closed tells the node the gateway dropped a channel (client gone), so
	// the node can free what the channel holds.
	MethodRelayClosed = "relay.closed" // gateway->node notification: RelayCloseParams
	// relay.peer_opened tells a node that another node opened a channel to it,
	// sent before the channel's first relayed frame.
	MethodRelayPeerOpened = "relay.peer_opened" // gateway->node notification: RelayPeerOpenedParams
	// Trust-log distribution (locked mode). Cleartext, self-authenticating chain
	// bytes the blind gateway relays but cannot forge/roll back.
	MethodTrustLogSync = "trustlog.sync" // request: TrustLogSyncParams; result: TrustLogSyncResult (offer: known hashes; gateway set-subtracts diff)
	MethodTrustLogPush = "trustlog.push" // node->gateway request: TrustLogPushParams; result: nil (publish entries)
	// MethodTrustLogChanged is a gateway→node notification that a branch the gateway
	// did not previously hold has been offered. It is a hint with no authority: the
	// node's response is to pull and verify against its pinned genesis. It buys the
	// gateway strictly less than a timer tick does — the pull is rate-limited. A
	// forged or withheld notification changes only when the pull happens, never what
	// the node accepts or concludes.
	MethodTrustLogChanged = "trustlog.changed" // gateway->node notification: TrustLogChangedParams
	MethodSessionTasks    = "sessions.tasks"   // request: SessionRef; result: TasksResult
	MethodTasksChanged    = "tasks.changed"    // notification: TasksChanged (server→client)
	MethodProjectList     = "project.list"     // request: no params; result: ProjectListResult (node-local)
	// Read-only workspace RPCs. The client splits the composite workspace_id and
	// routes to the owning node.
	MethodWorkspaceChangedFiles = "workspace.changedFiles" // request: WorkspaceRef; result: ChangedFilesResult
	MethodWorkspaceDiff         = "workspace.diff"         // request: WorkspaceFileParams; result: WorkspaceDiffResult
	MethodWorkspaceListDir      = "workspace.listDir"      // request: WorkspaceFileParams; result: ListDirResult
	MethodWorkspaceReadFile     = "workspace.readFile"     // request: WorkspaceFileParams; result: ReadFileResult
	MethodWorkspaceCommits      = "workspace.commits"      // request: WorkspaceRef; result: CommitsResult (since the target merge base)
	MethodWorkspaceCommitFiles  = "workspace.commitFiles"  // request: WorkspaceCommitParams; result: ChangedFilesResult
	// Mutating workspace/project management (project_id-addressed except remove).
	MethodWorkspaceCreate  = "workspace.create"  // request: WorkspaceCreateParams; result: WorkspaceCreateResult
	MethodWorkspaceRemove  = "workspace.remove"  // request: WorkspaceRemoveParams; result: WorkspaceRemoveResult
	MethodProjectRename    = "project.rename"    // request: ProjectRenameParams; result: ProjectRenameResult
	MethodProjectSetHidden = "project.setHidden" // request: ProjectFlagParams; result: nil
	MethodProjectSetPinned = "project.setPinned" // request: ProjectFlagParams; result: nil
	MethodProjectForget    = "project.forget"    // request: ProjectRef; result: nil (drops the rows, keeps the files)
	// Create-picker reads and target changes.
	MethodProjectBranches    = "project.branches"    // request: ProjectRef; result: BranchesResult
	MethodProjectPRs         = "project.prs"         // request: ProjectRef; result: PRsResult
	MethodProjectIssues      = "project.issues"      // request: ProjectRef; result: IssuesResult
	MethodWorkspaceSetTarget = "workspace.setTarget" // request: WorkspaceSetTargetParams; result: WorkspaceSetTargetResult
	MethodWorkspaceRunSetup  = "workspace.runSetup"  // request: WorkspaceRef; result: ScriptRun
	MethodWorkspaceSetupLog  = "workspace.setupLog"  // request: WorkspaceRef; result: SetupLogResult
	MethodProjectChanged     = "project.changed"     // notification: empty params (server→client); refetch project.list
	MethodHostInfo           = "host.info"           // request: HostInfoParams; result: HostInfo
	MethodHostSetWakelock    = "host.setWakelock"    // request: HostSetWakelockParams; result: HostWakelock
	MethodHostCompleteDir    = "host.completeDir"    // request: HostCompleteDirParams; result: HostCompleteDirResult
	// Locked-mode control: local unix-socket only. remoteDispatch rejects every
	// lock.* method, so only the CLI (which dials the unix socket) can invoke these.
	MethodLockInit               = "lock.init"               // request: LockInitParams; result: LockInitResult
	MethodLockSign               = "lock.sign"               // request: LockDeviceParams; result: LockDeviceResult
	MethodLockRevoke             = "lock.revoke"             // request: LockDeviceParams; result: LockDeviceResult
	MethodLockAddSigner          = "lock.addSigner"          // request: LockSignerParams; result: LockDeviceResult
	MethodLockRemoveSigner       = "lock.removeSigner"       // request: LockSignerParams; result: LockDeviceResult
	MethodLockDisable            = "lock.disable"            // request: LockDisableParams; result: LockDisableResult
	MethodLockPin                = "lock.pin"                // request: LockPinParams; result: nil
	MethodLockUnpin              = "lock.unpin"              // request: no params; result: nil
	MethodLockLocalDisable       = "lock.localDisable"       // request: no params; result: nil
	MethodLockStatus             = "lock.status"             // request: no params; result: LockStatusResult
	MethodLockLog                = "lock.log"                // request: no params; result: LockLogResult
	MethodLockRevokeSignerStart  = "lock.revokeSignerStart"  // request: LockRevokeSignerStartParams; result: LockRevokeSignerBlobResult
	MethodLockRevokeSignerCosign = "lock.revokeSignerCosign" // request: LockRevokeSignerCosignParams; result: LockRevokeSignerBlobResult
	MethodLockRevokeSignerFinish = "lock.revokeSignerFinish" // request: LockRevokeSignerFinishParams; result: LockRevokeSignerFinishResult
)

Method names exchanged over the wire.

View Source
const (
	SourceNew    = "new"
	SourceBranch = "branch"
	SourcePR     = "pr"
	SourceIssue  = "issue"

	AgainstTarget = "target"
)
View Source
const (
	CodeParseError     = -32700
	CodeInvalidRequest = -32600
	CodeMethodNotFound = -32601
	CodeInvalidParams  = -32602
	CodeInternalError  = -32603
)

Standard JSON-RPC error codes used by argus.

View Source
const (
	// CodePushGone marks a push.test against a permanently dead target (404/410).
	// The gateway has already pruned it; the client should fetch a fresh endpoint
	// rather than re-register the dead one.
	CodePushGone = 410
	// CodeUnknownSession marks a call whose target session the node does not hold.
	CodeUnknownSession = 4404
	// CodeNotReady marks a call that came before the node finished its startup
	// discovery, so a missing target can still appear. The caller retries.
	CodeNotReady = 4503
	// CodePushRejected marks a node-to-node push that the receiver refuses
	// for good, for example a bad sender or a malformed message. The sender
	// drops it. Every other error reply is transient, and the sender retries.
	CodePushRejected = 4422
)

Application-defined error codes (outside the JSON-RPC reserved range).

View Source
const (
	// TermExitedProcess: the PTY ended on its own (process exited / mirror died).
	TermExitedProcess = "exited"
	// TermExitedEvicted: booted because the same session was opened elsewhere
	// (single-viewer enforcement; last opener wins).
	TermExitedEvicted = "evicted"
)

Reasons carried by TerminalExited.Reason.

View Source
const (
	NodeEventAdded        = "added"
	NodeEventOnline       = "online"
	NodeEventOffline      = "offline"
	NodeEventRemoved      = "removed"
	NodeEventTrustChanged = "trust-changed" // gateway→client: trust log changed; client should pull promptly
)

NodeEvent transitions on the roster stream (node.event).

View Source
const HostWakelockIndefinite = "9999-12-31T23:59:59Z"

HostWakelockIndefinite is the HostWakelock.Until value for "until turned off". It equals the push pause sentinel, so clients share one value.

View Source
const MaxFrameSize = 16 << 20

MaxFrameSize bounds a single frame's payload.

View Source
const MethodE2EHandshake = "e2e.handshake"

MethodE2EHandshake carries a Noise handshake message (msg1/msg2) as a relay frame Body over a channel, before any sealed app traffic.

Variables

View Source
var (
	// EncMode and DecMode are the CBOR modes for all frames. Decoding is
	// bounded since frames come from untrusted peers.
	EncMode cbor.EncMode
	DecMode cbor.DecMode
)

CBORMethods are the methods whose messages travel as CBOR frames once negotiated.

View Source
var ErrFrameTooLarge = errors.New("api: frame exceeds 16 MiB")
View Source
var ErrNoCaller = errors.New("not running inside an argus agent session")
View Source
var ErrNoTerminalControl = errors.New("session has no terminal control")

ErrNoTerminalControl is returned for pane-bound actions on a session argus cannot drive (paneless vscode/external). Clients gate the action's UI on it.

View Source
var ErrSessionBusy = errors.New("session is busy: send the prompt once its turn ends")

ErrSessionBusy is returned for a prompt to a session that takes one only when idle, while it works or waits on an answer.

View Source
var ErrShellNeedsPane = errors.New("bash mode (!) needs a tmux session")

ErrShellNeedsPane is returned for "!" bash mode input to a session without a tmux pane, for an agent that takes it only as typed keys.

View Source
var StartedAt = time.Now().UTC()

StartedAt is when this process started. An exec in place starts it again, so a client can tell that a restart completed.

View Source
var StopDelay = 200 * time.Millisecond

StopDelay lets the reply reach the client before the shutdown closes the connection.

Functions

func AcceptWS

func AcceptWS(w http.ResponseWriter, r *http.Request) (net.Conn, error)

AcceptWS upgrades an HTTP request to a WebSocket and adapts it to a net.Conn. Origin checking is disabled because access is gated by bearer token, not by browser origin.

func BearerToken

func BearerToken(r *http.Request) string

BearerToken extracts the auth token from an HTTP request: the Authorization "Bearer <token>" header, falling back to a "token" query parameter (browsers cannot set custom headers on a WebSocket handshake).

func CBORMarshal

func CBORMarshal(v any) ([]byte, error)

func CBORParams

func CBORParams[T any](ctx context.Context) (T, bool)

CBORParams returns the typed params WithCBORParams decoded for the request.

func CBORToJSON

func CBORToJSON(b []byte) (json.RawMessage, error)

CBORToJSON converts a CBOR value to JSON; byte strings become base64.

func CBORUnmarshal

func CBORUnmarshal(b []byte, v any) error

func ChannelPrologue

func ChannelPrologue(nodeID, chanID string) []byte

ChannelPrologue is the Noise prologue binding a channel to its node id and chan id. Client and node MUST derive it identically.

func ClearStaleSocket

func ClearStaleSocket(path string) error

ClearStaleSocket removes a leftover socket at path that no process answers. A live one is an error, so a second process never unlinks the socket of a running one.

func Decode

func Decode[T any](params json.RawMessage) (T, error)

Decode unmarshals JSON-RPC params into T, centralizing the decode-and-check boilerplate shared by node and gateway handlers. Empty params yield the zero value (handlers validate required fields themselves).

func DialWSConn

func DialWSConn(ctx context.Context, url, token string, httpClient *http.Client) (net.Conn, error)

DialWSConn connects over WebSocket and returns the raw net.Conn, for callers (e.g. ReconnectingClient) that manage their own Peer over it.

func HandleStop

func HandleStop(srv *Server, stop func())

HandleStop serves server.stop on srv. Serve it only on local sockets.

func HandshakeFromFrame

func HandshakeFromFrame(f RelayFrame) ([]byte, error)

func IsMethodNotFound

func IsMethodNotFound(err error) bool

func ListenOwnerOnly

func ListenOwnerOnly(path string, log *slog.Logger) (net.Listener, error)

ListenOwnerOnly listens on a unix socket at path that only its owner can use. The umask keeps the socket private from bind to chmod. It is process-wide, so a file made meanwhile is owner-only too. Some filesystems (bind mounts under colima) reject chmod on a socket, which then keeps the umask mode.

func ListenUnix

func ListenUnix(path string, log *slog.Logger) (net.Listener, error)

ListenUnix clears a stale socket at path, then listens owner-only there.

func LogAttr

func LogAttr(ctx context.Context, kv ...any)

LogAttr adds key/value pairs to the current request's rpc log line. No-op when ctx carries no collector (e.g. handler invoked outside the dispatch path).

func MarshalHandshakeFrame

func MarshalHandshakeFrame(chanID string, handshake []byte) ([]byte, error)

MarshalHandshakeFrame carries a raw Noise handshake message unsealed — there is no session yet.

func SocketAbsent

func SocketAbsent(err error) bool

SocketAbsent reports whether a dial error means that no process listens: a missing socket (ENOENT) or a stale one with no listener (ECONNREFUSED).

func SortTerminalsByNode

func SortTerminalsByNode(ts []Terminal)

SortTerminalsByNode orders terminals by node, keeping each node's own order.

func StartedAtRFC3339

func StartedAtRFC3339() string

func WithNotifier

func WithNotifier(ctx context.Context, n Notifier) context.Context

WithNotifier attaches the connection's Notifier to ctx so request handlers dispatched over that connection can push notifications back to the client.

func WithPrincipal

func WithPrincipal(ctx context.Context, p Principal) context.Context

WithPrincipal attaches the connection's authenticated Principal to ctx so handlers dispatched over that connection can enforce per-method authorization.

Types

type Actor

type Actor struct {
	Node string `json:"node"`
	Key  string `json:"key"`
}

Actor identifies a message sender or recipient: a node and an actor key.

type AgentInfo

type AgentInfo struct {
	ID        string `json:"id"`
	Name      string `json:"name"`
	Color     string `json:"color"`
	Spawnable bool   `json:"spawnable"`
}

type AgentModelListParams

type AgentModelListParams struct {
	NodeID string `json:"node_id,omitempty"` // gateway routing key; empty = sole node
	Agent  string `json:"agent"`
}

type AgentModelListResult

type AgentModelListResult struct {
	Models []ModelInfo `json:"models"`
}

AgentModelListResult lists the models the agent offers. Empty means the agent offers no model choice.

type AgentsListParams

type AgentsListParams struct {
	NodeID string `json:"node_id,omitempty"` // gateway routing key; empty = sole node
}

type AgentsListResult

type AgentsListResult struct {
	Agents []AgentInfo `json:"agents"`
}

AgentsListResult lists every agent the node knows, in priority order (first = default spawn target among the spawnable ones).

type BranchInfo

type BranchInfo struct {
	Name       string `json:"name"`
	Remote     bool   `json:"remote,omitempty"`
	Local      bool   `json:"local,omitempty"`
	CheckedOut bool   `json:"checked_out,omitempty"`
}

type BranchesResult

type BranchesResult struct {
	Branches []BranchInfo `json:"branches"`
}

type CBORNegotiator

type CBORNegotiator interface {
	SetRemoteCBOR(ok bool)
}

CBORNegotiator records whether the remote end of a connection accepts CBOR frames.

type CallerInfo

type CallerInfo struct {
	PID int               `json:"pid"`
	Env map[string]string `json:"env,omitempty"` // only the adapters' caller identity variables
	// Remote names a caller on another node; only that node's peer channel may send it.
	Remote *RemoteCaller `json:"remote,omitempty"`
}

CallerInfo identifies the process that issued an orch.* call.

type CallerParams

type CallerParams struct {
	Caller CallerInfo `json:"caller"`
}

type CaptureResult

type CaptureResult struct {
	Screen string `json:"screen"`
}

CaptureResult is the rendered screen of a session's tmux pane.

type ChangedFile

type ChangedFile struct {
	Path     string `json:"path"`                // current (working-tree) path
	OrigPath string `json:"orig_path,omitempty"` // rename source (HEAD-side), else ""
	Change   string `json:"change"`              // added|modified|deleted|renamed|untracked
	Staged   bool   `json:"staged"`              // index differs from HEAD
	Unstaged bool   `json:"unstaged,omitempty"`  // working tree differs from index
}

ChangedFile is one entry in a session working directory's git status.

type ChangedFilesResult

type ChangedFilesResult struct {
	Root  string        `json:"root,omitempty"` // repo top-level (for display)
	Files []ChangedFile `json:"files"`
}

ChangedFilesResult lists everything git status reports for the session's repo.

type Channel

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

Channel seals JSON-RPC payloads for one client<->node channel. The routing header travels in cleartext so a blind gateway can relay by chan_id; the inner params/result/error travel in the sealed, opaque Body.

func NewChannel

func NewChannel(id string, session *e2e.Session) *Channel

func NewPlainChannel

func NewPlainChannel(id string) *Channel

func (*Channel) ID

func (c *Channel) ID() string

func (*Channel) OpenParams

func (c *Channel) OpenParams(f RelayFrame) ([]byte, error)

OpenParams returns the inner params bytes, encoded in f.Enc.

func (*Channel) OpenResponse

func (c *Channel) OpenResponse(f RelayFrame) ([]byte, *RPCError, error)

OpenResponse returns the inner result bytes, encoded in f.Enc.

func (*Channel) SealNotificationFrame

func (c *Channel) SealNotificationFrame(enc Encoding, method string, route RouteHeader, params []byte) ([]byte, error)

SealNotificationFrame overwrites route.ChanID with this channel; the caller sets only SubID/TermID. params is already encoded in enc.

func (*Channel) SealRequestFrame

func (c *Channel) SealRequestFrame(enc Encoding, id *json.RawMessage, method, nodeID string, params []byte) ([]byte, error)

SealRequestFrame output is ready for Peer.SendRawFrame(enc, frame). params is already encoded in enc.

func (*Channel) SealResponseFrame

func (c *Channel) SealResponseFrame(enc Encoding, id *json.RawMessage, result []byte, rpcErr *RPCError) ([]byte, error)

SealResponseFrame output is ready for Peer.SendRawFrame(enc, frame). result is already encoded in enc.

type CheckUpgradeResult

type CheckUpgradeResult struct {
	Current string `json:"current"`
	Latest  string `json:"latest"`
	// Beta is true when the result includes prereleases.
	Beta bool `json:"beta,omitempty"`
}

type Cipher

type Cipher interface {
	Seal(plaintext []byte) ([]byte, error)
	Open(sealed []byte) ([]byte, error)
}

Cipher seals and opens channel payloads. Noise for E2EE; identity for plaintext.

type Client

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

Client is a JSON-RPC client over a stream connection. It is a thin consumer wrapper around a Peer that serves no inbound methods and surfaces notifications on a channel.

func Dial

func Dial(socket string) (*Client, error)

Dial connects to a unix socket node.

func DialWS

func DialWS(ctx context.Context, url, token string, httpClient *http.Client) (*Client, error)

DialWS connects to a gateway over WebSocket and returns a consumer Client. Non-empty token is sent as a Bearer header. httpClient may be nil (use a custom one for a TLS config or pinned cert).

func NewClient

func NewClient(conn net.Conn) *Client

NewClient wraps an established connection and starts its read loop.

func (*Client) Call

func (c *Client) Call(method string, params, out any) error

Call sends a request and unmarshals the result into out (which may be nil).

func (*Client) CallContext

func (c *Client) CallContext(ctx context.Context, method string, params, out any) error

CallContext is Call bounded by ctx: on cancel or deadline it abandons the request and closes the connection so the peer does not serve a stale response.

func (*Client) Close

func (c *Client) Close() error

Close terminates the connection.

func (*Client) Events

func (c *Client) Events() <-chan Notification

Events returns the channel of remote notifications. Closed when the connection ends.

func (*Client) Quarantined

func (c *Client) Quarantined() bool

Quarantined is always false: the plaintext client never enforces trust-log locking.

func (*Client) Reconnect

func (c *Client) Reconnect()

Reconnect is a no-op: a plain Client does not reconnect.

func (*Client) States

func (c *Client) States() <-chan bool

States satisfies the same client interface as ReconnectingClient. A plain Client never reconnects, so it returns a nil channel (which never fires).

type ClientRemoveParams

type ClientRemoveParams struct {
	Token string `json:"token"`
}

ClientRemoveParams identifies the client token to revoke.

type ClientTokenInfo

type ClientTokenInfo struct {
	Token     string `json:"token"`
	CreatedAt string `json:"created_at"`
}

ClientTokenInfo is one persisted client token in a clients.list result.

type Commit

type Commit struct {
	SHA     string `json:"sha"`
	Short   string `json:"short"`
	Subject string `json:"subject"`
	Author  string `json:"author"`
	UnixSec int64  `json:"unix_sec"` // authored time; client formats
}

Commit is one entry in a session's branch/unpushed commit log.

type CommitFilesParams

type CommitFilesParams struct {
	SessionID string `json:"session_id"`
	SHA       string `json:"sha"`
}

CommitFilesParams selects one commit in a session's repo.

type CommitsResult

type CommitsResult struct {
	Commits  []Commit `json:"commits"`
	Unpushed bool     `json:"unpushed,omitempty"`
}

CommitsResult carries the commit list. Unpushed is true when the scope is unpushed-vs-remote.

type DescendantCountResult

type DescendantCountResult struct {
	Count int `json:"count"`
}

DescendantCountResult is the number of live sessions that sessions.kill on the session also kills.

type DialAuthError

type DialAuthError struct {
	URL        string
	StatusCode int
	TokenSent  bool
	Err        error
}

DialAuthError reports that the gateway answered the WebSocket handshake with an auth status instead of upgrading. It is distinct from a transport failure: the gateway was reached, and it refused this caller's token.

func (*DialAuthError) Error

func (e *DialAuthError) Error() string

func (*DialAuthError) Unwrap

func (e *DialAuthError) Unwrap() error

type Dialer

type Dialer func(ctx context.Context) (net.Conn, error)

Dialer establishes a new connection. Called for the initial connect and every reconnect, so it must be safe to invoke repeatedly.

type DirEntry

type DirEntry struct {
	Name    string `json:"name"`
	Path    string `json:"path"`             // repo-relative slash path
	IsDir   bool   `json:"is_dir,omitempty"` // for a symlink: its target is a directory in the repo
	Symlink bool   `json:"symlink,omitempty"`
	Target  string `json:"target,omitempty"` // symlink only: the link text
}

type DispatchFunc

type DispatchFunc func(ctx context.Context, method string, params json.RawMessage) (any, error)

DispatchFunc handles an incoming request. params is the raw JSON params (may be nil); the returned value is marshaled as the result. ctx is cancelled when the peer's connection closes.

type Encoding

type Encoding uint8

Encoding identifies how a frame's payload is encoded on the wire.

const (
	EncodingJSON Encoding = iota // one JSON object per line
	EncodingCBOR                 // 0x00, u32 big-endian length, CBOR envelope
)

func EncodeParams

func EncodeParams(method string, params any, cborOK bool) (Encoding, []byte, error)

EncodeParams marshals params as CBOR for a CBOR method when cborOK, otherwise as JSON. A json.RawMessage is always sent as JSON; nil params encode to nil.

func (Encoding) Marshal

func (e Encoding) Marshal(v any) ([]byte, error)

Marshal encodes v in e.

func (Encoding) Unmarshal

func (e Encoding) Unmarshal(b []byte, v any) error

Unmarshal decodes b, encoded in e, into v.

type ExportBundleParams

type ExportBundleParams struct {
	NodeID         string          `json:"node_id,omitempty"` // gateway routing
	Agent          string          `json:"agent"`
	TranscriptPath string          `json:"transcript_path"`
	Metadata       bundle.Metadata `json:"metadata"`
}

ExportBundleParams selects a session to export. Metadata is supplied by the client (what it already displays) and written verbatim into the manifest.

type ExportBundleResult

type ExportBundleResult struct {
	Filename string `json:"filename"`
	Data     []byte `json:"data"`
}

ExportBundleResult carries the gzipped-tar bundle. Data marshals to base64.

type FileDiffParams

type FileDiffParams struct {
	SessionID string `json:"session_id"`
	Path      string `json:"path"`
	OrigPath  string `json:"orig_path,omitempty"` // rename source, so the old side resolves
	Rev       string `json:"rev,omitempty"`       // commit sha; empty = HEAD vs worktree
}

FileDiffParams selects one changed file in a session's working directory.

type FileDiffResult

type FileDiffResult struct {
	Path       string `json:"path"`
	OldContent string `json:"old_content,omitempty"`
	NewContent string `json:"new_content,omitempty"`
	NotShown   bool   `json:"not_shown,omitempty"`
}

FileDiffResult carries a changed file's HEAD (old) and working-tree (new) content. Either side is "" when absent; NotShown (both empty) marks binary or oversized files.

type FrameWriter

type FrameWriter interface {
	WriteFrame(enc Encoding, frame []byte) error
}

FrameWriter is optional on the transport: when present the Peer hands it each complete framed frame instead of writing to its buffered stream (e.g. one WebSocket message per frame).

type HandlerFunc

type HandlerFunc func(ctx context.Context, params json.RawMessage) (any, error)

HandlerFunc handles a single request. params is the raw JSON params (may be nil); the returned value is marshaled as the result.

type HistorySessionsParams

type HistorySessionsParams struct {
	NodeID     string `json:"node_id,omitempty"`
	ProjectDir string `json:"project_dir"` // cwd merge key (node-local) shared across agents
	Limit      int    `json:"limit,omitempty"`
	Offset     int    `json:"offset,omitempty"`
}

HistorySessionsParams: Limit <= 0 returns all from Offset.

type HistoryToolDetailParams

type HistoryToolDetailParams struct {
	NodeID         string `json:"node_id,omitempty"`
	Agent          string `json:"agent,omitempty"` // owning agent; selects the adapter
	TranscriptPath string `json:"transcript_path"`
	AgentID        string `json:"agent_id,omitempty"`
	ToolID         string `json:"tool_id"`
}

HistoryToolDetailParams is the history counterpart of ToolDetailParams, addressed by node-local path.

type HistoryTranscriptParams

type HistoryTranscriptParams struct {
	NodeID         string `json:"node_id,omitempty"`
	Agent          string `json:"agent,omitempty"` // owning agent; selects the adapter
	TranscriptPath string `json:"transcript_path"`
	AgentID        string `json:"agent_id,omitempty"`
}

HistoryTranscriptParams reads a past session's transcript by node-local path. AgentID selects a nested subagent trace.

type HookResult

type HookResult struct {
	Output string `json:"output,omitempty"`
}

HookResult is the node's reply to a hook.event call. Output is the hookSpecificOutput JSON `argus hook` prints to stdout (blocking PermissionRequest path).

type HostBattery

type HostBattery struct {
	Percent int    `json:"percent"`
	State   string `json:"state"` // charging | discharging | full | not_charging | unknown
}

type HostCompleteDirParams

type HostCompleteDirParams struct {
	NodeID string `json:"node_id,omitempty"`
	Path   string `json:"path"`
}

HostCompleteDirParams.Path may lead with "~" for the node user's home.

type HostCompleteDirResult

type HostCompleteDirResult struct {
	Home  string   `json:"home"`
	Paths []string `json:"paths"`
}

HostCompleteDirResult lists the subdirectories, sorted, in Path's parent that start with Path's last segment, each as Path's parent (as given) plus the name and a trailing slash. An empty Path lists Home. Home is the node user's home directory.

type HostInfo

type HostInfo struct {
	OS            string       `json:"os,omitempty"` // e.g. "macOS 26.0.1 (arm64)"
	UptimeSeconds int64        `json:"uptime_seconds"`
	Battery       *HostBattery `json:"battery,omitempty"` // nil when the host has no battery
	Wakelock      HostWakelock `json:"wakelock"`
}

HostInfo describes the machine a node runs on.

type HostInfoParams

type HostInfoParams struct {
	NodeID string `json:"node_id,omitempty"`
}

type HostSetWakelockParams

type HostSetWakelockParams struct {
	NodeID string `json:"node_id,omitempty"`
	Until  string `json:"until,omitempty"`
}

type HostWakelock

type HostWakelock struct {
	Until string `json:"until,omitempty"` // RFC3339; empty = off; HostWakelockIndefinite = until turned off
}

type IdentifyParams

type IdentifyParams struct {
	Capabilities *PeerCapabilities `json:"capabilities,omitempty"`
}

IdentifyParams is what a client sends to declare its capabilities. Capabilities is nil when absent, which leaves the recorded ones unchanged.

type IdentifyResult

type IdentifyResult struct {
	ID             string           `json:"id"`
	Label          string           `json:"label"`
	Version        string           `json:"version"` // node's binary version
	Capabilities   NodeCapabilities `json:"capabilities"`
	IdentityPubKey string           `json:"identity_pubkey,omitempty"` // base64 Curve25519 static public (E2E)
	SignerPubKey   string           `json:"signer_pubkey,omitempty"`   // base64 Ed25519 signer public (locked-mode trust log)
	Tip            []byte           `json:"tip,omitempty"`             // resolved trust-log tip (nil when locked mode is off)
	LockDisabled   bool             `json:"lock_disabled,omitempty"`   // see NodeDescriptor.LockDisabled
}

IdentifyResult announces a node's identity to the gateway. ID is the stable node id (composite-id prefix and routing key).

type InputParams

type InputParams struct {
	SessionID string `json:"session_id"`
	Text      string `json:"text"`
	Submit    bool   `json:"submit"`
	Prepare   bool   `json:"prepare"`
}

InputParams sends text to a session. Submit appends an Enter. Prepare first normalizes the pane for input (exit copy mode; leave vim mode in insert) — set for discrete composer sends, not live key streaming.

type IssueInfo

type IssueInfo struct {
	Number int    `json:"number"`
	Title  string `json:"title"`
	Author string `json:"author,omitempty"`
	URL    string `json:"url,omitempty"`
}

type IssuesResult

type IssuesResult struct {
	Issues    []IssueInfo `json:"issues"`
	Truncated bool        `json:"truncated,omitempty"` // the forge's list limit cut it off
}

type KeyParams

type KeyParams struct {
	SessionID string   `json:"session_id"`
	Keys      []string `json:"keys"`
}

KeyParams sends one or more named keys (e.g. "Escape", "C-c", "Enter").

type Link struct {
	Child   Actor  `json:"child"`
	Parent  Actor  `json:"parent"`
	TaskID  string `json:"task_id,omitempty"`
	EndedBy string `json:"ended_by,omitempty"` // "owner" | "parent" | "self" | "ancestor"
	// ParentEnded reports that a parent on another node ended. The child's node
	// learns it from an orch.peer.parent_ended push, and the parent's node sets
	// it on its mirror once that push is queued.
	ParentEnded bool `json:"parent_ended,omitempty"`
}

Link records that a child session was spawned by a parent.

type ListDirResult

type ListDirResult struct {
	Root    string     `json:"root,omitempty"`
	Path    string     `json:"path,omitempty"`
	Entries []DirEntry `json:"entries"`
}

ListDirResult lists one directory's children (git-ignored entries and .git hidden), directories first.

type LockDeviceParams

type LockDeviceParams struct {
	Device []byte `json:"device"`
}

LockDeviceParams identifies a device to authorize/revoke by its Curve25519 identity pubkey.

type LockDeviceResult

type LockDeviceResult struct {
	Tip     []byte `json:"tip"`
	Changed bool   `json:"changed"`
}

LockDeviceResult reports the trust-log tip after the sign/revoke. Changed is false when the device was already in the target state (idempotent no-op).

type LockDisableParams

type LockDisableParams struct {
	Secret []byte `json:"secret"`
}

LockDisableParams carries the raw disablement secret to consume.

type LockDisableResult

type LockDisableResult struct {
	Tip      []byte `json:"tip"`
	Disabled bool   `json:"disabled"`
}

LockDisableResult reports the trust-log tip and disabled flag after lock.disable.

type LockInitParams

type LockInitParams struct {
	Signers         [][]byte `json:"signers,omitempty"`
	Devices         [][]byte `json:"devices,omitempty"`
	GenDisablements int      `json:"gen_disablements,omitempty"`
}

LockInitParams enables locked mode. Signers lists Ed25519 signer pubkeys (this node's own key must be included explicitly). Devices lists Curve25519 identity pubkeys to authorize in the genesis.

type LockInitResult

type LockInitResult struct {
	Tip                []byte   `json:"tip"`
	SignerCount        int      `json:"signer_count"`
	DisablementSecrets [][]byte `json:"disablement_secrets,omitempty"`
}

LockInitResult reports the new genesis tip and the final signer count.

type LockLogEntry

type LockLogEntry struct {
	Index       int      `json:"index"`
	Kind        string   `json:"kind"`                   // genesis|add-signer|remove-signer|authorize-device|revoke-device|revoke-signer|disable
	Hash        []byte   `json:"hash,omitempty"`         // this entry's chain hash; entry 0's is the genesis
	Target      []byte   `json:"target,omitempty"`       // single-key entries: the target pubkey
	Signers     [][]byte `json:"signers,omitempty"`      // genesis: initial signer set
	Revoked     [][]byte `json:"revoked,omitempty"`      // revoke-signer: revoked signer pubkeys
	Replaces    [][]byte `json:"replaces,omitempty"`     // revoke-signer: replacement signer pubkeys
	CoSignCount int      `json:"cosign_count,omitempty"` // revoke-signer: number of co-signs
}

LockLogEntry summarises one entry in the trust-log chain, as returned by lock.log.

type LockLogResult

type LockLogResult struct {
	Entries []LockLogEntry `json:"entries"`
	Tip     []byte         `json:"tip,omitempty"`
	Signers [][]byte       `json:"signers,omitempty"` // current trusted signer set (for fingerprint computation)
}

LockLogResult is the reply to lock.log.

type LockPinParams

type LockPinParams struct {
	Genesis []byte `json:"genesis"`
}

LockPinParams pins a node to a trust-log genesis hash.

type LockRevokeSignerBlobResult

type LockRevokeSignerBlobResult struct {
	Blob []byte `json:"blob"`
}

type LockRevokeSignerCosignParams

type LockRevokeSignerCosignParams struct {
	Blob []byte `json:"blob"`
}

type LockRevokeSignerFinishParams

type LockRevokeSignerFinishParams struct {
	Blob []byte `json:"blob"`
}

type LockRevokeSignerFinishResult

type LockRevokeSignerFinishResult struct {
	Tip []byte `json:"tip"`
}

type LockRevokeSignerStartParams

type LockRevokeSignerStartParams struct {
	Revoked  [][]byte `json:"revoked"`
	Replaces [][]byte `json:"replaces,omitempty"`
	ForkFrom []byte   `json:"fork_from,omitempty"`
}

Revoked is the list of signer pubkeys to revoke (required, non-empty). Replaces is an optional list of replacement signer pubkeys added atomically. ForkFrom overrides the fork-point hash; nil = auto-select (parent of the revoked signer's earliest action, erasing it from the chain).

type LockSignerParams

type LockSignerParams struct {
	Signer []byte `json:"signer"`
}

LockSignerParams identifies a signer to add/remove by its Ed25519 pubkey.

type LockStatusResult

type LockStatusResult struct {
	Enabled     bool     `json:"enabled"`
	Tip         []byte   `json:"tip,omitempty"`
	Signers     [][]byte `json:"signers,omitempty"`
	DeviceCount int      `json:"device_count"`
	// Devices is the authorized set. A non-zero DeviceCount with no Devices means the
	// running daemon predates this field — upgraded binary, not yet restarted.
	Devices        [][]byte `json:"devices,omitempty"`
	Length         int      `json:"length,omitempty"`
	SignerTrusted  bool     `json:"signer_trusted"`
	Authorized     bool     `json:"authorized"`
	SignerPubKey   []byte   `json:"signer_pubkey,omitempty"`
	IdentityPubKey []byte   `json:"identity_pubkey,omitempty"`
	Disabled       bool     `json:"disabled,omitempty"`
	LocalDisabled  bool     `json:"local_disabled,omitempty"`
	Pinned         bool     `json:"pinned,omitempty"`
	PinGenesis     []byte   `json:"pin_genesis,omitempty"`  // this device's own pin
	SeenGenesis    []byte   `json:"seen_genesis,omitempty"` // genesis observed by a tripped quarantine gate
	PinSource      string   `json:"pin_source,omitempty"`   // "config" or "file"
	Quarantined    bool     `json:"quarantined,omitempty"`
}

LockStatusResult is the audit view of a node's locked state.

type Message

type Message struct {
	ID   string      `json:"id"`
	Kind MessageKind `json:"kind"`
	From Actor       `json:"from"`
	// FromLabel is a session sender's label, as known when the message was
	// created. The receiving node renders it for a sender on another node, which
	// it cannot look up.
	FromLabel string `json:"from_label,omitempty"`
	To        Actor  `json:"to"`
	Body      string `json:"body"`
	ReplyTo   string `json:"reply_to,omitempty"`
	// Child is the child session a notice is about.
	Child       *Actor               `json:"child,omitempty"`
	Interaction *session.Interaction `json:"interaction,omitempty"` // interaction messages
	State       MessageState         `json:"state"`
	// AnsweredBy is the actor that answered an interaction message.
	AnsweredBy *Actor    `json:"answered_by,omitempty"`
	CreatedAt  time.Time `json:"created_at"`
	UpdatedAt  time.Time `json:"updated_at"`
}

type MessageKind

type MessageKind string
const (
	MessageText             MessageKind = "text"
	MessageTask             MessageKind = "task"
	MessageReply            MessageKind = "reply"
	MessageInteraction      MessageKind = "interaction"
	MessageTurnEnded        MessageKind = "turn_ended"
	MessageInteractionEnded MessageKind = "interaction_ended"
)

type MessageState

type MessageState string
const (
	MessageQueued    MessageState = "queued"
	MessageDelivered MessageState = "delivered"
	MessageReplied   MessageState = "replied"
	MessageWithdrawn MessageState = "withdrawn"
	MessageFailed    MessageState = "failed"
)

type MessagesListResult

type MessagesListResult struct {
	Messages []Message `json:"messages"`
	Links    []Link    `json:"links"`
}

type ModelInfo

type ModelInfo struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

ModelInfo is one model an agent can spawn with. ID is opaque to clients: they show Name and send ID back unchanged in SpawnParams.Model.

type NodeCapabilities

type NodeCapabilities struct {
	// SpawnSession reports whether the node can spawn sessions (tmux present).
	SpawnSession bool `json:"spawn_session"`
	// Terminal reports whether the node can run persistent terminals (tmux present).
	Terminal bool `json:"terminal"`
	// HostWakelock reports whether the node can hold a wakelock (host.setWakelock).
	HostWakelock bool `json:"host_wakelock"`
	// CBOR reports whether the node accepts CBOR frames.
	CBOR bool `json:"cbor"`
	// CrossNodeOrch is the version of the node-to-node orch protocol the node
	// speaks; 0 means none. Version 2 adds orch.peer.state.
	CrossNodeOrch int `json:"cross_node_orch"`
	// contains filtered or unexported fields
}

NodeCapabilities describes what a node supports, so clients can gate features per node. Reported by node.identify and server.info.

func (NodeCapabilities) MarshalJSON

func (c NodeCapabilities) MarshalJSON() ([]byte, error)

func (*NodeCapabilities) UnmarshalJSON

func (c *NodeCapabilities) UnmarshalJSON(b []byte) error

type NodeDescriptor

type NodeDescriptor struct {
	ID             string           `json:"id"`
	Label          string           `json:"label"`
	Version        string           `json:"version"`
	Capabilities   NodeCapabilities `json:"capabilities"`
	IdentityPubKey string           `json:"identity_pubkey,omitempty"`
	// SignerPubKey is served by the untrusted gateway roster and is therefore
	// gateway-forgeable. Use it for discovery only (e.g. picking a signer to add).
	// Any trust or enforcement decision must read the signer key from the
	// authenticated node.identify reply, never from this roster copy.
	SignerPubKey string `json:"signer_pubkey,omitempty"`
	Online       bool   `json:"online"`
	// LockDisabled reports that the node turned off locked-mode enforcement for
	// itself (`argus lock local-disable`), so it accepts channels from any device.
	// Gateway-forgeable: a hint for which nodes to try, never a trust decision.
	LockDisabled bool `json:"lock_disabled,omitempty"`
}

NodeDescriptor is one node in the gateway's roster (nodes.list / node.event). It carries the node's Noise static public key so an E2E client can open a channel (Noise IK precondition), and the online flag the gateway derives from socket + grace state.

type NodeEvent

type NodeEvent struct {
	Type string         `json:"type"` // added | online | offline | removed | trust-changed
	Node NodeDescriptor `json:"node"`
}

NodeEvent is one roster change streamed to a client.

type NodeInfo

type NodeInfo struct {
	ID           string           `json:"id"`
	Label        string           `json:"label"`
	Version      string           `json:"version"` // node's binary version
	Capabilities NodeCapabilities `json:"capabilities"`
}

NodeInfo identifies a node connected to the gateway (the unit in server.info). ID is the routing key a client passes to sessions.spawn as node_id.

type NodesListResult

type NodesListResult struct {
	Nodes []NodeDescriptor `json:"nodes"`
}

type Notification

type Notification struct {
	Method string
	Params json.RawMessage
	Enc    Encoding
}

Notification is a remote-initiated message (no response expected). When Enc is CBOR, Params holds CBOR bytes.

func (Notification) Decode

func (n Notification) Decode(v any) error

Decode unmarshals Params into v by Enc. Empty params leave v untouched.

type Notifier

type Notifier interface {
	Notify(method string, params any) error
}

Notifier sends a server-initiated notification to one connected client.

func NotifierFrom

func NotifierFrom(ctx context.Context) (Notifier, bool)

NotifierFrom returns the connection's Notifier, if one was attached.

type OrchGetResult

type OrchGetResult struct {
	Session session.Session `json:"session"`
	Queued  []Message       `json:"queued"`
}

type OrchKillParams

type OrchKillParams struct {
	OrchTargetParams
	Ancestor bool `json:"ancestor,omitempty"`
}

OrchKillParams is a kill request. Ancestor is honored only from a peer node killing a child of a session it is killing: the child ends by "ancestor".

type OrchKillResult

type OrchKillResult struct {
	Killed    []string `json:"killed"`
	NotKilled []string `json:"not_killed,omitempty"`
}

OrchKillResult lists the agent IDs of the killed sessions: the target's live descendants, deepest first, then the target. NotKilled lists the descendants on other nodes that could not be reached or killed.

type OrchListParams

type OrchListParams struct {
	Caller CallerInfo `json:"caller"`
	// All asks for the sessions of every online node, not only this one.
	All bool `json:"all,omitempty"`
}

type OrchListResult

type OrchListResult struct {
	Sessions []session.Session `json:"sessions"`
	// Unreachable is the IDs of nodes whose sessions are missing from Sessions.
	Unreachable []string `json:"unreachable,omitempty"`
}

type OrchOutputResult

type OrchOutputResult struct {
	Text string `json:"text"`
}

type OrchPeerDeliverParams

type OrchPeerDeliverParams struct {
	Message Message `json:"message"`
}

OrchPeerDeliverParams carries a message the sending node created, with its ID and timestamps.

type OrchPeerLinkEndedParams

type OrchPeerLinkEndedParams struct {
	ChildKey string `json:"child_key"`
	EndedBy  string `json:"ended_by"`
}

OrchPeerLinkEndedParams records how a child on the sending node ended.

type OrchPeerParentEndedParams

type OrchPeerParentEndedParams struct {
	ParentKey string `json:"parent_key"`
}

OrchPeerParentEndedParams records that a parent on the sending node ended.

type OrchPeerStateParams

type OrchPeerStateParams struct {
	MessageID string       `json:"message_id"`
	State     MessageState `json:"state"`
}

OrchPeerStateParams moves the sending node's copy of a message to State: delivered, replied, or failed. The receiver created the message.

type OrchPeerWithdrawParams

type OrchPeerWithdrawParams struct {
	MessageID  string `json:"message_id"`
	Ended      string `json:"ended,omitempty"`
	AnsweredBy *Actor `json:"answered_by,omitempty"`
}

OrchPeerWithdrawParams withdraws an open message the sending node created. Ended is the interaction_ended message the receiver gives the recipient when it already delivered the message. AnsweredBy, when set, names the actor on the receiving node that answered the interaction: the receiver marks its copy answered by that actor and gives no interaction_ended message.

type OrchRenameParams

type OrchRenameParams struct {
	SessionID string `json:"session_id"`
	Name      string `json:"name"`
}

OrchRenameParams names any session; no caller is needed.

type OrchReplyParams

type OrchReplyParams struct {
	Caller    CallerInfo `json:"caller"`
	MessageID string     `json:"message_id"`
	Text      string     `json:"text"`
}

type OrchRespondParams

type OrchRespondParams struct {
	Caller    CallerInfo     `json:"caller"`
	MessageID string         `json:"message_id"`
	Behavior  string         `json:"behavior,omitempty"` // "allow" | "deny"
	Reason    string         `json:"reason,omitempty"`
	Answers   map[string]any `json:"answers,omitempty"` // question text → option label
}

type OrchSendParams

type OrchSendParams struct {
	Caller    CallerInfo `json:"caller"`
	SessionID string     `json:"session_id"`
	Text      string     `json:"text"`
	// RequestID makes a retry return the first message instead of sending again.
	RequestID string `json:"request_id,omitempty"`
}

type OrchSendResult

type OrchSendResult struct {
	MessageID string `json:"message_id"`
}

type OrchSpawnParams

type OrchSpawnParams struct {
	Caller CallerInfo `json:"caller"`
	Agent  string     `json:"agent"`
	Cwd    string     `json:"cwd"`
	Name   string     `json:"name,omitempty"`
	Model  string     `json:"model,omitempty"`
	Prompt string     `json:"prompt,omitempty"`
	// RequestID makes a retry return the first result instead of spawning again.
	RequestID string `json:"request_id,omitempty"`
	// Node is the ID or label of the node to spawn on; empty means this node.
	Node string `json:"node,omitempty"`
}

type OrchSpawnResult

type OrchSpawnResult struct {
	SessionID string `json:"session_id"`
	TaskID    string `json:"task_id,omitempty"`
}

type OrchTargetParams

type OrchTargetParams struct {
	Caller    CallerInfo `json:"caller"`
	SessionID string     `json:"session_id"`
}

type OrchTranscriptParams

type OrchTranscriptParams struct {
	Caller    CallerInfo `json:"caller"`
	SessionID string     `json:"session_id"`
	Last      int        `json:"last,omitempty"` // 0 = all entries
}

type OrchTranscriptResult

type OrchTranscriptResult struct {
	Entries []transcript.Entry `json:"entries"`
}

type OwnerSendParams

type OwnerSendParams struct {
	SessionID string `json:"session_id,omitempty"` // bare local id; required unless ReplyTo is set
	Text      string `json:"text"`
	ReplyTo   string `json:"reply_to,omitempty"`
}

type PRInfo

type PRInfo struct {
	Number     int    `json:"number"`
	Title      string `json:"title"`
	Author     string `json:"author,omitempty"`
	HeadBranch string `json:"head_branch"`
	BaseBranch string `json:"base_branch"`
	URL        string `json:"url,omitempty"`
}

type PRsResult

type PRsResult struct {
	PRs       []PRInfo `json:"prs"`
	Truncated bool     `json:"truncated,omitempty"` // the forge's list limit cut it off
}

type PairAwaitParams

type PairAwaitParams struct {
	Token string `json:"token"`
}

PairAwaitParams identifies the minted token to wait on.

type PairAwaitResult

type PairAwaitResult struct {
	Connected bool `json:"connected"`
}

PairAwaitResult reports whether a device connected with the token before the pairing window closed.

type PairStartResult

type PairStartResult struct {
	Token string `json:"token"`
	URL   string `json:"url"`
}

PairStartResult carries a freshly minted client token plus the gateway's public base URL for the pairing QR.

type Peer

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

Peer is one end of a symmetric JSON-RPC 2.0 connection: it both issues and serves requests/notifications over a single stream. The gateway↔node uplink uses a Peer directly so both sides can call each other.

func DialWSPeer

func DialWSPeer(ctx context.Context, url, token string, httpClient *http.Client, opts PeerOptions) (*Peer, error)

DialWSPeer connects over WebSocket and returns a symmetric Peer. The node uplink uses this so it can both push events up and serve control requests coming back down the same connection.

func NewPeer

func NewPeer(rwc io.ReadWriteCloser, opts PeerOptions) *Peer

NewPeer wraps an established connection and starts its read loop.

func (*Peer) Call

func (p *Peer) Call(method string, params, out any) error

Call issues a request and unmarshals the result into out (which may be nil). It blocks until the reply arrives or the connection closes; use CallContext to bound the wait.

func (*Peer) CallContext

func (p *Peer) CallContext(ctx context.Context, method string, params, out any) error

CallContext is Call with a context: on cancel/deadline it abandons the request and returns ctx.Err(), reclaiming the pending slot so a late reply isn't leaked.

func (*Peer) Close

func (p *Peer) Close() error

Close terminates the connection and unblocks in-flight calls.

func (*Peer) Done

func (p *Peer) Done() <-chan struct{}

Done is closed when the peer's read loop ends (connection closed or errored).

func (*Peer) Notify

func (p *Peer) Notify(method string, params any) error

Notify sends a one-way notification (no response expected).

func (*Peer) RemoteCBOR

func (p *Peer) RemoteCBOR() bool

func (*Peer) SendRawFrame

func (p *Peer) SendRawFrame(enc Encoding, payload []byte) error

SendRawFrame writes a pre-marshaled payload verbatim, adding the framing for enc. A blind gateway uses it to forward a relayed frame's Raw bytes to the paired peer without re-encoding — the sealed Body is never touched.

func (*Peer) SetRemoteCBOR

func (p *Peer) SetRemoteCBOR(ok bool)

SetRemoteCBOR records whether the remote accepts CBOR frames.

type PeerCapabilities

type PeerCapabilities struct {
	CBOR bool `json:"cbor"`
}

PeerCapabilities is what a connection peer supports, sent in the identify handshake and echoed in server.info.

type PeerOptions

type PeerOptions struct {
	// Dispatch handles requests the remote end issues. Nil means this peer serves
	// no methods (every inbound request gets method-not-found).
	Dispatch DispatchFunc
	// OnNotify receives notifications the remote end sends. Nil drops them.
	OnNotify func(Notification)
	// OnRelayFrame receives frames carrying a Route header (relayed E2E frames),
	// along with the source Peer so the gateway can enforce channel ownership. Set
	// on the gateway (to forward by chan_id) and on endpoints (to decrypt Body).
	// Nil drops relay frames — they never reach Dispatch/OnNotify/the pending path.
	OnRelayFrame func(*Peer, RelayFrame)
	// BaseContext is the parent of each served request's context (so values like
	// an auth Principal flow to handlers). Defaults to context.Background().
	BaseContext context.Context
	// KeepaliveInterval > 0 pings the remote every interval; used to detect a
	// half-open link that never errors on read. Zero disables keepalive.
	KeepaliveInterval time.Duration
	// KeepaliveTimeout bounds each ping's wait for a reply. Defaults to KeepaliveInterval.
	KeepaliveTimeout time.Duration
	// KeepaliveFailureThreshold is how many consecutive failed pings close the
	// peer; an answered ping resets the count. Defaults to 1.
	KeepaliveFailureThreshold int
	// WriteTimeout bounds how long a single frame write may block, so one stuck
	// consumer can't wedge a shared writer (e.g. a slow terminal viewer blocking
	// the node uplink). Exceeding it errors and closes the peer. Zero uses
	// defaultWriteTimeout; a negative value disables the deadline.
	WriteTimeout time.Duration
}

PeerOptions configures a Peer's inbound behavior.

type Principal

type Principal struct {
	Admin bool
}

Principal identifies how a connection authenticated. Admin is true when the caller presented the gateway's master token (vs. a minted per-client token), gating connection-management methods.

func PrincipalFrom

func PrincipalFrom(ctx context.Context) Principal

PrincipalFrom returns the connection's Principal; the zero value (non-admin) when none was attached.

type ProjectFlagParams

type ProjectFlagParams struct {
	ProjectID string `json:"project_id"`
	Value     bool   `json:"value"`
}

type ProjectListResult

type ProjectListResult struct {
	Projects []ProjectNode `json:"projects"`
}

ProjectListResult is one node's project tree (node-local; ids not composited).

type ProjectNode

type ProjectNode struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	Kind string `json:"kind"` // git|plain
	Dir  string `json:"dir"`
	Root string `json:"root,omitempty"`
	// DefaultBranch is resolved live.
	DefaultBranch string          `json:"default_branch,omitempty"`
	IsGone        bool            `json:"is_gone,omitempty"`
	Error         string          `json:"error,omitempty"` // git failed on it this list; workspaces are the last known
	Hidden        bool            `json:"hidden,omitempty"`
	Pinned        bool            `json:"pinned,omitempty"`
	CreatedAt     string          `json:"created_at,omitempty"`   // RFC3339
	LastSeenAt    string          `json:"last_seen_at,omitempty"` // RFC3339
	Scripts       *ProjectScripts `json:"scripts,omitempty"`      // from .argus/settings*.toml in the main worktree
	Workspaces    []WorkspaceNode `json:"workspaces"`
	// Set only by the aggregating client, not the node.
	NodeID    string `json:"node_id,omitempty"`
	NodeLabel string `json:"node_label,omitempty"`
}

ProjectNode is a repository or plain directory with its workspaces. Root is the main workspace's dir, empty for a bare repo.

type ProjectRef

type ProjectRef struct {
	ProjectID string `json:"project_id"`
}

ProjectRef addresses a project by its (composite) id.

type ProjectRenameParams

type ProjectRenameParams struct {
	ProjectID string `json:"project_id"`
	Name      string `json:"name"`
}

ProjectRenameParams sets a project's display name.

type ProjectRenameResult

type ProjectRenameResult struct {
	Name string `json:"name"`
}

ProjectRenameResult is the name as stored.

type ProjectScripts

type ProjectScripts struct {
	Setup    string `json:"setup,omitempty"`
	Teardown string `json:"teardown,omitempty"`
}

type PromptCompleteParams

type PromptCompleteParams struct {
	SessionID string `json:"session_id"`
	Trigger   string `json:"trigger"` // "/", "$" or "@"
}

type PromptCompleteResult

type PromptCompleteResult struct {
	Items []PromptCompletion `json:"items"`
}

PromptCompleteResult is empty when the agent has nothing for the trigger.

type PromptCompletion

type PromptCompletion struct {
	Name        string `json:"name"`
	Description string `json:"description"`
}

PromptCompletion is one menu entry. Name omits the trigger character.

type PushDeliverParams

type PushDeliverParams struct {
	Endpoint   string `json:"endpoint"`
	Ciphertext string `json:"ciphertext"`
	TTL        string `json:"ttl,omitempty"`
	Urgency    string `json:"urgency,omitempty"`
}

PushDeliverParams carries an opaque, pre-encrypted (aes128gcm) Web Push body for the gateway to deliver on a node's behalf. Ciphertext is base64 (std encoding).

type PushDeliverResult

type PushDeliverResult struct {
	Gone bool `json:"gone,omitempty"`
}

PushDeliverResult reports delivery outcome. Gone means the subscription is dead (404/410) and the node should prune its local record.

type PushDeviceRef

type PushDeviceRef struct {
	DeviceID string `json:"device_id"`
}

PushDeviceRef identifies a device by its stable id (for unregister/test).

type PushPortSetTokenParams

type PushPortSetTokenParams struct {
	Token string `json:"token"`
}

PushPortSetTokenParams is the request body for MethodPushPortSetToken.

type PushRegisterParams

type PushRegisterParams struct {
	DeviceID string `json:"device_id"`
	Endpoint string `json:"endpoint,omitempty"`
	P256dh   string `json:"p256dh,omitempty"`
	Auth     string `json:"auth,omitempty"`
	// PausedUntil carries the device's current pause preference so the node applies
	// it atomically at register time. Empty means enabled. See PushSetPauseParams.
	PausedUntil string `json:"paused_until,omitempty"`
}

PushRegisterParams registers a device's Web Push target. DeviceID is the stable storage key; Endpoint is the distributor URL; P256dh/Auth are subscription keys.

type PushSetPauseParams

type PushSetPauseParams struct {
	DeviceID    string `json:"device_id"`
	PausedUntil string `json:"paused_until,omitempty"`
}

PushSetPauseParams updates only a device's pause state without re-registering. PausedUntil is an RFC3339 time; empty re-enables the device.

type PushVAPIDKey

type PushVAPIDKey struct {
	Key string `json:"key,omitempty"`
}

PushVAPIDKey carries the gateway's VAPID public key (the applicationServerKey a device subscribes with).

type RPCError

type RPCError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

RPCError is a JSON-RPC error object.

func Serve

func Serve(ctx context.Context, dispatch DispatchFunc, enc Encoding, method string, params []byte) ([]byte, *RPCError)

Serve dispatches a request whose params are encoded in enc and returns the result encoded in enc. CBOR params are decoded by WithCBORParams, so dispatch sees no params for them.

func WithCBORParams

func WithCBORParams(ctx context.Context, method string, params []byte) (context.Context, *RPCError)

WithCBORParams prepares a CBOR request for dispatch. A method outside CBORMethods is rejected without decoding its params; otherwise the params decode into the method's typed struct, carried on the returned context (see CBORParams), and the request is dispatched without JSON params.

func (*RPCError) Error

func (e *RPCError) Error() string

type ReadFileResult

type ReadFileResult struct {
	Path     string `json:"path"`
	Content  string `json:"content,omitempty"`
	NotShown bool   `json:"not_shown,omitempty"` // binary or oversized
}

ReadFileResult carries a working-tree file's content.

type ReconnectingClient

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

ReconnectingClient re-dials with capped exponential backoff when its connection drops, keeping a stable Events() stream across reconnects and reporting state transitions on States(). Reconnect() forces an immediate retry. Safe for concurrent use.

func NewReconnectingClient

func NewReconnectingClient(ctx context.Context, dial Dialer) (*ReconnectingClient, error)

NewReconnectingClient dials once (so startup failure surfaces immediately) and then maintains the connection until Close.

func (*ReconnectingClient) Call

func (c *ReconnectingClient) Call(method string, params, out any) error

Call routes to the live peer, erroring promptly when disconnected rather than blocking.

func (*ReconnectingClient) Close

func (c *ReconnectingClient) Close() error

Close stops reconnecting and terminates the current connection.

func (*ReconnectingClient) Events

func (c *ReconnectingClient) Events() <-chan Notification

Events returns the stable notification stream, not closed on reconnect; it carries notifications from whichever connection is currently live.

func (*ReconnectingClient) Quarantined

func (c *ReconnectingClient) Quarantined() bool

Quarantined is always false: the plaintext client never enforces trust-log locking.

func (*ReconnectingClient) Reconnect

func (c *ReconnectingClient) Reconnect()

Reconnect forces an immediate reconnect attempt (and resets backoff). No-op while connected.

func (*ReconnectingClient) States

func (c *ReconnectingClient) States() <-chan bool

States reports connection-state transitions: false when the connection drops, true when it is re-established.

type RelayCloseParams

type RelayCloseParams struct {
	ChanID string `json:"chan_id"`
}

RelayCloseParams tears down an E2E channel the client owns.

type RelayFrame

type RelayFrame struct {
	Enc    Encoding
	Method string
	ID     *json.RawMessage
	Route  RouteHeader
	Body   []byte
	Raw    []byte
}

RelayFrame is a JSON-RPC frame on a relayed (gateway) link. A blind gateway routes it by Route.ChanID alone and forwards Raw verbatim to the paired peer, never reading the cleartext Method/ID or touching the sealed Body. Raw is the envelope without framing; Body is the JSON body token (JSON) or the sealed bytes (CBOR).

func ParseRelayFrame

func ParseRelayFrame(enc Encoding, raw []byte) (RelayFrame, error)

ParseRelayFrame parses a frame payload (without framing) as a relay frame.

type RelayOpenParams

type RelayOpenParams struct {
	NodeID string `json:"node_id"`
}

type RelayOpenResult

type RelayOpenResult struct {
	ChanID string `json:"chan_id"`
}

type RelayPeerOpenedParams

type RelayPeerOpenedParams struct {
	ChanID   string `json:"chan_id"`
	FromNode string `json:"from_node"`
}

RelayPeerOpenedParams names the node that opened ChanID to the receiving node.

type RemoteCaller

type RemoteCaller struct {
	Actor Actor  `json:"actor"`
	Label string `json:"label"`
}

RemoteCaller is an agent session on another node, as that node states it.

type RespondParams

type RespondParams struct {
	SessionID string `json:"session_id"`

	// Structured hook decision (PermissionRequest path).
	Behavior string         `json:"behavior,omitempty"` // "allow" | "deny"
	Reason   string         `json:"reason,omitempty"`   // deny message
	Answers  map[string]any `json:"answers,omitempty"`  // AskUserQuestion: question -> label|[label]|text
	// QuestionAction is a non-answer action on an AskUserQuestion prompt.
	// "" = normal answer submit; "chat" = reject with a clarify request;
	// "cancel" = reject the tool the way native Claude Code cancel does.
	QuestionAction string `json:"question_action,omitempty"`
	// Notes carries a free-text note per question (question text -> note) for
	// questions with AllowNotes. Adapters without note support ignore it.
	Notes map[string]string `json:"notes,omitempty"`
	// SetMode, on an allow decision (e.g. ExitPlanMode approval), switches the
	// session's permission mode: "acceptEdits" | "default" | "auto".
	SetMode string `json:"set_mode,omitempty"`
	// OptionValue echoes a server-built DecisionOption.Value. Node maps it:
	// "deny" → deny; "allow" → plain allow; any other → allow + setMode <value>.
	OptionValue string `json:"option_value,omitempty"`
	// RequestID echoes Interaction.RequestID so the answer reaches the request the
	// user saw, not one that replaced it.
	RequestID string `json:"request_id,omitempty"`

	// Keystroke fallback (no parked hook / idle).
	Kind        string `json:"kind,omitempty"`
	OptionIndex int    `json:"option_index,omitempty"`
	Text        string `json:"text,omitempty"`
}

RespondParams answers a pending interaction (see session.Interaction). Preferred path: a parked PermissionRequest hook turns this into the hook's decision JSON (Behavior, Reason, Answers). Without a parked hook it falls back to pane keystrokes (Kind/OptionIndex/Text).

type ResumeParams

type ResumeParams struct {
	NodeID         string `json:"node_id,omitempty"` // gateway routing key; ignored node-side
	Agent          string `json:"agent"`             // owning agent id
	AgentSessionID string `json:"agent_session_id"`  // the tool's own session id to resume
	Cwd            string `json:"cwd"`               // original working directory
}

ResumeParams asks a node to resume a past session by its agent session id, in the session's original working directory.

type ResumeResult

type ResumeResult struct {
	SessionID string `json:"session_id"`
}

ResumeResult identifies the session to open, whether newly spawned or an already-live session the resume jumped to.

type RouteHeader

type RouteHeader struct {
	ChanID string `json:"chan_id"`           // client<->node E2E channel; the routing key
	NodeID string `json:"node_id,omitempty"` // target node (set on the channel-open request)
	SubID  string `json:"sub_id,omitempty"`  // streaming handle; the client demuxes on it
	TermID string `json:"term_id,omitempty"` // terminal handle; the client demuxes on it
}

RouteHeader is the cleartext routing metadata a blind gateway reads to relay a frame between a client and a node. It appears only on relayed (gateway) links; the local unix-socket path leaves it nil and uses Params/Result directly.

type ScriptRun

type ScriptRun struct {
	State      string `json:"state"` // running|ok|failed
	Command    string `json:"command"`
	ExitCode   int    `json:"exit_code,omitempty"`
	StartedAt  string `json:"started_at,omitempty"` // RFC3339
	EndedAt    string `json:"ended_at,omitempty"`   // RFC3339
	OutputTail string `json:"output_tail,omitempty"`
}

ScriptRun is a workspace's last setup run.

type Server

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

Server dispatches JSON-RPC requests and streams notifications to clients. Each accepted connection becomes a Peer routed through the shared handler registry.

func NewServer

func NewServer() *Server

NewServer returns an empty Server.

func (*Server) DispatchFunc

func (s *Server) DispatchFunc() DispatchFunc

DispatchFunc returns a DispatchFunc bound to this server's handler registry, so the same handlers serve over a non-listener transport (e.g. the node's gateway uplink).

func (*Server) Handle

func (s *Server) Handle(method string, h HandlerFunc)

Handle registers a handler for a method.

func (*Server) OnConnect

func (s *Server) OnConnect(fn func(n Notifier) (cleanup func()))

OnConnect registers a hook invoked once per connection with a Notifier for pushing notifications; the returned cleanup runs when the connection closes.

func (*Server) Serve

func (s *Server) Serve(l net.Listener) error

Serve accepts connections on l until the listener is closed.

func (*Server) ServeConn

func (s *Server) ServeConn(netConn net.Conn)

ServeConn serves a single established connection until it closes. Exported so non-listener transports (e.g. a WebSocket adapted to net.Conn) reuse the dispatch path.

func (*Server) ServeConnContext

func (s *Server) ServeConnContext(ctx context.Context, netConn net.Conn)

ServeConnContext is ServeConn with a connection-scoped base context, whose values (e.g. an auth Principal) reach every request served on the connection.

func (*Server) ServeContext

func (s *Server) ServeContext(ctx context.Context, l net.Listener) error

ServeContext is Serve until ctx is done. It then closes l and returns nil.

func (*Server) SetLogger

func (s *Server) SetLogger(l *slog.Logger)

SetLogger enables per-request logging through l (nil disables it). Each request is logged once on completion (method, duration, error).

func (*Server) SetRelayFrameHandler

func (s *Server) SetRelayFrameHandler(fn func(*Peer, RelayFrame))

SetRelayFrameHandler installs a handler invoked for every relay frame (one carrying a Route header) on any connection this server serves. The handler receives the source *Peer so it can enforce channel ownership (a relay frame must come from the peer that owns the target chan_id). Nil (the default) drops relay frames.

func (*Server) WSHandler

func (s *Server) WSHandler(authorize func(token string) bool) http.Handler

WSHandler returns an http.Handler that authenticates the bearer token, upgrades to a WebSocket, and serves it through this Server's registry. nil authorize allows all connections (local/dev only). TLS is applied by the enclosing http.Server.

type ServerInfo

type ServerInfo struct {
	Version            string            `json:"version"`
	StartedAt          string            `json:"started_at,omitempty"` // RFC3339
	Nodes              []NodeInfo        `json:"nodes"`
	PushPortConfigured bool              `json:"pushPortConfigured"`
	Capabilities       *PeerCapabilities `json:"capabilities,omitempty"`
}

ServerInfo carries server-wide metadata for a connected client: server version and connected nodes. Served by the gateway.

type ServerTargetParams

type ServerTargetParams struct {
	NodeID string `json:"node_id,omitempty"`
}

ServerTargetParams addresses a server.* call: the client sends it to the node named by NodeID, or to the gateway when NodeID is empty.

type SessionKillResult

type SessionKillResult struct {
	NotKilled []string `json:"not_killed,omitempty"`
}

SessionKillResult lists the descendants on other nodes that could not be reached or killed; the session and its local descendants were killed.

type SessionRef

type SessionRef struct {
	SessionID string `json:"session_id"`
}

SessionRef selects a session by id.

type SessionRenameParams

type SessionRenameParams struct {
	SessionID string `json:"session_id"`
	Name      string `json:"name"`
}

SessionRenameParams renames a session through the agent's own rename feature. Name is trimmed; blank names are rejected.

type SessionRenameResult

type SessionRenameResult struct {
	Name    string `json:"name"`
	Applied bool   `json:"applied"`
}

SessionRenameResult is the requested name. Applied is false when the agent takes the name later; the session update follows once it has.

type SetupLogResult

type SetupLogResult struct {
	Output string `json:"output"`
}

type SpawnParams

type SpawnParams struct {
	NodeID  string `json:"node_id,omitempty"` // gateway routing key; ignored node-side
	Name    string `json:"name,omitempty"`    // tmux session name; blank = node-generated default
	Cwd     string `json:"cwd,omitempty"`
	Agent   string `json:"agent,omitempty"`   // node resolves to a command; blank = default
	Command string `json:"command,omitempty"` // explicit launch command; overrides Agent when set
	Prompt  string `json:"prompt,omitempty"`  // initial prompt; how it reaches the CLI is agent-specific (an argument, or a flag like --prompt-interactive)
	Model   string `json:"model,omitempty"`   // a ModelInfo.ID from agent.model.list; blank = the agent's default
}

type SpawnResult

type SpawnResult struct {
	SessionID string `json:"session_id"`
	PaneID    string `json:"pane_id"`
}

SpawnResult identifies the newly created session.

type Task

type Task struct {
	ID          string   `json:"id"`
	Subject     string   `json:"subject"`
	Description string   `json:"description,omitempty"`
	ActiveForm  string   `json:"active_form,omitempty"` // spinner label while in_progress
	Status      string   `json:"status"`                // pending|in_progress|completed
	Blocks      []string `json:"blocks,omitempty"`
	BlockedBy   []string `json:"blocked_by,omitempty"`
}

Task is one entry in a session's Claude Code task list (the TaskCreate/ TaskUpdate tools), read from ~/.claude/tasks/<session>/<id>.json.

type TasksChanged

type TasksChanged struct {
	SubID     string `json:"sub_id"`
	SessionID string `json:"session_id"`
}

TasksChanged signals that a session's task list changed on disk; the client re-pulls via sessions.tasks. SubID routes it through the gateway like a transcript delta.

type TasksResult

type TasksResult struct {
	Tasks []Task `json:"tasks"`
}

TasksResult is a session's current task list, ordered by numeric id.

type Terminal

type Terminal struct {
	ID       string `json:"id"`
	Name     string `json:"name,omitempty"` // empty until renamed
	Cwd      string `json:"cwd"`            // the node user's home shows as ~
	Command  string `json:"command"`
	Attached bool   `json:"attached,omitempty"`
	// WorkspaceID is the workspace the terminal was created in, composited by
	// the aggregating client like session.workspace_id.
	WorkspaceID string `json:"workspace_id,omitempty"`
	// Set only by the aggregating client, not the node.
	NodeID    string `json:"node_id,omitempty"`
	NodeLabel string `json:"node_label,omitempty"`
}

Terminal is a persistent shell on a node: one window of its terminal tmux session. ID is the tmux window id.

type TerminalChanged

type TerminalChanged struct {
	NodeID string `json:"node_id,omitempty"`
}

TerminalChanged is empty from a node; a gateway client sets NodeID.

type TerminalCloseParams

type TerminalCloseParams struct {
	TermID string `json:"term_id"`
}

TerminalCloseParams closes a terminal session.

type TerminalCreateParams

type TerminalCreateParams struct {
	NodeID      string `json:"node_id,omitempty"`
	WorkspaceID string `json:"workspace_id,omitempty"`
}

TerminalCreateParams opens the terminal in $HOME, or in the directory of the node-local WorkspaceID, which the terminal then belongs to.

type TerminalExited

type TerminalExited struct {
	TermID string `json:"term_id"`
	// Reason is why the attach ended; empty is treated as TermExitedProcess.
	Reason string `json:"reason,omitempty"`
}

TerminalExited notifies the client that a terminal attach ended. Reason tells the client why so it can show a fitting message (see the TermExited* consts).

type TerminalInputParams

type TerminalInputParams struct {
	TermID string `json:"term_id"`
	Data   []byte `json:"data"`
}

TerminalInputParams sends input data to a terminal session.

type TerminalListResult

type TerminalListResult struct {
	Terminals   []Terminal `json:"terminals"`
	FailedNodes []string   `json:"failed_nodes,omitempty"`
}

TerminalListResult is one node's terminals (node-local; ids not composited). FailedNodes is set only by a client merge: nodes whose list failed.

type TerminalOpenParams

type TerminalOpenParams struct {
	TermID    string `json:"term_id"`
	SessionID string `json:"session_id"`
	Cols      int    `json:"cols"`
	Rows      int    `json:"rows"`
	// ClientPane is the caller's own tmux pane ($TMUX_PANE) when co-located on the
	// session's server; empty otherwise (e.g. the mobile app). The node uses it to
	// refuse an open that would share the agent pane's window.
	ClientPane string `json:"client_pane,omitempty"`
	// TerminalID names a persistent terminal to attach instead of a session.
	TerminalID string `json:"terminal_id,omitempty"`
}

TerminalOpenParams opens a terminal session with the given dimensions.

type TerminalOutput

type TerminalOutput struct {
	TermID string `json:"term_id"`
	Data   []byte `json:"data"`
}

TerminalOutput is server→client output from a terminal session (base64 in JSON, raw in CBOR).

type TerminalRef

type TerminalRef struct {
	TerminalID string `json:"terminal_id"`
}

type TerminalRenameParams

type TerminalRenameParams struct {
	TerminalID string `json:"terminal_id"`
	Name       string `json:"name"`
}

type TerminalResizeParams

type TerminalResizeParams struct {
	TermID string `json:"term_id"`
	Cols   int    `json:"cols"`
	Rows   int    `json:"rows"`
}

TerminalResizeParams resizes a terminal session.

type ToolDetail

type ToolDetail struct {
	ToolInput     string `json:"toolInput,omitempty"`
	Result        string `json:"result,omitempty"`
	ResultIsError bool   `json:"resultIsError,omitempty"`
}

ToolDetail is one tool entry's heavy body, fetched on demand. The json tags match the Entry fields so clients can fill a cached entry in place.

type ToolDetailParams

type ToolDetailParams struct {
	SessionID string `json:"session_id"`
	AgentID   string `json:"agent_id,omitempty"`
	ToolID    string `json:"tool_id"`
}

ToolDetailParams selects one tool entry's full body in a live session's transcript. AgentID selects a subagent trace; ToolID is the entry's toolId.

type TranscriptDelta

type TranscriptDelta struct {
	SubID     string                     `json:"sub_id"`
	FromIndex int                        `json:"from_index"`
	Entries   []transcript.Entry         `json:"entries"`
	Queue     *[]transcript.QueuedPrompt `json:"queue,omitempty"`
}

TranscriptDelta is both the subscribe result (initial catch-up) and the push payload. The client truncates its cached entries to FromIndex, then appends Entries. Queue, when present, replaces the client's queued prompts; absent, they are unchanged.

type TranscriptParams

type TranscriptParams = SessionRef

TranscriptParams selects a session for MethodSessionTranscriptView.

type TranscriptSubscribeParams

type TranscriptSubscribeParams struct {
	SubID       string `json:"sub_id"`
	SessionID   string `json:"session_id"`
	AgentID     string `json:"agent_id,omitempty"`
	HaveEntries int    `json:"have_entries"`
}

TranscriptSubscribeParams opens a subscription. AgentID selects a subagent trace. HaveEntries is the client's cached entry count, for a minimal catch-up.

type TranscriptUnsubscribeParams

type TranscriptUnsubscribeParams struct {
	SubID string `json:"sub_id"`
}

TranscriptUnsubscribeParams closes the subscription identified by SubID.

type TrustLogChangedParams

type TrustLogChangedParams struct {
	Heads [][]byte `json:"heads,omitempty"`
}

TrustLogChangedParams is the payload of a MethodTrustLogChanged notification. Heads are the gateway's head hashes after the change. A receiver that already holds every one of them has nothing to fetch and can skip the sync entirely.

type TrustLogPushParams

type TrustLogPushParams struct {
	Entries [][]byte `json:"entries,omitempty"`
}

TrustLogPushParams carries individually marshalled entries a node is publishing to the gateway, ordered parents before children.

type TrustLogSyncParams

type TrustLogSyncParams struct {
	Known     [][]byte `json:"known,omitempty"`
	Truncated bool     `json:"truncated,omitempty"`
}

TrustLogSyncParams states what the caller holds. Known lists the hash of every entry it retains — adopted chain and rejected branches alike — so the gateway computes the delta by set subtraction and never infers ancestry from a head. Truncated reports that Known was capped and is partial: the caller will receive entries it already holds, which dedupe, and the gateway must not treat a truncated offer as disjoint.

type TrustLogSyncResult

type TrustLogSyncResult struct {
	Entries  [][]byte `json:"entries,omitempty"`
	Want     [][]byte `json:"want,omitempty"`
	Disjoint bool     `json:"disjoint,omitempty"`
}

TrustLogSyncResult answers a trustlog.sync. Entries holds every retained entry the caller does not hold, as individually marshalled trustlog.MarshalEntry bytes, ordered parents before children; the gateway computes this by set subtraction over the caller's Known offer. Want names hashes in the caller's Known that the gateway does not hold; a node answers it with trustlog.push, a client ignores it — clients are supplicants and must not publish trust state. Disjoint reports that a non-empty, untruncated Known shared no entry with the gateway's store — the caller is almost certainly following a different trust root. Advisory only: the entries are still returned, because a client discovering the network's genesis and a device detecting supersession both need them.

type UpgradeParams

type UpgradeParams struct {
	ServerTargetParams
	Beta bool `json:"beta,omitempty"`
	// Fresh makes server.checkUpgrade skip its cache.
	Fresh bool `json:"fresh,omitempty"`
}

type UpgradeResult

type UpgradeResult struct {
	From string `json:"from"`
	To   string `json:"to"`
}

UpgradeResult: To == From means the target already runs the latest version.

type WorkspaceCommitParams

type WorkspaceCommitParams struct {
	WorkspaceID string `json:"workspace_id"`
	SHA         string `json:"sha"`
}

type WorkspaceCreateParams

type WorkspaceCreateParams struct {
	ProjectID    string `json:"project_id"`
	Source       string `json:"source,omitempty"`        // SourceNew (default) | SourceBranch | SourcePR | SourceIssue
	Branch       string `json:"branch,omitempty"`        // new: name to create; branch: name to check out
	Number       int    `json:"number,omitempty"`        // pr, issue
	TargetBranch string `json:"target_branch,omitempty"` // "" = project default branch
}

type WorkspaceCreateResult

type WorkspaceCreateResult struct {
	WorkspaceID string `json:"workspace_id"`
	Dir         string `json:"dir"`
	Warning     string `json:"warning,omitempty"`
	Prompt      string `json:"prompt,omitempty"`
	Setup       string `json:"setup,omitempty"` // the setup command that started in the background
	// SetupRun is the setup's state when the reply was sent, absent with no setup.
	SetupRun     *ScriptRun `json:"setup_run,omitempty"`
	Branch       string     `json:"branch,omitempty"`
	TargetBranch string     `json:"target_branch,omitempty"` // empty: the repository's default branch
}

WorkspaceCreateResult's Prompt carries an issue's text for an optional agent spawn.

type WorkspaceDiffResult

type WorkspaceDiffResult struct {
	Path     string `json:"path"`
	Diff     string `json:"diff,omitempty"`
	NotShown bool   `json:"not_shown,omitempty"` // binary or oversized
}

type WorkspaceFileParams

type WorkspaceFileParams struct {
	WorkspaceID string `json:"workspace_id"`
	Path        string `json:"path"`                // repo-relative slash path ("" = root, for listDir)
	Against     string `json:"against,omitempty"`   // diff only: "" (vs HEAD) or AgainstTarget
	OrigPath    string `json:"orig_path,omitempty"` // diff only: rename source, so the diff shows the rename
	Rev         string `json:"rev,omitempty"`       // diff only: a commit sha; shows that commit's change and ignores Against
}

type WorkspaceNode

type WorkspaceNode struct {
	ID     string `json:"id"`
	Dir    string `json:"dir"`
	IsMain bool   `json:"is_main,omitempty"`
	IsGone bool   `json:"is_gone,omitempty"`
	Branch string `json:"branch,omitempty"`
	Head   string `json:"head,omitempty"`
	// TargetBranch is the stored target, or the project's default branch.
	TargetBranch string     `json:"target_branch,omitempty"`
	CreatedAt    string     `json:"created_at,omitempty"`   // RFC3339
	LastSeenAt   string     `json:"last_seen_at,omitempty"` // RFC3339
	Setup        *ScriptRun `json:"setup,omitempty"`        // the last setup run; absent after a node restart
}

WorkspaceNode is one git worktree (or a plain project's single directory) in the project tree. Branch and Head are computed live at read; they are empty for a gone or plain workspace, and Branch is empty for a detached HEAD.

type WorkspaceRef

type WorkspaceRef struct {
	WorkspaceID string `json:"workspace_id"`
	Against     string `json:"against,omitempty"`
}

WorkspaceRef addresses a workspace by its (composite) id. Against selects the changed-files view: "" (uncommitted) or AgainstTarget.

type WorkspaceRemoveParams

type WorkspaceRemoveParams struct {
	WorkspaceID string `json:"workspace_id"`
	Force       bool   `json:"force,omitempty"`
}

WorkspaceRemoveParams removes a worktree. Force removes a dirty worktree; a workspace with live sessions is refused either way.

type WorkspaceRemoveResult

type WorkspaceRemoveResult struct {
	Warning string `json:"warning,omitempty"`
}

WorkspaceRemoveResult carries a teardown failure that a forced remove passed over.

type WorkspaceSetTargetParams

type WorkspaceSetTargetParams struct {
	WorkspaceID  string `json:"workspace_id"`
	TargetBranch string `json:"target_branch"`
}

WorkspaceSetTargetParams sets a workspace's target branch ("" = default).

type WorkspaceSetTargetResult

type WorkspaceSetTargetResult struct {
	TargetBranch string `json:"target_branch"`
}

WorkspaceSetTargetResult is the target as stored; empty is the repository's default branch.

Jump to

Keyboard shortcuts

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