|
| 1 | +/** |
| 2 | + * `SubagentRosterTracker` — accumulates the per-session roster of live |
| 3 | + * subagent tasks so a reconnecting client can rebuild swarm cards from the |
| 4 | + * session snapshot. The refresh flow subscribes at the snapshot watermark, so |
| 5 | + * earlier `subagent.spawned` events — the only carriers of the swarm identity |
| 6 | + * metadata — are never replayed to it. |
| 7 | + * |
| 8 | + * Ported from v1 (`packages/server/src/services/gateway/subagentRosterTracker.ts`), |
| 9 | + * with two adaptations: a swarm member's own `turn.ended` never clears the |
| 10 | + * roster (every agent's events flow through the same per-session dispatch |
| 11 | + * queue here, unlike v1's firehose), and the main agent's `turn.ended` does |
| 12 | + * not clear it either — the swarm result is only queued for the async wire |
| 13 | + * append at that point, so clearing there would open a window where a |
| 14 | + * reconnecting client sees neither the roster nor the transcript result. |
| 15 | + * |
| 16 | + * Without this roster a mid-swarm page refresh loses the swarm card's member |
| 17 | + * list: REST `/tasks` only serves the main agent's background-task store |
| 18 | + * (foreground swarm subagents never persist there), and later `subagent.*` |
| 19 | + * events carry only the `subagentId`, so the identity metadata |
| 20 | + * (`parentToolCallId` / `swarmIndex` / `description`) is unrecoverable until |
| 21 | + * the swarm's `<agent_swarm_result>` tool output lands. |
| 22 | + * |
| 23 | + * Owned by the `SessionEventBroadcaster` and updated INSIDE its per-session |
| 24 | + * dispatch queue — same pattern as `InFlightTurnTracker`, keeping the roster, |
| 25 | + * the journal watermark, and the fan-out order mutually consistent. |
| 26 | + * |
| 27 | + * Lifetime: the roster is dropped when the main agent starts its NEXT turn — |
| 28 | + * the previous turn's result record was queued for the async wire append |
| 29 | + * before `turn.ended`, so by then it is durable in practice and the |
| 30 | + * transcript takes over as the restore source (a queued/cron follow-up turn |
| 31 | + * can still start inside the ms-scale flush gap; that window self-heals on |
| 32 | + * the next refresh). If the main turn |
| 33 | + * aborts (cancelled / failed / blocked), still-live entries are finalized as |
| 34 | + * failed at `turn.ended` instead: the swarm dies with the turn and the abort |
| 35 | + * path suppresses the members' own `subagent.failed` events. Background |
| 36 | + * subagents (`run_in_background`) are excluded by design: they persist in the |
| 37 | + * background-task store and are served by REST `/tasks`, so listing them here |
| 38 | + * would duplicate the row after a refresh. |
| 39 | + */ |
| 40 | + |
| 41 | +import type { Event, SnapshotSubagent } from '@moonshot-ai/protocol'; |
| 42 | + |
| 43 | +const MAIN_AGENT_ID = 'main'; |
| 44 | + |
| 45 | +export class SubagentRosterTracker { |
| 46 | + private readonly bySession = new Map<string, Map<string, SnapshotSubagent>>(); |
| 47 | + |
| 48 | + apply(sessionId: string, event: Event): void { |
| 49 | + switch (event.type) { |
| 50 | + case 'subagent.spawned': { |
| 51 | + // Background subagents persist in the main agent's background-task |
| 52 | + // store and come back through REST `/tasks` after a refresh (keyed by |
| 53 | + // task id) — tracking them here too would duplicate the row (keyed by |
| 54 | + // agent id) and mis-target cancel/detail actions. The roster exists |
| 55 | + // for the foreground/live-only subagents REST cannot serve. |
| 56 | + if (event.runInBackground === true) return; |
| 57 | + let roster = this.bySession.get(sessionId); |
| 58 | + if (!roster) { |
| 59 | + roster = new Map(); |
| 60 | + this.bySession.set(sessionId, roster); |
| 61 | + } |
| 62 | + roster.set(event.subagentId, { |
| 63 | + id: event.subagentId, |
| 64 | + session_id: sessionId, |
| 65 | + kind: 'subagent', |
| 66 | + description: event.description ?? event.subagentName ?? 'Sub Agent', |
| 67 | + status: 'running', |
| 68 | + subagent_phase: 'queued', |
| 69 | + subagent_type: event.subagentName, |
| 70 | + parent_tool_call_id: event.parentToolCallId === '' ? undefined : event.parentToolCallId, |
| 71 | + swarm_index: event.swarmIndex, |
| 72 | + run_in_background: event.runInBackground, |
| 73 | + created_at: new Date().toISOString(), |
| 74 | + }); |
| 75 | + return; |
| 76 | + } |
| 77 | + case 'subagent.started': { |
| 78 | + const entry = this.bySession.get(sessionId)?.get(event.subagentId); |
| 79 | + if (!entry) return; |
| 80 | + entry.subagent_phase = 'working'; |
| 81 | + entry.suspended_reason = undefined; |
| 82 | + // Keep an existing started_at: a resumed (previously suspended) |
| 83 | + // subagent re-fires `subagent.started`. |
| 84 | + entry.started_at ??= new Date().toISOString(); |
| 85 | + return; |
| 86 | + } |
| 87 | + case 'subagent.suspended': { |
| 88 | + const entry = this.bySession.get(sessionId)?.get(event.subagentId); |
| 89 | + if (!entry) return; |
| 90 | + entry.subagent_phase = 'suspended'; |
| 91 | + entry.suspended_reason = event.reason; |
| 92 | + return; |
| 93 | + } |
| 94 | + case 'subagent.completed': { |
| 95 | + const entry = this.bySession.get(sessionId)?.get(event.subagentId); |
| 96 | + if (!entry) return; |
| 97 | + entry.subagent_phase = 'completed'; |
| 98 | + entry.status = 'completed'; |
| 99 | + entry.completed_at = new Date().toISOString(); |
| 100 | + entry.output_preview = event.resultSummary; |
| 101 | + return; |
| 102 | + } |
| 103 | + case 'subagent.failed': { |
| 104 | + const entry = this.bySession.get(sessionId)?.get(event.subagentId); |
| 105 | + if (!entry) return; |
| 106 | + entry.subagent_phase = 'failed'; |
| 107 | + entry.status = 'failed'; |
| 108 | + entry.completed_at = new Date().toISOString(); |
| 109 | + entry.output_preview = event.error; |
| 110 | + return; |
| 111 | + } |
| 112 | + case 'task.started': { |
| 113 | + // A foreground subagent that detaches (Ctrl+B / timeout) re-enters as |
| 114 | + // a detached background task served by REST `/tasks` under a new task |
| 115 | + // id — drop its roster entry so a refresh doesn't seed both the roster |
| 116 | + // row (agent id) and the REST row (task id). Registration of a |
| 117 | + // background spawn emits the same event, but those were never tracked |
| 118 | + // here, so the delete is a no-op for them. |
| 119 | + const info = event.info; |
| 120 | + if (info.kind === 'agent' && info.detached === true && info.agentId !== undefined) { |
| 121 | + this.bySession.get(sessionId)?.delete(info.agentId); |
| 122 | + } |
| 123 | + return; |
| 124 | + } |
| 125 | + case 'turn.ended': { |
| 126 | + if (event.agentId !== MAIN_AGENT_ID) return; |
| 127 | + const roster = this.bySession.get(sessionId); |
| 128 | + if (roster === undefined || event.reason === 'completed') return; |
| 129 | + // Aborted main turn (cancelled / failed / blocked): the swarm dies |
| 130 | + // with it, and the abort path suppresses the members' own |
| 131 | + // `subagent.failed` events — finalize any still-live entries here so a |
| 132 | + // refresh doesn't seed phantom `running` subagents that no later |
| 133 | + // lifecycle event would correct. The roster itself stays until the |
| 134 | + // next main `turn.started`, same as the completed path. |
| 135 | + for (const entry of roster.values()) { |
| 136 | + if (entry.status !== 'running') continue; |
| 137 | + entry.status = 'failed'; |
| 138 | + entry.subagent_phase = 'failed'; |
| 139 | + entry.completed_at = new Date().toISOString(); |
| 140 | + entry.output_preview ??= `Main turn ${event.reason}`; |
| 141 | + } |
| 142 | + return; |
| 143 | + } |
| 144 | + case 'turn.started': { |
| 145 | + // Settle the roster when the main agent starts a NEW turn. The result |
| 146 | + // record is queued for the async wire append before `turn.ended`, so |
| 147 | + // by the next turn it is durable in practice; a queued/cron follow-up |
| 148 | + // can still start inside the flush gap, but that window is ms-scale |
| 149 | + // and self-heals on the next refresh once the flush lands. (Fully |
| 150 | + // closing it needs the snapshot reader to read through the agent |
| 151 | + // append log — deliberately left out of this change.) A subagent's |
| 152 | + // own turn boundaries must never drop the roster mid-swarm. |
| 153 | + if (event.agentId === MAIN_AGENT_ID) { |
| 154 | + this.bySession.delete(sessionId); |
| 155 | + } |
| 156 | + return; |
| 157 | + } |
| 158 | + default: |
| 159 | + return; |
| 160 | + } |
| 161 | + } |
| 162 | + |
| 163 | + /** Fresh copies — callers must not mutate the tracked entries. */ |
| 164 | + get(sessionId: string): SnapshotSubagent[] { |
| 165 | + const roster = this.bySession.get(sessionId); |
| 166 | + if (!roster) return []; |
| 167 | + return Array.from(roster.values(), (entry) => ({ ...entry })); |
| 168 | + } |
| 169 | + |
| 170 | + clear(sessionId: string): void { |
| 171 | + this.bySession.delete(sessionId); |
| 172 | + } |
| 173 | +} |
0 commit comments