SLOPSHOPPER

agents

Single source of the session's agents: collects them and publishes them as state other mods read

agents
v0.1.0no licenseupdated 2026-10-15djavrell/dotfile/claude/mods/agents
A shopper browsing a rack in a slop shop
README

agents

Single source of the session's agents. The mod collects every agent the session spawns and keeps the list as state (agents.list, oldest first), so other mods can show or react to agents without tracking them on their own.

It draws nothing itself: panes, bands and toasts read that state. Another mod gets it by listing agents under its dependencies. The session pane is the current consumer.

Example

One agent of the list (AgentEntry in types/index.d.ts; parentId, model, background, the times and endReason are optional):

{
  "id": "a1b2c3", "type": "Explore", "description": "find the config loader", "status": "completed",
  "model": "claude-haiku-4-5", "background": false, "stepsStarted": 4, "stepsDone": 4,
  "startedAt": 1760000000000, "endedAt": 1760000042000, "endReason": "answer"
}
Source 3 files
hooks/register.ts 109 lines
1// Single source of the session's agents. This mod draws nothing: it collects the agents and publishes
2// them as its `list` state; the session pane (and any later band, toast or command) reads that state.
3// The atom stays in this file with its update calls (the validator wants them together); the pure
4// list operations live in lib/entries.ts.
5import { atom, update } from "claude-code";
6import type { EngineInterface, Register } from "claude-code";
7
8import { mergeListed, newEntry, patchEntry, resumed, statusOfEnd, stepStarted, upsertEntry } from "./lib/entries";
9
10const list = atom({ plugin: "agents", key: "list" } as const, []);
11
12// bumped by every list refresh: a run that is no longer the latest drops its result
13let listGeneration = 0;
14
15// first step of every agent loop, by id: the start of an agent born without a spawn (a forked skill
16// such as /code-review), which the list only shows once it spawns a child
17// ponytail: never pruned, a few numbers per session (forks for compaction and memory included)
18const firstStepAt = new Map<string, number>();
19
20async function refreshFromList($: EngineInterface) {
21  const thisGeneration = ++listGeneration;
22  const agentInfos = await $.agent.list();
23  const nowMs = await $.clock.now();
24  if (thisGeneration !== listGeneration) return;
25  const listed = agentInfos.map((agentInfo) => ({
26    id: agentInfo.id,
27    parentId: agentInfo.parentId,
28    type: agentInfo.type,
29    description: agentInfo.description,
30    status: agentInfo.status,
31    startedAt: firstStepAt.get(agentInfo.id),
32  }));
33  await update($, list, (entries) => mergeListed(entries, listed, nowMs));
34}
35
36export const register: Register = (on) => {
37  on("session.start", async ($, event, next) => {
38    void refreshFromList($).catch(() => {});
39
40    return next(event);
41  });
42
43  on("agent.spawn", async ($, event, next) => {
44    const result = await next(event);
45    const agentId = result.agentId;
46    // a resume (SendMessage, a teammate back from disk) spawns no new agent: only its end is undone;
47    // one unknown here (reloaded from disk) is added by the list refresh
48    if (agentId && event.resume) {
49      void update($, list, (entries) => patchEntry(entries, agentId, resumed)).catch(() => {});
50      void refreshFromList($).catch(() => {});
51    } else if (agentId) {
52      const startedAt = await $.clock.now();
53      const entry = newEntry({
54        id: agentId,
55        parentId: event.parentAgentId,
56        type: event.subagentType,
57        description: event.description,
58        status: "running",
59        model: result.model,
60        background: event.background,
61        startedAt,
62        workflow: event.workflow,
63      });
64      void update($, list, (entries) => upsertEntry(entries, entry)).catch(() => {});
65      void refreshFromList($).catch(() => {});
66    }
67
68    return result;
69  });
70
71  // one step = one model request; counted before it goes out and once it came back
72  on("turn.step", async function* ($, event, next) {
73    const agentId = event.agentId;
74    if (agentId && !firstStepAt.has(agentId)) firstStepAt.set(agentId, await $.clock.now());
75    if (agentId)
76      void update($, list, (entries) =>
77        patchEntry(entries, agentId, (entry) => stepStarted(entry, event.model)),
78      ).catch(() => {});
79
80    const result = yield* next(event);
81
82    if (agentId)
83      void update($, list, (entries) =>
84        patchEntry(entries, agentId, (entry) => ({ stepsDone: entry.stepsDone + 1 })),
85      ).catch(() => {});
86
87    return result;
88  });
89
90  // a subagent's run is one turn: its end is the agent's end
91  on("turn.complete", async ($, event, next) => {
92    const result = await next(event);
93    const agentId = event.agentId;
94    if (agentId) {
95      const endedAt = await $.clock.now();
96      void update($, list, (entries) =>
97        patchEntry(entries, agentId, () => ({
98          endedAt,
99          endReason: event.reason,
100          status: statusOfEnd(event.reason),
101        })),
102      ).catch(() => {});
103      void refreshFromList($).catch(() => {});
104    }
105
106    return result;
107  });
108};
109
hooks/lib/entries.ts 80 lines
1import type { AgentEntry } from "../../types";
2
3// ponytail: keeps the last 30 agents; older ones drop off the list
4export const MAX_ENTRIES = 30;
5
6// what $.agent.list() says about one agent
7export type ListedAgent = {
8  id: string;
9  parentId?: string;
10  type: string;
11  description: string;
12  status: string;
13  // the engine gives no start: its first step, when this mod saw it (not across a reload)
14  startedAt?: number;
15};
16
17export const newEntry = (
18  fields: Omit<AgentEntry, "stepsStarted" | "stepsDone">,
19): AgentEntry => ({ ...fields, stepsStarted: 0, stepsDone: 0 });
20
21// adds an agent, or replaces the fields given on the one already there
22export const upsertEntry = (
23  entries: readonly AgentEntry[],
24  entry: AgentEntry,
25): AgentEntry[] => {
26  const existing = entries.find((candidate) => candidate.id === entry.id);
27  if (!existing) return [...entries, entry].slice(-MAX_ENTRIES);
28  return entries.map((candidate) =>
29    candidate.id === entry.id ? { ...candidate, ...entry, stepsStarted: candidate.stepsStarted, stepsDone: candidate.stepsDone } : candidate,
30  );
31};
32
33// changes an agent already known; ids never seen (the engine's own forks: compaction, memory) are ignored
34export const patchEntry = (
35  entries: readonly AgentEntry[],
36  agentId: string,
37  patch: (entry: AgentEntry) => Partial<AgentEntry>,
38): AgentEntry[] =>
39  entries.map((entry) => (entry.id === agentId ? { ...entry, ...patch(entry) } : entry));
40
41// the engine's list brings statuses, and agents born without a spawn (a forked skill); agents it has
42// dropped keep their last known state. A new one with no first step seen starts `nowMs`; a known one
43// only takes a seen first step, never `nowMs`: it may have ended already (after a reload), and a
44// start after its end drew a negative time
45export const mergeListed = (
46  entries: readonly AgentEntry[],
47  listed: readonly ListedAgent[],
48  nowMs: number,
49): AgentEntry[] => {
50  let merged = [...entries];
51  for (const agent of listed) {
52    const existing = merged.find((entry) => entry.id === agent.id);
53    merged = existing
54      ? patchEntry(merged, agent.id, () => ({
55          status: agent.status,
56          parentId: agent.parentId ?? existing.parentId,
57          startedAt: existing.startedAt ?? agent.startedAt,
58        }))
59      : upsertEntry(merged, newEntry({ ...agent, startedAt: agent.startedAt ?? nowMs }));
60  }
61  return merged;
62};
63
64// a finished turn's reason, as a status, until the engine's list says otherwise
65export const statusOfEnd = (reason: string) =>
66  reason === "answer" ? "completed" : reason === "aborted" ? "killed" : "failed";
67
68const FINISHED_STATUSES = new Set(["completed", "failed", "killed"]);
69
70// a known agent running again (SendMessage, a teammate woken): its start, parent and description stay
71export const resumed = (): Partial<AgentEntry> => ({ status: "running", endedAt: undefined, endReason: undefined });
72
73// a step about to go out; a finished agent stepping again was resumed with no spawn event (a teammate
74// woken in memory): running again
75export const stepStarted = (entry: AgentEntry, model: string): Partial<AgentEntry> => ({
76  stepsStarted: entry.stepsStarted + 1,
77  model,
78  ...(FINISHED_STATUSES.has(entry.status) ? resumed() : {}),
79});
80
types/index.d.ts 36 lines
1// One agent of the session as this mod publishes it. Consumers list "agents" under `dependencies`
2// in their plugin.json, import this type from "agents", and read the list with
3//   read($, atom({ plugin: "agents", key: "list" } as const, []))
4export type AgentEntry = {
5  id: string
6  // the agent that spawned it; absent when the main conversation did
7  parentId?: string
8  // the agent type it was spawned as (general-purpose, Explore, ...)
9  type: string
10  description: string
11  // pending, running, waiting, idle, completed, failed, killed
12  status: string
13  // the model it runs on, as the engine resolved it (claude-haiku-4-5-..., or an alias)
14  model?: string
15  background?: boolean
16  // $.clock.now() milliseconds
17  startedAt?: number
18  endedAt?: number
19  // why its last turn ended: answer, aborted, refusal, error
20  endReason?: string
21  // model requests (turn.step) it started, and the ones that came back
22  stepsStarted: number
23  stepsDone: number
24  // set when a Workflow run's agent() spawned it: the run (wf_...) and its 1-based place among the run's agents
25  workflow?: { runId: string; agentIndex: number }
26}
27
28declare module 'claude-code' {
29  interface PluginState {
30    agents: {
31      // spawn order, oldest first; finished agents are kept (the engine's own list drops them)
32      list: AgentEntry[]
33    }
34  }
35}
36