import type { ExtensionAPI, ExtensionContext, ExtensionUIContext, } from "@earendil-works/pi-coding-agent"; import type { JobState } from "./helpers"; import type { InteractiveSubagentState } from "./interactive-tmux"; import type { ParsedSpawnTreeContext } from "./spawn-tree-context"; import type { TelemetrySession } from "./telemetry"; import { detectEnvironment, type EnvironmentSnapshot } from "./environment"; const SESSION_SCOPE_REGISTRY_KEY = "__piSubagenturaSessionScopes"; const SESSION_SCOPE_ID_COUNTER_KEY = "__piSubagenturaSessionScopeIdCounter"; export type SessionScopeLifecycle = "registered" | "started" | "shutdown"; export interface SessionScopeManager extends Partial< Pick< ExtensionContext["sessionManager"], "getEntries" | "getSessionId" | "getSessionDir" > > {} /** Mutable state owned by one extension registration and lifecycle generation. */ export interface SessionScope { id: number; generation: number; pi: ExtensionAPI; ui?: ExtensionUIContext; cwd?: string; lifecycle: SessionScopeLifecycle; /** Closed while the session lifecycle retires or replaces this generation. */ workflowAdmissionClosed: boolean; sessionManager?: SessionScopeManager; spawnTreeContext?: ParsedSpawnTreeContext; /** Closed activation-scoped observations, not live mux authority. */ readonly environment: EnvironmentSnapshot; lineageMode?: "root" | "child"; isParentIdle?: () => boolean; /** True while Pi is waiting on a blocking extension UI prompt. */ uiPromptActive?: boolean; parentStreaming: boolean; inProcessJobs: Map; interactiveStates: Map; /** Anonymous correlation state for this exact lifecycle generation. */ telemetry?: TelemetrySession; } /** External registrations may omit runtime-owned fields; omitted state uses defaults. */ export interface SessionScopeRegistration { id: number; generation: number; pi: ExtensionAPI; ui?: ExtensionUIContext; cwd?: string; lifecycle?: SessionScopeLifecycle; workflowAdmissionClosed?: boolean; sessionManager?: SessionScopeManager; spawnTreeContext?: ParsedSpawnTreeContext; environment?: EnvironmentSnapshot; lineageMode?: "root" | "child"; isParentIdle?: () => boolean; /** True while Pi is waiting on a blocking extension UI prompt. */ uiPromptActive?: boolean; parentStreaming?: boolean; inProcessJobs?: Map; interactiveStates?: Map; telemetry?: TelemetrySession; } export interface SessionOwnerToken { id: number; generation: number; } export interface SessionToolToken { id: number; } interface SessionScopeGlobalState { __piSubagenturaSessionScopes?: Map; __piSubagenturaSessionScopeIdCounter?: number; __piSubagenturaPendingInteractiveLaunches?: Map< string, { cancelled: boolean } >; } function getGlobalState(): typeof globalThis & SessionScopeGlobalState { return globalThis as typeof globalThis & SessionScopeGlobalState; } function getSessionScopeRegistry(): Map { const state = getGlobalState(); return (state[SESSION_SCOPE_REGISTRY_KEY] ??= new Map()); } /** A persisted pane still belongs to its launcher until submission settles. */ export function trackPendingInteractiveLaunch(id: string) { const pending = (getGlobalState().__piSubagenturaPendingInteractiveLaunches ??= new Map()); const launch = { cancelled: false }; pending.set(id, launch); return { isCancelled: () => launch.cancelled, release: () => { pending.delete(id); }, }; } export function markPendingInteractiveLaunchCancelled(id: string): void { const launch = getGlobalState().__piSubagenturaPendingInteractiveLaunches?.get(id); if (launch) launch.cancelled = true; } export function isPendingInteractiveLaunch(id: string): boolean { return ( getGlobalState().__piSubagenturaPendingInteractiveLaunches?.has(id) ?? false ); } export function getSessionScopes(): SessionScope[] { return [...getSessionScopeRegistry().values()]; } export function clearSessionScopes(): void { getSessionScopeRegistry().clear(); const state = getGlobalState(); state[SESSION_SCOPE_ID_COUNTER_KEY] = 0; } export function getStartedSessionScopes(): SessionScope[] { return getSessionScopes().filter((scope) => scope.lifecycle === "started"); } export function nextSessionScopeId(): number { const state = getGlobalState(); const next = (state[SESSION_SCOPE_ID_COUNTER_KEY] ?? 0) + 1; state[SESSION_SCOPE_ID_COUNTER_KEY] = next; return next; } export function createSessionScope( pi: ExtensionAPI, spawnTreeContext?: ParsedSpawnTreeContext, lineageMode: "root" | "child" = "root", environment: EnvironmentSnapshot = detectEnvironment(), ): SessionScope { return { id: nextSessionScopeId(), generation: 0, lifecycle: "registered", workflowAdmissionClosed: false, pi, spawnTreeContext, environment, lineageMode, parentStreaming: false, uiPromptActive: false, inProcessJobs: new Map(), interactiveStates: new Map(), telemetry: undefined, }; } function isCompleteSessionScope( registration: SessionScopeRegistration, ): registration is SessionScope { return ( (registration.lifecycle === "registered" || registration.lifecycle === "started" || registration.lifecycle === "shutdown") && typeof registration.workflowAdmissionClosed === "boolean" && typeof registration.parentStreaming === "boolean" && registration.inProcessJobs instanceof Map && registration.environment !== undefined && registration.interactiveStates instanceof Map ); } export function registerSessionScope( registration: SessionScopeRegistration, ): SessionScope { const state = getGlobalState(); state[SESSION_SCOPE_ID_COUNTER_KEY] = Math.max( state[SESSION_SCOPE_ID_COUNTER_KEY] ?? 0, registration.id, ); const registry = getSessionScopeRegistry(); const existing = registry.get(registration.id); if (existing) { existing.generation = registration.generation; existing.pi = registration.pi; existing.lifecycle = registration.lifecycle ?? existing.lifecycle; if (registration.workflowAdmissionClosed !== undefined) { existing.workflowAdmissionClosed = registration.workflowAdmissionClosed; } existing.parentStreaming = registration.parentStreaming ?? existing.parentStreaming; if (registration.ui !== undefined) existing.ui = registration.ui; if (registration.cwd !== undefined) existing.cwd = registration.cwd; if (registration.sessionManager !== undefined) { existing.sessionManager = registration.sessionManager; } if (Object.hasOwn(registration, "spawnTreeContext")) { existing.spawnTreeContext = registration.spawnTreeContext; } if (registration.lineageMode !== undefined) { existing.lineageMode = registration.lineageMode; } if (registration.isParentIdle !== undefined) { existing.isParentIdle = registration.isParentIdle; } if (registration.uiPromptActive !== undefined) { existing.uiPromptActive = registration.uiPromptActive; } if (registration.inProcessJobs !== undefined) { existing.inProcessJobs = registration.inProcessJobs; } if (registration.interactiveStates !== undefined) { existing.interactiveStates = registration.interactiveStates; } if (Object.hasOwn(registration, "telemetry")) { existing.telemetry = registration.telemetry; } return existing; } const scope: SessionScope = isCompleteSessionScope(registration) ? registration : { id: registration.id, generation: registration.generation, pi: registration.pi, ui: registration.ui, cwd: registration.cwd, lifecycle: registration.lifecycle ?? "started", workflowAdmissionClosed: registration.workflowAdmissionClosed ?? false, sessionManager: registration.sessionManager, spawnTreeContext: registration.spawnTreeContext, lineageMode: registration.lineageMode ?? "root", isParentIdle: registration.isParentIdle, uiPromptActive: registration.uiPromptActive ?? false, parentStreaming: registration.parentStreaming ?? false, inProcessJobs: registration.inProcessJobs ?? new Map(), interactiveStates: registration.interactiveStates ?? new Map(), environment: registration.environment ?? detectEnvironment(), telemetry: registration.telemetry, }; registry.set(scope.id, scope); return scope; } export function findSessionScope(id: number): SessionScope | undefined { return getSessionScopeRegistry().get(id); } export function removeSessionScope(id: number): SessionScope | undefined { const registry = getSessionScopeRegistry(); const removed = registry.get(id); if (!removed) return undefined; registry.delete(id); return removed; } /** Advance a generation so pending work cannot cross lifecycle boundaries. */ export function advanceSessionScopeGeneration(id: number): number { const scope = findSessionScope(id); if (!scope) return 0; scope.generation++; return scope.generation; } export function sessionOwner(scope: SessionScope): SessionOwnerToken { return { id: scope.id, generation: scope.generation }; } /** Resolve an exact owner only while that lifecycle generation remains live. */ export function resolveLiveSessionScope( owner: SessionOwnerToken | undefined, ): SessionScope | undefined { if (!owner) return undefined; const scope = findSessionScope(owner.id); return scope?.generation === owner.generation && scope.lifecycle === "started" ? scope : undefined; } /** Resolve a registration-captured tool token to its current live generation. */ export function resolveToolSessionScope( token: SessionToolToken | undefined, ): SessionScope | undefined { if (!token) return undefined; const scope = findSessionScope(token.id); return scope?.lifecycle === "started" ? scope : undefined; } export function resolveToolSessionOwner( token: SessionToolToken | undefined, ): SessionOwnerToken | undefined { const scope = resolveToolSessionScope(token); return scope ? sessionOwner(scope) : undefined; } export function isSessionOwnerLive( owner: SessionOwnerToken | undefined, ): boolean { return owner !== undefined && resolveLiveSessionScope(owner) !== undefined; } export function sessionIdForOwner( owner: SessionOwnerToken | undefined, ): string | undefined { if (!owner) return undefined; try { return resolveLiveSessionScope(owner)?.sessionManager?.getSessionId?.(); } catch { return undefined; } } export function parentSessionBelongsToOwner( parentSessionId: string | undefined, owner: SessionOwnerToken | undefined, ): boolean { if (!owner) return false; const ownerSessionId = sessionIdForOwner(owner); return ownerSessionId !== undefined && parentSessionId === ownerSessionId; } export function resolveStreamingFlag(owner?: SessionOwnerToken): boolean { const scope = owner ? resolveLiveSessionScope(owner) : undefined; return Boolean(scope?.parentStreaming || scope?.uiPromptActive); } export function resolveActualStreamingFlag(owner?: SessionOwnerToken): boolean { const scope = owner ? resolveLiveSessionScope(owner) : undefined; if (scope?.uiPromptActive) return true; if (scope?.isParentIdle) { try { return !scope.isParentIdle(); } catch { // A stale context falls back to the scoped event-maintained flag. } } return resolveStreamingFlag(owner); } export interface InteractiveSessionOwnerState { parentSessionId?: string; sessionOwner?: SessionOwnerToken; supervisorOwner?: SessionOwnerToken; } export function interactiveStateBelongsToOwner( state: InteractiveSessionOwnerState, owner: SessionOwnerToken | undefined, sessionId?: string, ): boolean { const stateOwner = state.sessionOwner ?? state.supervisorOwner; if (stateOwner) { return owner ? stateOwner.id === owner.id && stateOwner.generation === owner.generation : false; } if (owner) { const ownerSessionId = sessionIdForOwner(owner); return ( ownerSessionId !== undefined && state.parentSessionId === ownerSessionId ); } return sessionId === undefined || state.parentSessionId === sessionId; }