import { type WorkingStatus } from '../../constants.js'; import type { EventBusService } from '../event-bus/event-bus.service.js'; /** * Team Working Status File Structure * Tracks ONLY workingStatus (idle vs in_progress) based on terminal activity * agentStatus is now managed by AgentHeartbeatService via MCP calls */ export interface TeamWorkingStatusFile { /** Orchestrator working status */ orchestrator: { sessionName: string; workingStatus: WorkingStatus; lastActivityCheck: string; updatedAt: string; }; /** Team member working statuses indexed by sessionName */ teamMembers: Record; /** File metadata */ metadata: { lastUpdated: string; version: string; }; } /** * Told about a workingStatus change the moment a poll observes it. * * Unlike the `agent:busy` event — held back until the agent has been busy * for MIN_BUSY_DURATION_MS and so never published for a turn shorter than * one poll interval — this fires on every observed change. */ export type WorkingStatusListener = (sessionName: string, status: WorkingStatus, previous: WorkingStatus | null) => void; /** * Activity Monitor Service - NEW ARCHITECTURE * * Responsibilities: * - Track ONLY workingStatus (idle vs in_progress) based on terminal activity * - Create and manage teamWorkingStatus.json file * - Integrate with AgentHeartbeatService for stale agent detection * - Remove ALL agentStatus management (now owned by AgentHeartbeatService) * * Key Changes: * - No more agentStatus updates to teams.json * - Simple activity detection: output changed = in_progress, else = idle * - Integration with stale detection (30-minute threshold) * - Separate teamWorkingStatus.json file for working statuses */ export declare class ActivityMonitorService { private static instance; private logger; private storageService; private _sessionBackend; private agentHeartbeatService; private intervalId; private readonly POLLING_INTERVAL; private lastTerminalOutputs; private readonly MAX_OUTPUT_SIZE; private readonly ACTIVITY_CHECK_TIMEOUT; private lastCleanup; private crewlyHome; private teamWorkingStatusFile; private eventBusService; /** Tracks when each session entered in_progress (epoch ms) */ private stuckCommandDetector; private busyTransitionTimestamps; /** Tracks which sessions have had their agent:busy event emitted */ private busyEventEmitted; /** Latest workingStatus seen per session, from the most recent poll (in memory) */ private observedStatus; /** Callbacks told about every observed workingStatus change, undelayed */ private statusListeners; /** Tracks last recorded token counts per session to avoid duplicate recording */ private lastRecordedTokens; /** Cached tokenTracking setting, refreshed periodically to avoid async reads in hot path */ private tokenTrackingEnabled; private tokenTrackingLastCheck; /** * Set once the waiting_on_human escalations left open by the previous run * have been checked against this run's first full poll (#851). */ private openWaitingEscalationsReconciled; /** * Whether the runtime itself reports the session mid-turn (hooks / * transcript). A silent screen is not idle while it says so: long tool * calls print nothing (2026-10-02, Eve; specs/2026-10-02-restart-busy-and-resume.md). */ private runtimeTurnCheck; /** * Install the runtime turn check consulted before calling a silent agent idle. * * @param check - Returns true while the runtime reports a turn in progress; null removes it */ setRuntimeTurnCheck(check: ((sessionName: string) => boolean) | null): void; /** * Whether the runtime says the session is mid-turn (never throws). * * @param sessionName - Session * @returns True when the runtime reports a turn in progress */ private isRuntimeMidTurn; private constructor(); /** * Get the session backend, lazily initializing if needed. */ private getBackend; static getInstance(): ActivityMonitorService; /** * Inject the EventBusService for direct event publishing on status transitions. * * @param service - The EventBusService instance */ setEventBusService(service: EventBusService): void; /** * Build an AgentEvent for a working status transition. * * @param type - The event type ('agent:busy' or 'agent:idle') * @param timestamp - ISO timestamp for the event * @param identity - Agent identity fields (team/member/session) * @param previousValue - The previous working status * @param newValue - The new working status * @returns A fully-formed AgentEvent */ private buildAgentEvent; /** * Subscribe to observed workingStatus changes (idle ↔ in_progress). * * @param listener - Called with the session, its new status and the previous one * @returns Unsubscribe function */ onWorkingStatusChange(listener: WorkingStatusListener): () => void; /** * The workingStatus the latest poll saw for a session, from memory. * * @param sessionName - Agent session * @returns The status, or null when no poll has looked at it yet */ getObservedWorkingStatus(sessionName: string): WorkingStatus | null; /** * Remember what a poll saw and tell listeners when it is a change. * * @param sessionName - Agent session * @param status - Status observed now * @param previous - Status recorded before this poll (null when none) */ private observeStatus; /** * Handle duration-gated event emission for a session status transition. * Suppresses spurious idle→busy→idle cycles by requiring a minimum * busy duration (MIN_BUSY_DURATION_MS) before emitting events. * * @param key - Unique key for tracking (e.g. 'orchestrator' or session name) * @param newStatus - The new working status * @param previousStatus - The previous working status * @param statusChanged - Whether the status actually changed this poll * @param identity - Agent identity fields for building the event * @param now - ISO timestamp for the event */ private handleDurationGatedEmission; /** * Compute the waiting_on_human verdict for one agent and act on a change. * * Entering the state: records it in the attention registry (read by the * reconciler), publishes `agent:waiting_on_human`, and opens an * escalation in the owner's queue (GET /api/escalations, which * crewly-mobile polls, plus a Slack notice). Leaving it: the reverse. * Screen text is never logged, only rule names. * * @param backend - Session backend to read screen and title from * @param identity - Agent identity for the event * @param now - ISO timestamp of this poll */ private evaluateAttention; /** * Leave the waiting_on_human state for a session, if it was in it. * * `!cleared` also covers "the registry never knew this session was * waiting": the normal case for an agent that was never blocked, and also * the case right after a restart when the owner answered the prompt while * the backend was down. The escalation such a restart leaves open is closed * by {@link reconcileOpenWaitingEscalations}, once per run, rather than by * reading the escalation list on every poll of every agent here (#851). * * @param sessionName - Agent session * @param identity - Agent identity for the event * @param now - ISO timestamp of this poll */ private clearAttention; /** * Close the `agent_waiting_on_human` escalations that are still open from * before a restart although the prompt is gone. * * The attention registry is in memory. When the owner answers a prompt while * the backend is down, the registry comes back empty, so `clearAttention` * finds nothing to clear and never closes the durable escalation; it stayed * in the owner's queue (GET /api/escalations, crewly-mobile) indefinitely * (#851). This runs once, after the first poll of this run has re-learned * every live prompt: an open escalation whose session that poll checked and * found not waiting, or whose session no longer belongs to any member, is * resolved. Escalations for sessions the poll could not check stay open and * are retried on the next poll. Reading the escalation list once per run * keeps the per-poll path free of storage reads. * * @param attentionChecked - Sessions whose attention state this poll established * @param memberSessions - Every session bound to a team member */ private reconcileOpenWaitingEscalations; startPolling(): void; stopPolling(): void; private performActivityCheck; /** * NEW ARCHITECTURE: Simplified activity checking * * This method now: * 1. Detects stale agents via AgentHeartbeatService (30-minute threshold) * 2. Checks terminal activity for working status (ONLY) * 3. Updates teamWorkingStatus.json (separate from teams.json) * 4. Removes ALL agentStatus logic (handled by AgentHeartbeatService) */ private performActivityCheckInternal; /** * Load teamWorkingStatus.json file with proper initialization */ private loadTeamWorkingStatusFile; /** * Save teamWorkingStatus.json file with atomic write */ private saveTeamWorkingStatusFile; /** * Create default teamWorkingStatus.json structure */ private createDefaultTeamWorkingStatusFile; /** * Cleanup old terminal outputs and perform garbage collection */ private performPeriodicCleanup; /** * Attempt to parse and record token usage from PTY terminal output. * * Only records when token tracking is enabled in settings and when the * parsed token counts differ from the last recorded values (to avoid * duplicate recording from the same output being captured multiple times). * * @param sessionName - Agent session name * @param output - Captured terminal output * @param runtimeType - Runtime type hint for parser selection */ private tryRecordPtyTokenUsage; /** * Send Escape to an antigravity session stuck on a finished "Running command..." spinner. * * @param backend - Session backend * @param sessionName - Antigravity session */ private checkStuckAntigravityCommand; /** * Get terminal output with size limits for activity detection */ private getTerminalOutput; isRunning(): boolean; getPollingInterval(): number; /** * Get current team working status data * Useful for external services that need to check working statuses */ getTeamWorkingStatus(): Promise; /** * Get working status for a specific session */ getWorkingStatusForSession(sessionName: string): Promise; } //# sourceMappingURL=activity-monitor.service.d.ts.map