subagent

package
v0.13.0 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2026 License: AGPL-3.0 Imports: 14 Imported by: 0

Documentation

Overview

Package subagent tracks the subagents and agent-team teammates a Claude session has spawned, from the Claude Code hook events loom registers at launch. See docs/superpowers/specs/2026-09-16-subagent-nesting-design.md.

It has no dependency on tmux, the UI or the app, so every piece can be tested against payloads captured from a real Claude session.

Index

Constants

View Source
const (
	EventSubagentStart = "SubagentStart"
	EventSubagentStop  = "SubagentStop"
	EventTeammateIdle  = "TeammateIdle"
	EventStop          = "Stop"
	EventSessionEnd    = "SessionEnd"
)

Hook event names loom registers.

Variables

View Source
var ErrNoHooks = errors.New("subagent: no hooks folder")

ErrNoHooks means the folder or its launch-id is missing: the session was launched without tracking.

View Source
var ErrUnknownEvent = errors.New("subagent: unknown hook event")

ErrUnknownEvent is returned by ParseEvent for a JSON object whose hook_event_name is not one loom registers.

HookEvents lists the registered events in the order settings.json declares them.

Functions

func EventsDir

func EventsDir(dir string) string

EventsDir is where hooks write one file per event.

func HookCommand

func HookCommand(eventsDir string) string

HookCommand returns the shell command every hook runs. It writes the payload Claude pipes on stdin to a new file in eventsDir, first as .tmp and then renamed, so a reader never sees a partial file. It always exits 0 and always reads its whole input, including when eventsDir is gone or the disk is full, so Claude never reports a hook error or fails writing the payload. The name is <unix-nanos>-<pid>; macOS date prints a literal N for %N, so there the pid alone keeps names unique and the scan orders by modification time. eventsDir must satisfy SafePath.

func MetaPath

func MetaPath(transcriptPath, agentID string) string

MetaPath returns where Claude writes agentID's sidecar for the session whose transcript is at transcriptPath. It returns "" when either is empty, or when agentID could escape the subagents folder.

func Prepare

func Prepare(dir string) (string, error)

Prepare empties dir and writes a fresh settings.json, events folder and launch-id for a new launch, returning the launch ID. Events from an earlier launch describe agents that no longer exist, so nothing is kept. launch-id is written last, so a concurrent scan never sees a new ID without its settings.

func SafePath

func SafePath(p string) bool

SafePath reports whether p can be embedded in the single-quoted hook command and the single-quoted --settings flag.

func SettingsJSON

func SettingsJSON(eventsDir string) ([]byte, error)

SettingsJSON returns the settings file registering HookCommand for every event in HookEvents. Claude adds these hooks to the user's own.

func SettingsPath

func SettingsPath(dir string) string

SettingsPath is the file passed to claude --settings.

Types

type Event

type Event struct {
	Name           string
	AgentID        string
	AgentType      string
	TeammateName   string
	TranscriptPath string
	// Tasks is the background_tasks list. HasTasks is false when the field
	// was absent, null or malformed. Reconciliation must then do nothing:
	// reading an unusable list as empty would remove every agent.
	Tasks    []Task
	HasTasks bool
}

Event is one hook event. The same shape covers the raw payload Claude writes and the compact form the scan keeps (see Compact).

func ParseEvent

func ParseEvent(data []byte) (Event, error)

ParseEvent decodes a raw hook payload or a compact event. It returns an error wrapping ErrUnknownEvent for events loom does not register, and a different error for input that is not a JSON object.

func (Event) Compact

func (e Event) Compact() ([]byte, error)

Compact returns the event as the scan keeps it on disk: the payload's field names, only the fields loom reads, and tasks reduced to id/type/status. ParseEvent reads it back unchanged. A missing task list stays missing and an empty one stays empty.

type Meta

type Meta struct {
	AgentType   string `json:"agentType"`
	Name        string `json:"name"`
	Description string `json:"description"`
	TaskKind    string `json:"taskKind"`
}

Meta is the part of Claude's agent-<id>.meta.json sidecar loom reads. Several key sets exist across CLI versions; every field is optional.

func ParseMeta

func ParseMeta(data []byte) (Meta, error)

ParseMeta decodes a metadata sidecar.

func (Meta) DisplayName

func (m Meta) DisplayName() string

DisplayName is the label shown for the agent: its name when it has one, else its agent type.

func (Meta) IsTeammate

func (m Meta) IsTeammate() bool

IsTeammate reports whether the sidecar describes an agent-team teammate, which goes idle after a turn rather than ending.

type MetaRef

type MetaRef struct {
	AgentID string
	Path    string
}

MetaRef locates one agent's sidecar.

type Request

type Request struct {
	// Dir is the instance's hooks folder.
	Dir string
	// Cold replays the retained .ev log. True for the first scan after a
	// launch or a loom restart.
	Cold bool
	// MissingMeta lists agents still waiting for their sidecar.
	MissingMeta []MetaRef
}

Request describes one instance's scan.

type Result

type Result struct {
	LaunchID string
	Events   []Event
	Meta     map[string]Meta
	// Replayed is true when Events is the full history (Request.Cold).
	Replayed bool
}

Result is what one scan found.

func Scan

func Scan(req Request, now time.Time) (Result, error)

Scan collects hook events for one instance. New .json files (at most maxNewPerScan, oldest first) are parsed and replaced by compact .ev files that keep their original modification time. A cold scan also replays every .ev file that existed before this scan. Events are returned ordered by modification time, then file stem, together with the metadata sidecars for new SubagentStart events and req.MissingMeta. Scan only touches the filesystem, so it is safe to run from a tea.Cmd.

type Task

type Task struct {
	ID     string `json:"id"`
	Type   string `json:"type"`
	Status string `json:"status"`
}

Task is one entry of a payload's background_tasks list, reduced to the fields reconciliation reads.

type Tracker

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

Tracker derives the live agent set from hook events. It is not safe for concurrent use; session.Instance guards it with its own mutex.

func NewTracker

func NewTracker() *Tracker

NewTracker returns an empty tracker.

func (*Tracker) Apply

func (t *Tracker) Apply(events []Event, meta map[string]Meta)

Apply folds events, in order, into the tracker. meta holds sidecars read since the last call, keyed by agent ID. They are applied to known agents first, so an agent that started and stopped within one batch already has its kind when its SubagentStop is processed.

func (*Tracker) MissingMeta

func (t *Tracker) MissingMeta() []MetaRef

MissingMeta lists agents still waiting for their sidecar, sorted by ID, so the next scan can retry them.

func (*Tracker) Reset

func (t *Tracker) Reset()

Reset forgets every agent. Called at a new launch and before a replay rebuilds state from the full event log.

func (*Tracker) Visible

func (t *Tracker) Visible() []View

Visible returns the agents to render: those with a sidecar, working first, then idle, each group in spawn order. Never nil.

type View

type View struct {
	Name        string
	Description string
	Idle        bool
}

View is one agent as the UI renders it.

Jump to

Keyboard shortcuts

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