import CoreGraphics public struct DriverInputState: Codable, Sendable, Equatable { public let heldKeys: Set public let flags: UInt64 public init(heldKeys: Set, flags: UInt64) { self.heldKeys = heldKeys self.flags = flags } public static func capture() -> Self { Self( heldKeys: Set((UInt16(0)...127).filter { CGEventSource.keyState(.combinedSessionState, key: $0) }), flags: CGEventSource.flagsState(.combinedSessionState).rawValue) } public func requireNeutralBaseline() throws { try requireRestored(to: Self(heldKeys: [], flags: flags & 0x0001_0000)) } public func requireRestored(to baseline: Self) throws { guard heldKeys.isEmpty else { throw DriverError("Safety stop: combined session still holds keys \(heldKeys.sorted()); input leaked") } let extra = flags & DriverModifierSequence.heldFlags & ~baseline.flags guard extra == 0 else { throw DriverError("Safety stop: combined session has modifier flags beyond baseline: \(extra)") } guard flags & 0x0001_0000 == baseline.flags & 0x0001_0000 else { throw DriverError("Safety stop: Caps Lock changed from the lane baseline") } } }