2026-02-12 08:34:51 +01:00
|
|
|
/**
|
|
|
|
|
* @fileoverview Agent Teams Watcher
|
|
|
|
|
*
|
|
|
|
|
* Polls ~/.claude/teams/ and ~/.claude/tasks/ for agent team activity.
|
|
|
|
|
* Matches teams to Claudeman sessions via leadSessionId and emits
|
|
|
|
|
* events for UI updates and team-aware idle detection.
|
|
|
|
|
*
|
|
|
|
|
* @module team-watcher
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
import { EventEmitter } from 'node:events';
|
2026-02-12 18:26:16 +01:00
|
|
|
import { readdir, readFile, stat } from 'node:fs/promises';
|
2026-02-12 08:34:51 +01:00
|
|
|
import { homedir } from 'node:os';
|
|
|
|
|
import { join } from 'node:path';
|
|
|
|
|
|
2026-02-12 13:44:07 +01:00
|
|
|
import type { TeamConfig, TeamMember, TeamTask, InboxMessage } from './types.js';
|
2026-02-12 08:34:51 +01:00
|
|
|
import { LRUMap } from './utils/lru-map.js';
|
|
|
|
|
|
|
|
|
|
// ========== Constants ==========
|
|
|
|
|
|
|
|
|
|
const POLL_INTERVAL_MS = 3000;
|
|
|
|
|
const MAX_CACHED_TEAMS = 50;
|
|
|
|
|
const MAX_CACHED_TASKS = 200;
|
|
|
|
|
|
|
|
|
|
// ========== TeamWatcher Class ==========
|
|
|
|
|
|
|
|
|
|
export class TeamWatcher extends EventEmitter {
|
|
|
|
|
private teamsDir: string;
|
|
|
|
|
private tasksDir: string;
|
|
|
|
|
private pollTimer: NodeJS.Timeout | null = null;
|
|
|
|
|
private teams: LRUMap<string, TeamConfig> = new LRUMap({ maxSize: MAX_CACHED_TEAMS });
|
|
|
|
|
private teamTasks: LRUMap<string, TeamTask[]> = new LRUMap({ maxSize: MAX_CACHED_TASKS });
|
|
|
|
|
private inboxCache: LRUMap<string, InboxMessage[]> = new LRUMap({ maxSize: MAX_CACHED_TASKS });
|
|
|
|
|
// Track config mtimes to avoid re-reading unchanged files
|
|
|
|
|
private configMtimes: Map<string, number> = new Map();
|
2026-02-12 13:44:07 +01:00
|
|
|
private taskMtimes: Map<string, string> = new Map();
|
2026-02-12 08:34:51 +01:00
|
|
|
private inboxMtimes: Map<string, number> = new Map();
|
|
|
|
|
|
|
|
|
|
constructor(teamsDir?: string, tasksDir?: string) {
|
|
|
|
|
super();
|
|
|
|
|
const claudeHome = join(homedir(), '.claude');
|
|
|
|
|
this.teamsDir = teamsDir || join(claudeHome, 'teams');
|
|
|
|
|
this.tasksDir = tasksDir || join(claudeHome, 'tasks');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
start(): void {
|
|
|
|
|
if (this.pollTimer) return;
|
|
|
|
|
this.poll();
|
|
|
|
|
this.pollTimer = setInterval(() => this.poll(), POLL_INTERVAL_MS);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
stop(): void {
|
|
|
|
|
if (this.pollTimer) {
|
|
|
|
|
clearInterval(this.pollTimer);
|
|
|
|
|
this.pollTimer = null;
|
|
|
|
|
}
|
|
|
|
|
this.teams.clear();
|
|
|
|
|
this.teamTasks.clear();
|
|
|
|
|
this.inboxCache.clear();
|
|
|
|
|
this.configMtimes.clear();
|
|
|
|
|
this.taskMtimes.clear();
|
|
|
|
|
this.inboxMtimes.clear();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Get all discovered teams */
|
|
|
|
|
getTeams(): TeamConfig[] {
|
|
|
|
|
return Array.from(this.teams.values());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Get team associated with a Claudeman session (matched by leadSessionId) */
|
|
|
|
|
getTeamForSession(sessionId: string): TeamConfig | undefined {
|
|
|
|
|
for (const team of this.teams.values()) {
|
|
|
|
|
if (team.leadSessionId === sessionId) {
|
|
|
|
|
return team;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return undefined;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Get tasks for a team (excluding internal tasks) */
|
|
|
|
|
getTeamTasks(teamName: string): TeamTask[] {
|
|
|
|
|
const tasks = this.teamTasks.get(teamName);
|
|
|
|
|
if (!tasks) return [];
|
|
|
|
|
return tasks.filter(t => !t.metadata?._internal);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Count active (non-completed) tasks for a team */
|
|
|
|
|
getActiveTaskCount(teamName: string): number {
|
|
|
|
|
const tasks = this.getTeamTasks(teamName);
|
|
|
|
|
return tasks.filter(t => t.status !== 'completed').length;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Get inbox messages for a team member (or all members) */
|
|
|
|
|
getInboxMessages(teamName: string, member?: string): InboxMessage[] {
|
|
|
|
|
if (member) {
|
|
|
|
|
const key = `${teamName}/${member}`;
|
|
|
|
|
return this.inboxCache.get(key) || [];
|
|
|
|
|
}
|
|
|
|
|
// Return all messages for team
|
|
|
|
|
const messages: InboxMessage[] = [];
|
|
|
|
|
for (const [key, msgs] of this.inboxCache.entries()) {
|
|
|
|
|
if (key.startsWith(`${teamName}/`)) {
|
|
|
|
|
messages.push(...msgs);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return messages.sort((a, b) =>
|
|
|
|
|
new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime()
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Check if a session has active teammates (for idle detection) */
|
|
|
|
|
hasActiveTeammates(sessionId: string): boolean {
|
|
|
|
|
const team = this.getTeamForSession(sessionId);
|
|
|
|
|
if (!team) return false;
|
|
|
|
|
|
|
|
|
|
// Check if any non-lead members exist (they are active by definition while present)
|
|
|
|
|
const teammates = team.members.filter(m => m.agentType !== 'team-lead');
|
|
|
|
|
if (teammates.length === 0) return false;
|
|
|
|
|
|
|
|
|
|
// Check if team has active (non-completed) tasks
|
|
|
|
|
const activeTasks = this.getActiveTaskCount(team.name);
|
|
|
|
|
return activeTasks > 0;
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-12 13:44:07 +01:00
|
|
|
/** Get teammates that have real tmux panes (not in-process) */
|
|
|
|
|
getTmuxPaneTeammates(teamName: string): Array<TeamMember & { tmuxPaneId: string }> {
|
|
|
|
|
const team = this.teams.get(teamName);
|
|
|
|
|
if (!team) return [];
|
|
|
|
|
|
|
|
|
|
return team.members
|
|
|
|
|
.filter((m): m is TeamMember & { tmuxPaneId: string } =>
|
|
|
|
|
m.agentType !== 'team-lead' &&
|
|
|
|
|
!!m.tmuxPaneId &&
|
|
|
|
|
m.tmuxPaneId !== 'in-process'
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-12 08:34:51 +01:00
|
|
|
/** Get count of active teammates for a session */
|
|
|
|
|
getActiveTeammateCount(sessionId: string): number {
|
|
|
|
|
const team = this.getTeamForSession(sessionId);
|
|
|
|
|
if (!team) return 0;
|
|
|
|
|
return team.members.filter(m => m.agentType !== 'team-lead').length;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ========== Private Methods ==========
|
|
|
|
|
|
|
|
|
|
private poll(): void {
|
2026-02-12 18:26:16 +01:00
|
|
|
// Run async poll — errors are caught internally per method
|
|
|
|
|
this.pollAsync().catch(() => {
|
2026-02-12 08:34:51 +01:00
|
|
|
// Don't crash on polling errors — filesystem may be temporarily unavailable
|
2026-02-12 18:26:16 +01:00
|
|
|
});
|
2026-02-12 08:34:51 +01:00
|
|
|
}
|
|
|
|
|
|
2026-02-12 18:26:16 +01:00
|
|
|
private async pollAsync(): Promise<void> {
|
|
|
|
|
await this.pollTeams();
|
|
|
|
|
await this.pollTasks();
|
|
|
|
|
await this.pollInboxes();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async pollTeams(): Promise<void> {
|
2026-02-12 08:34:51 +01:00
|
|
|
let entries: string[];
|
|
|
|
|
try {
|
2026-02-12 18:26:16 +01:00
|
|
|
entries = await readdir(this.teamsDir);
|
2026-02-12 08:34:51 +01:00
|
|
|
} catch {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const currentTeamNames = new Set<string>();
|
|
|
|
|
|
|
|
|
|
for (const entry of entries) {
|
|
|
|
|
const configPath = join(this.teamsDir, entry, 'config.json');
|
|
|
|
|
|
|
|
|
|
currentTeamNames.add(entry);
|
|
|
|
|
|
2026-02-12 18:26:16 +01:00
|
|
|
// Check mtime to skip unchanged configs
|
2026-02-12 13:44:07 +01:00
|
|
|
let mtime: number;
|
2026-02-12 08:34:51 +01:00
|
|
|
try {
|
2026-02-12 18:26:16 +01:00
|
|
|
mtime = (await stat(configPath)).mtimeMs;
|
2026-02-12 08:34:51 +01:00
|
|
|
} catch {
|
2026-02-12 13:44:07 +01:00
|
|
|
// File doesn't exist or was removed between readdir and stat
|
2026-02-12 08:34:51 +01:00
|
|
|
continue;
|
|
|
|
|
}
|
2026-02-12 13:44:07 +01:00
|
|
|
if (this.configMtimes.get(entry) === mtime) continue;
|
|
|
|
|
this.configMtimes.set(entry, mtime);
|
2026-02-12 08:34:51 +01:00
|
|
|
|
|
|
|
|
// Skip if locked
|
2026-02-12 18:26:16 +01:00
|
|
|
if (await this.isLocked(join(this.teamsDir, entry, 'config.json'))) continue;
|
2026-02-12 08:34:51 +01:00
|
|
|
|
2026-02-12 18:26:16 +01:00
|
|
|
const config = await this.readJson<TeamConfig>(configPath);
|
2026-02-12 13:44:07 +01:00
|
|
|
if (!config || !config.name || !config.leadSessionId || !Array.isArray(config.members)) continue;
|
2026-02-12 08:34:51 +01:00
|
|
|
|
|
|
|
|
const existing = this.teams.get(entry);
|
|
|
|
|
this.teams.set(entry, config);
|
|
|
|
|
|
|
|
|
|
if (existing) {
|
|
|
|
|
this.emit('teamUpdated', config);
|
|
|
|
|
} else {
|
|
|
|
|
this.emit('teamCreated', config);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Detect removed teams
|
|
|
|
|
for (const name of Array.from(this.teams.keys())) {
|
|
|
|
|
if (!currentTeamNames.has(name)) {
|
|
|
|
|
const removed = this.teams.get(name);
|
|
|
|
|
this.teams.delete(name);
|
|
|
|
|
this.configMtimes.delete(name);
|
2026-02-12 18:26:16 +01:00
|
|
|
// Prune stale mtime entries for removed teams
|
|
|
|
|
this.taskMtimes.delete(name);
|
|
|
|
|
for (const key of Array.from(this.inboxMtimes.keys())) {
|
|
|
|
|
if (key.startsWith(`${name}/`)) {
|
|
|
|
|
this.inboxMtimes.delete(key);
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-02-12 08:34:51 +01:00
|
|
|
if (removed) {
|
|
|
|
|
this.emit('teamRemoved', removed);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-12 18:26:16 +01:00
|
|
|
private async pollTasks(): Promise<void> {
|
2026-02-12 08:34:51 +01:00
|
|
|
let teamDirs: string[];
|
|
|
|
|
try {
|
2026-02-12 18:26:16 +01:00
|
|
|
teamDirs = await readdir(this.tasksDir);
|
2026-02-12 08:34:51 +01:00
|
|
|
} catch {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
for (const teamName of teamDirs) {
|
|
|
|
|
const teamTaskDir = join(this.tasksDir, teamName);
|
|
|
|
|
let taskFiles: string[];
|
|
|
|
|
try {
|
2026-02-12 18:26:16 +01:00
|
|
|
taskFiles = (await readdir(teamTaskDir)).filter(f => f.endsWith('.json') && f !== '.lock');
|
2026-02-12 08:34:51 +01:00
|
|
|
} catch {
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-12 13:44:07 +01:00
|
|
|
// Check combined mtime for all task files (use count:max:sum to avoid collisions)
|
2026-02-12 08:34:51 +01:00
|
|
|
const mtimeKey = teamName;
|
2026-02-12 13:44:07 +01:00
|
|
|
let mtimeSum = 0;
|
|
|
|
|
let mtimeMax = 0;
|
|
|
|
|
let mtimeCount = 0;
|
2026-02-12 08:34:51 +01:00
|
|
|
for (const f of taskFiles) {
|
|
|
|
|
try {
|
2026-02-12 18:26:16 +01:00
|
|
|
const mt = (await stat(join(teamTaskDir, f))).mtimeMs;
|
2026-02-12 13:44:07 +01:00
|
|
|
mtimeSum += mt;
|
|
|
|
|
if (mt > mtimeMax) mtimeMax = mt;
|
|
|
|
|
mtimeCount++;
|
2026-02-12 08:34:51 +01:00
|
|
|
} catch {
|
|
|
|
|
// File may have been deleted between readdir and stat
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-02-12 13:44:07 +01:00
|
|
|
const combinedMtime = `${mtimeCount}:${mtimeMax}:${mtimeSum}`;
|
2026-02-12 08:34:51 +01:00
|
|
|
if (this.taskMtimes.get(mtimeKey) === combinedMtime) continue;
|
|
|
|
|
this.taskMtimes.set(mtimeKey, combinedMtime);
|
|
|
|
|
|
|
|
|
|
// Skip if locked
|
2026-02-12 18:26:16 +01:00
|
|
|
if (await this.isLocked(join(teamTaskDir, '.lock'))) continue;
|
2026-02-12 08:34:51 +01:00
|
|
|
|
|
|
|
|
const tasks: TeamTask[] = [];
|
|
|
|
|
for (const f of taskFiles) {
|
2026-02-12 18:26:16 +01:00
|
|
|
const task = await this.readJson<TeamTask>(join(teamTaskDir, f));
|
2026-02-12 08:34:51 +01:00
|
|
|
if (task && task.id) {
|
|
|
|
|
tasks.push(task);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
this.teamTasks.set(teamName, tasks);
|
|
|
|
|
this.emit('taskUpdated', { teamName, tasks });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-12 18:26:16 +01:00
|
|
|
private async pollInboxes(): Promise<void> {
|
2026-02-12 08:34:51 +01:00
|
|
|
// Inbox files live under ~/.claude/teams/{name}/inboxes/
|
|
|
|
|
for (const [teamName] of this.teams.entries()) {
|
|
|
|
|
const inboxDir = join(this.teamsDir, teamName, 'inboxes');
|
|
|
|
|
|
|
|
|
|
let inboxFiles: string[];
|
|
|
|
|
try {
|
2026-02-12 18:26:16 +01:00
|
|
|
inboxFiles = (await readdir(inboxDir)).filter(f => f.endsWith('.json'));
|
2026-02-12 08:34:51 +01:00
|
|
|
} catch {
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
for (const f of inboxFiles) {
|
|
|
|
|
const filePath = join(inboxDir, f);
|
|
|
|
|
const memberName = f.replace('.json', '');
|
|
|
|
|
const cacheKey = `${teamName}/${memberName}`;
|
|
|
|
|
|
|
|
|
|
// Check mtime
|
|
|
|
|
try {
|
2026-02-12 18:26:16 +01:00
|
|
|
const mtime = (await stat(filePath)).mtimeMs;
|
2026-02-12 08:34:51 +01:00
|
|
|
if (this.inboxMtimes.get(cacheKey) === mtime) continue;
|
|
|
|
|
this.inboxMtimes.set(cacheKey, mtime);
|
|
|
|
|
} catch {
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Skip if locked
|
2026-02-12 18:26:16 +01:00
|
|
|
if (await this.isLocked(filePath)) continue;
|
2026-02-12 08:34:51 +01:00
|
|
|
|
2026-02-12 18:26:16 +01:00
|
|
|
const messages = await this.readJson<InboxMessage[]>(filePath);
|
2026-02-12 08:34:51 +01:00
|
|
|
if (!Array.isArray(messages)) continue;
|
|
|
|
|
|
|
|
|
|
const previous = this.inboxCache.get(cacheKey);
|
|
|
|
|
this.inboxCache.set(cacheKey, messages);
|
|
|
|
|
|
|
|
|
|
// Emit new messages (ones not in previous cache)
|
|
|
|
|
const prevCount = previous?.length || 0;
|
|
|
|
|
if (messages.length > prevCount) {
|
|
|
|
|
for (let i = prevCount; i < messages.length; i++) {
|
|
|
|
|
this.emit('inboxMessage', { teamName, member: memberName, message: messages[i] });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Check for directory-based lock (mkdir atomic locking) */
|
2026-02-12 18:26:16 +01:00
|
|
|
private async isLocked(path: string): Promise<boolean> {
|
2026-02-12 08:34:51 +01:00
|
|
|
const lockDir = `${path}.lock`;
|
|
|
|
|
try {
|
2026-02-12 18:26:16 +01:00
|
|
|
return (await stat(lockDir)).isDirectory();
|
2026-02-12 08:34:51 +01:00
|
|
|
} catch {
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-12 18:26:16 +01:00
|
|
|
private async readJson<T>(filePath: string): Promise<T | null> {
|
2026-02-12 08:34:51 +01:00
|
|
|
try {
|
2026-02-12 18:26:16 +01:00
|
|
|
const content = await readFile(filePath, 'utf-8');
|
2026-02-12 08:34:51 +01:00
|
|
|
return JSON.parse(content) as T;
|
|
|
|
|
} catch {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|