/** * Society Protocol — Latent-Space Collaboration Layer * * Inspired by LatentMAS (arXiv:2511.20639) and Vision Wormhole (arXiv:2602.15382). * * Instead of exchanging verbose text between agents, this layer enables agents * to share compressed latent representations — "thought embeddings" — that * capture reasoning state in continuous vector space. * * Key innovations adapted for P2P: * - Universal Codec: Hub-and-spoke alignment (O(N) not O(N²)) for heterogeneous models * - Compressed Thought Tokens: Fixed-size representations regardless of reasoning depth * - KV-Cache Transfer: Layer-wise key/value cache sharing for same-architecture agents * - Latent Working Memory: Shared embedding space for collective reasoning * * References: * - LatentMAS: github.com/Gen-Verse/LatentMAS (Princeton/Stanford/UIUC) * - Vision Wormhole: arXiv:2602.15382 (heterogeneous model pools) */ import { EventEmitter } from 'events'; import type { RoomManager } from './rooms.js'; import type { Storage } from './storage.js'; import type { Identity } from './identity.js'; export interface LatentThought { /** Unique thought ID */ id: string; /** Source agent DID */ sourceDid: string; /** Source agent's model architecture (for compatibility checks) */ sourceArchitecture: string; /** Room where this thought was generated */ roomId: string; /** Chain ID (if part of a CoC workflow) */ chainId?: string; /** Step ID (if part of a specific step) */ stepId?: string; /** Compressed thought embedding (base64-encoded float32 array) */ embedding: string; /** Dimensionality of the embedding */ dimensions: number; /** Number of latent reasoning steps that produced this */ latentDepth: number; /** Semantic summary (short text for indexing/search) */ semanticLabel: string; /** Confidence in this thought (0-1) */ confidence: number; /** Timestamp */ createdAt: number; /** Alignment metadata for cross-architecture sharing */ alignment?: AlignmentMetadata; } export interface AlignmentMetadata { /** Whether this embedding has been projected to universal space */ isUniversal: boolean; /** Reference space ID (for hub-and-spoke alignment) */ referenceSpaceId?: string; /** Alignment quality score (0-1, from ridge regression R²) */ alignmentQuality: number; /** Original dimensions before projection */ originalDimensions: number; /** Universal token count (fixed-size after resampling) */ universalTokenCount: number; } export interface LatentWorkingMemory { /** Room-scoped shared latent space */ roomId: string; /** Accumulated thought embeddings from all agents */ thoughts: LatentThought[]; /** Merged embedding representing collective reasoning state */ collectiveEmbedding?: string; /** Dimensions of collective embedding */ collectiveDimensions?: number; /** Agent architecture registry for compatibility */ architectureRegistry: Map; /** Alignment matrices (agent DID → universal projection) */ alignmentMatrices: Map; } export interface AgentArchitectureInfo { did: string; architecture: string; hiddenDimension: number; vocabSize: number; numLayers: number; supportsKvTransfer: boolean; lastSeen: number; } export interface LatentCollaborationConfig { /** Max thoughts to keep in working memory per room */ maxThoughtsPerRoom: number; /** Default embedding dimensions */ defaultDimensions: number; /** Universal token count for cross-architecture sharing */ universalTokenCount: number; /** Alignment quality threshold (below this, fall back to text) */ alignmentQualityThreshold: number; /** Whether to auto-align embeddings to universal space */ autoAlign: boolean; /** TTL for thoughts in working memory (ms) */ thoughtTtlMs: number; } export declare const DEFAULT_LATENT_CONFIG: LatentCollaborationConfig; export declare class LatentSpaceEngine extends EventEmitter { private identity; private storage; private rooms; private workingMemories; private config; constructor(identity: Identity, storage: Storage, rooms: RoomManager, config?: Partial); private bindEvents; /** * Share a latent thought with the room. * The thought is a compressed embedding of the agent's reasoning state. */ shareThought(roomId: string, embedding: Float32Array | number[], options: { chainId?: string; stepId?: string; semanticLabel: string; confidence?: number; architecture?: string; latentDepth?: number; }): Promise; /** * Retrieve collective reasoning state for a room. * Returns accumulated latent thoughts and the merged collective embedding. */ getCollectiveState(roomId: string): LatentWorkingMemory | undefined; /** * Query thoughts by semantic similarity. * Uses cosine similarity on embeddings. */ queryThoughts(roomId: string, queryEmbedding: Float32Array | number[], options?: { topK?: number; minConfidence?: number; chainId?: string; }): Array<{ thought: LatentThought; similarity: number; }>; /** * Announce this agent's architecture for compatibility detection. */ announceArchitecture(roomId: string, info: Omit): Promise; /** * Check if two agents can do direct KV-cache transfer (same architecture). */ canDirectTransfer(roomId: string, agentA: string, agentB: string): boolean; /** * Compute alignment matrix between two embedding spaces. * Uses ridge regression: W_a = (W_out^T * W_out + λI)^(-1) * W_out^T * W_in * Adapted from LatentMAS alignment operator. */ computeAlignmentMatrix(sourceEmbeddings: Float32Array[], targetEmbeddings: Float32Array[], lambda?: number): Float64Array; /** * Merge multiple thoughts into a collective embedding. * Weighted average based on confidence and recency. */ mergeThoughts(thoughts: LatentThought[]): Float32Array | null; /** * Get statistics about the latent space for a room. */ getStats(roomId: string): { thoughtCount: number; uniqueAgents: number; architectures: string[]; avgConfidence: number; avgLatentDepth: number; canDirectTransferPairs: number; }; private handleIncomingThought; private handleArchitectureAnnouncement; private addToWorkingMemory; private ensureWorkingMemory; private projectToUniversalSpace; private decodeEmbedding; private cosineSimilarity; destroy(): void; } //# sourceMappingURL=latent-space.d.ts.map