| 1 | /** Maximum fork-chain depth resolved for one identity (cycle- and length-bounded). */ |
| 2 | export const LINEAGE_MAX_DEPTH = 32; |
| 3 | /** |
| 4 | * Official optional service access. `ctx.get` is the reflection accessor for a |
| 5 | * service a plugin does not declare in `inject`; a missing service yields |
| 6 | * `undefined` instead of a contract error, and a getter that still refuses is |
| 7 | * contained here. |
| 8 | */ |
| 9 | function optionalService(ctx, name) { |
| 10 | const get = ctx.get; |
| 11 | if (typeof get !== 'function') |
| 12 | return undefined; |
| 13 | try { |
| 14 | return get.call(ctx, name); |
| 15 | } |
| 16 | catch { |
| 17 | return undefined; |
| 18 | } |
| 19 | } |
| 20 | /** Ancestry this process already resolved for one session. */ |
| 21 | const ancestryCache = new Map(); |
| 22 | /** The live session for one id: resident agent first, then the live session store. */ |
| 23 | export function liveSession(ctx, id) { |
| 24 | const branded = id; |
| 25 | const agent = ctx.agents.get(branded); |
| 26 | if (agent !== undefined) |
| 27 | return agent.session; |
| 28 | return optionalService(ctx, 'sessions')?.get?.(branded); |
| 29 | } |
| 30 | /** Whether one session is a top-level conversation rather than a subagent child. */ |
| 31 | export function isTopLevelSession(session) { |
| 32 | return session.header.origin !== 'subagent' && (session.header.delegationDepth ?? 0) === 0; |
| 33 | } |
| 34 | /** Durable parent of one session id: the live header, else the stored header. */ |
| 35 | async function durableParent(ctx, id) { |
| 36 | const live = liveSession(ctx, id); |
| 37 | if (live !== undefined) |
| 38 | return live.header.parentSession; |
| 39 | const persistence = optionalService(ctx, 'sessionPersistence'); |
| 40 | try { |
| 41 | const snapshot = await persistence?.stat?.(id); |
| 42 | const parent = snapshot?.header?.parentSession; |
| 43 | return parent; |
| 44 | } |
| 45 | catch { |
| 46 | // Unreadable stored metadata ends this chain; authorization then fails |
| 47 | // closed on the identity the caller itself provides. |
| 48 | return undefined; |
| 49 | } |
| 50 | } |
| 51 | /** |
| 52 | * Durable ancestry of one session, nearest first. The calling session's own |
| 53 | * header supplies the first hop; later hops come from resident sessions or |
| 54 | * stored headers, so a fork resolves through sessions that are not loaded. |
| 55 | * @param ctx - the plugin context (injects `agents`). |
| 56 | * @param session - the calling session. |
| 57 | * @returns ancestor session ids, bounded by {@link LINEAGE_MAX_DEPTH}. |
| 58 | */ |
| 59 | export async function resolveAncestry(ctx, session) { |
| 60 | const ancestry = []; |
| 61 | const seen = new Set([session.id]); |
| 62 | let parent = session.header.parentSession; |
| 63 | while (parent !== undefined && ancestry.length < LINEAGE_MAX_DEPTH && !seen.has(parent)) { |
| 64 | seen.add(parent); |
| 65 | ancestry.push(parent); |
| 66 | parent = await durableParent(ctx, parent); |
| 67 | } |
| 68 | ancestryCache.set(session.id, ancestry); |
| 69 | return ancestry; |
| 70 | } |
| 71 | /** |
| 72 | * Ancestry resolvable without awaiting: the calling session's durable first |
| 73 | * hop, then resident sessions, then whatever the async resolver cached. |
| 74 | */ |
| 75 | export function sessionAncestry(ctx, session) { |
| 76 | const cached = ancestryCache.get(session.id); |
| 77 | if (cached !== undefined) |
| 78 | return cached; |
| 79 | const ancestry = []; |
| 80 | const seen = new Set([session.id]); |
| 81 | let parent = session.header.parentSession; |
| 82 | while (parent !== undefined && ancestry.length < LINEAGE_MAX_DEPTH && !seen.has(parent)) { |
| 83 | seen.add(parent); |
| 84 | ancestry.push(parent); |
| 85 | parent = liveSession(ctx, parent)?.header.parentSession; |
| 86 | } |
| 87 | return ancestry; |
| 88 | } |
| 89 | /** Resolve one session's lead identity synchronously (prompt-assembly path). */ |
| 90 | export function leadIdentityOf(ctx, session) { |
| 91 | return { |
| 92 | sessionId: session.id, |
| 93 | ancestry: sessionAncestry(ctx, session), |
| 94 | inheritsLead: isTopLevelSession(session), |
| 95 | }; |
| 96 | } |
| 97 | /** Resolve one session's lead identity durably (authorization paths). */ |
| 98 | export async function leadIdentityOfAsync(ctx, session) { |
| 99 | return { |
| 100 | sessionId: session.id, |
| 101 | ancestry: await resolveAncestry(ctx, session), |
| 102 | inheritsLead: isTopLevelSession(session), |
| 103 | }; |
| 104 | } |
| 105 | /** Whether one identity leads (or inherits the lead of) a team's recorded captain. */ |
| 106 | export function teamLeadMatch(team, lead) { |
| 107 | const members = team.members ?? []; |
| 108 | // A listed member is never a lead, retired or not: a member session is a |
| 109 | // subagent child of its captain, so its parent chain contains the captain id |
| 110 | // too, and membership revocation must never hand that session lead authority. |
| 111 | // Member participation itself stays governed by the removed filter in the |
| 112 | // team lookups. |
| 113 | if (members.some(member => member.id === lead.sessionId)) |
| 114 | return false; |
| 115 | if (team.captainSessionId === lead.sessionId) |
| 116 | return true; |
| 117 | if (!lead.inheritsLead) |
| 118 | return false; |
| 119 | // Descending from a member (a fork of one) is not lead identity either. |
| 120 | if (members.some(member => lead.ancestry.includes(member.id))) |
| 121 | return false; |
| 122 | return lead.ancestry.includes(team.captainSessionId); |
| 123 | } |
| 124 | /** |
| 125 | * Whether one live session id leads a team: the recorded captain itself, or a |
| 126 | * top-level fork descendant of it. Members never match through their parent |
| 127 | * chain, and a member's fork does not match either. |
| 128 | */ |
| 129 | export function sessionLeadsTeam(ctx, team, sessionId) { |
| 130 | if (team.members?.some(member => member.id === sessionId) === true) |
| 131 | return false; |
| 132 | if (team.captainSessionId === sessionId) |
| 133 | return true; |
| 134 | const session = liveSession(ctx, sessionId); |
| 135 | return session !== undefined && teamLeadMatch(team, leadIdentityOf(ctx, session)); |
| 136 | } |
| 137 | /** Durable {@link sessionLeadsTeam}: resolves the caller's chain through stored headers. */ |
| 138 | export async function sessionLeadsTeamAsync(ctx, team, sessionId) { |
| 139 | if (team.members?.some(member => member.id === sessionId) === true) |
| 140 | return false; |
| 141 | if (team.captainSessionId === sessionId) |
| 142 | return true; |
| 143 | const session = liveSession(ctx, sessionId); |
| 144 | return session !== undefined && teamLeadMatch(team, await leadIdentityOfAsync(ctx, session)); |
| 145 | } |
| 146 | /** |
| 147 | * Nearest live lead session of a team: the recorded captain while it is |
| 148 | * resident, otherwise the closest live fork descendant of it. Captain-directed |
| 149 | * reports use this so a human working in a fork still receives them, while the |
| 150 | * durable mail record stays addressed to the recorded captain. |
| 151 | * @param ctx - the plugin context (injects `agents`). |
| 152 | * @param team - current team state. |
| 153 | * @returns the live lead agent, or undefined when no lead session is resident. |
| 154 | */ |
| 155 | export function nearestLiveLead(ctx, team, live) { |
| 156 | // The recorded captain is the delivery parent whenever it is resident; a |
| 157 | // registry without `list` (or with rows the lineage cannot read) only means |
| 158 | // the fork fallback is unavailable, never that this lookup fails. |
| 159 | const exact = ctx.agents.get(team.captainSessionId); |
| 160 | if (exact !== undefined) |
| 161 | return exact; |
| 162 | let candidates; |
| 163 | try { |
| 164 | candidates = live ?? ctx.agents.list(); |
| 165 | } |
| 166 | catch { |
| 167 | return undefined; |
| 168 | } |
| 169 | let best; |
| 170 | let bestDistance = Number.POSITIVE_INFINITY; |
| 171 | for (const agent of candidates) { |
| 172 | try { |
| 173 | const identity = leadIdentityOf(ctx, agent.session); |
| 174 | if (!teamLeadMatch(team, identity)) |
| 175 | continue; |
| 176 | const distance = identity.ancestry.indexOf(team.captainSessionId); |
| 177 | if (distance < 0 || distance >= bestDistance) |
| 178 | continue; |
| 179 | best = agent; |
| 180 | bestDistance = distance; |
| 181 | } |
| 182 | catch { |
| 183 | continue; |
| 184 | } |
| 185 | } |
| 186 | return best; |
| 187 | } |
| 188 | /** |
| 189 | * Diagnostic note for a caller that matched no team but is a fork, so an |
| 190 | * operator can distinguish "no team exists" from "a team exists that this |
| 191 | * session does not lead". |
| 192 | */ |
| 193 | export function forkLineageNote(session) { |
| 194 | const parent = session.header.parentSession; |
| 195 | if (parent === undefined) |
| 196 | return ''; |
| 197 | return ` (this session is a fork of ${parent}; no active team in this workspace is led by that session or by a lead session in its lineage)`; |
| 198 | } |
| 199 |