v0.1.94 90d877f

agent.go RawHistoryFolder

1package swarm
2
3import (
4	"context"
5	"fmt"
6	"strings"
7	"sync"
8	"time"
9)
10
11// Agent is one supervised task. Public fields are immutable after
12// Spawn; mutable state (status, activity, transcript) lives behind
13// the embedded mutex.
14type Agent struct {
15	ID      string
16	Task    string
17	Dir     string // always the host's RepoRoot; agents share its cwd.
18	Started time.Time
19
20	// Model and Provider, when non-empty, override the child
21	// subprocess's model resolution. Empty means "inherit whatever
22	// the child resolves on its own from config / env / flags" —
23	// the historical behaviour. Persisted in meta.json so Resume
24	// keeps using the same model across zot restarts.
25	Model    string
26	Provider string
27
28	// SessionID, when non-empty, scopes the agent to a particular
29	// host zot session: the dashboard only surfaces agents whose
30	// SessionID matches the active session. Empty means "unscoped"
31	// (legacy meta files from before the field existed, or agents
32	// spawned without a session context such as in tests). Set at
33	// Spawn time from Swarm.activeSession and persisted in
34	// meta.json so the scope survives restarts.
35	SessionID string
36
37	// Resuming is true when this Agent struct was built by Resume
38	// rather than Spawn. The runner consults it to decide whether
39	// to pass the original Task as a positional argv to the child:
40	// on first Spawn we want the child to run the task immediately;
41	// on Resume the task was already run last time and replaying it
42	// would produce a second turn that collides ("agent busy; send
43	// 'cancel' first") with whatever the user types next. Not
44	// persisted — every Resume sets it explicitly.
45	Resuming bool
46
47	// InboxPath is the unix socket the child agent listens on for
48	// follow-up prompts and control messages. The supervisor opens
49	// an Inbox at this path; the child opens a Listener.
50	InboxPath string
51
52	// EventLogPath is the durable JSONL event log for this agent.
53	// The runner appends every well-formed event from the child
54	// (plus lifecycle events of its own) here. /swarm open in any
55	// zot process reads from this file to replay the full history.
56	EventLogPath string
57
58	// SessionPath is the child's persistent session file. Surfaced
59	// so the dashboard / /swarm open can resume the agent later.
60	SessionPath string
61
62	// inbox is the supervisor-side socket handle. Populated by
63	// Swarm.Spawn so SendInput can route messages without each
64	// caller redialing.
65	inbox *Inbox
66
67	mu         sync.Mutex
68	status     Status
69	activity   string
70	transcript []string
71	finished   time.Time
72	lastErr    error
73
74	ctx    context.Context
75	cancel context.CancelFunc
76	runner Runner
77
78	// done closes when the run goroutine finalises the agent's
79	// status (done / failed / killed). Wait blocks on this so
80	// callers don't have to poll.
81	done chan struct{}
82}
83
84// Inbox exposes the supervisor-side socket handle. Returns nil for
85// agents without inboxes (e.g. tests using a custom Runner that
86// doesn't speak the daemon protocol).
87func (a *Agent) Inbox() *Inbox { return a.inbox }
88
89// Status returns the current high-level status. Cheap; safe from any goroutine.
90func (a *Agent) Status() Status {
91	a.mu.Lock()
92	defer a.mu.Unlock()
93	return a.status
94}
95
96// Activity returns the current one-line activity string.
97func (a *Agent) Activity() string {
98	a.mu.Lock()
99	defer a.mu.Unlock()
100	return a.activity
101}
102
103// Transcript returns a copy of the running transcript.
104func (a *Agent) Transcript() []string {
105	a.mu.Lock()
106	defer a.mu.Unlock()
107	out := make([]string, len(a.transcript))
108	copy(out, a.transcript)
109	return out
110}
111
112// Err returns the runner's terminal error, if any.
113func (a *Agent) Err() error {
114	a.mu.Lock()
115	defer a.mu.Unlock()
116	return a.lastErr
117}
118
119// Wait blocks until the agent reaches a terminal state. Used by tests
120// and by /swarm wait <id>.
121func (a *Agent) Wait() { <-a.done }
122
123func (a *Agent) setStatus(s Status) {
124	a.mu.Lock()
125	a.status = s
126	a.mu.Unlock()
127}
128
129func (a *Agent) setActivity(msg string) {
130	a.mu.Lock()
131	a.activity = strings.TrimSpace(msg)
132	a.mu.Unlock()
133}
134
135func (a *Agent) appendTranscript(chunk string) {
136	chunk = strings.TrimRight(chunk, "\n")
137	if chunk == "" {
138		return
139	}
140	a.mu.Lock()
141	for _, line := range strings.Split(chunk, "\n") {
142		a.transcript = append(a.transcript, line)
143	}
144	// Bound the transcript so dashboards don't hold gigabytes for
145	// long-running agents. 2000 lines is plenty for inspection;
146	// the durable record lives in the agent's session file.
147	const cap = 2000
148	if len(a.transcript) > cap {
149		a.transcript = a.transcript[len(a.transcript)-cap:]
150	}
151	a.mu.Unlock()
152}
153
154// newAgentID returns a short, mostly-collision-free identifier of the
155// form "<slug>-<nano>". The slug is derived from the task text so
156// dashboards stay readable; the nano suffix guarantees uniqueness
157// even when two agents are spawned in the same millisecond.
158func newAgentID(task string, now time.Time) string {
159	slug := taskSlug(task)
160	return fmt.Sprintf("%s-%d", slug, now.UnixNano()%1_000_000)
161}
162
163func taskSlug(task string) string {
164	task = strings.ToLower(task)
165	var b strings.Builder
166	dash := false
167	for _, r := range task {
168		switch {
169		case r >= 'a' && r <= 'z', r >= '0' && r <= '9':
170			b.WriteRune(r)
171			dash = false
172		default:
173			if !dash && b.Len() > 0 {
174				b.WriteByte('-')
175				dash = true
176			}
177		}
178		if b.Len() >= 24 {
179			break
180		}
181	}
182	out := strings.Trim(b.String(), "-")
183	if out == "" {
184		out = "agent"
185	}
186	return out
187}

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 1

Tags 476

↑↓ moveenter openesc close