holomime 1.8.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -4792,6 +4792,63 @@ declare function generateIndexMarkdown(index: BehavioralIndex): string;
4792
4792
  */
4793
4793
  declare function startMCPServer(): Promise<void>;
4794
4794
 
4795
+ /**
4796
+ * Types for the HoloMime Live real-time behavioral monitoring system.
4797
+ */
4798
+ interface BrainRegionState {
4799
+ id: string;
4800
+ name: string;
4801
+ function: string;
4802
+ color: string;
4803
+ intensity: number;
4804
+ patterns: string[];
4805
+ }
4806
+ interface FiredPattern {
4807
+ id: string;
4808
+ name: string;
4809
+ severity: "info" | "warning" | "concern";
4810
+ percentage: number;
4811
+ description: string;
4812
+ }
4813
+ interface BrainEvent {
4814
+ type: "diagnosis";
4815
+ timestamp: string;
4816
+ health: number;
4817
+ grade: string;
4818
+ messageCount: number;
4819
+ regions: BrainRegionState[];
4820
+ patterns: FiredPattern[];
4821
+ activity: {
4822
+ role: "user" | "assistant";
4823
+ preview: string;
4824
+ } | null;
4825
+ }
4826
+
4827
+ /**
4828
+ * Snapshot encoding and share URL generation.
4829
+ * Used by brain command, diagnose command, and benchmark command
4830
+ * to generate shareable brain visualization URLs.
4831
+ */
4832
+
4833
+ /**
4834
+ * Compress a BrainEvent into a compact base64url-encoded string for sharing.
4835
+ */
4836
+ declare function encodeSnapshot(event: BrainEvent, agentName: string): string;
4837
+ /**
4838
+ * Generate a share URL from a DiagnosisResult.
4839
+ * Converts diagnosis → BrainEvent → compressed snapshot → URL.
4840
+ */
4841
+ declare function generateShareUrl(diagnosis: DiagnosisResult, agentName?: string): string;
4842
+ /**
4843
+ * Copy text to system clipboard. Silent fail on unsupported platforms.
4844
+ */
4845
+ declare function copyToClipboard(text: string): boolean;
4846
+ /**
4847
+ * Generate and print a share URL from a DiagnosisResult.
4848
+ * Convenience function that combines generation + clipboard + display.
4849
+ */
4850
+ declare function shareFromDiagnosis(diagnosis: DiagnosisResult, agentName?: string): void;
4851
+
4795
4852
  /**
4796
4853
  * Oversight — human gating controls for autonomous operations.
4797
4854
  *
@@ -5895,4 +5952,116 @@ declare function listPresets(): BehavioralPreset[];
5895
5952
  */
5896
5953
  declare function getPreset(key: string): BehavioralPreset | undefined;
5897
5954
 
5898
- export { ARCHETYPES, ATTACHMENT_STYLES, type AdversarialCallbacks, type AdversarialCategory, type AdversarialReport, type AdversarialResult, type AdversarialRunOptions, type AdversarialScenario, type AlpacaExample, type AnonymizedPatternReport, AnthropicProvider, type ArchetypeTemplate, type AssessmentReport, type AssessmentResult, type AssetReview, type AssetType, type AttachmentStyle, type AuditEntry, type AuditEventType, type AutopilotResult, type AutopilotThreshold, type AwarenessDimension, BUILT_IN_DETECTORS, type BehavioralBaseline, type BehavioralCredential, type BehavioralEvent, type BehavioralEventType, type BehavioralGap, type BehavioralIndex, type BehavioralMemoryStore, type BehavioralPolicy, type BehavioralPolicyRule, type BehavioralPreset, type BenchmarkCallbacks, type BenchmarkComparison, type BenchmarkReport, type BenchmarkResult, type BenchmarkScenario, type BigFive, CATEGORIES, type CertifyInput, type Communication, type CompactionResult, type CompactionSummary, type CompileInput, type CompiledConfig, type CompiledEmbodiedConfig, type ReACTStep as ComplianceReACTStep, type ComplianceReport, type ContextLayerInput, type Conversation, type ConversationLog, type CorpusFilter, type CorpusStats, type CorrectionRecord, type CrossAgentQuery, type CustomDetectorConfig, DEFAULT_OVERSIGHT, DIMENSIONS, type DPOPair, type DetectedPattern, type DetectorFactory, type DetectorFn$1 as DetectorFn, type DetectorOptions, type DiagnosisResult, type DimensionTrajectory, type Domain, type DriftTrigger, type EdgeType, type Embodiment, type EvolutionEntry, type EvolutionHistory, type EvolutionSummary, type EvolveCallbacks, type EvolveOptions, type EvolveResult, type Expression, type FleetAgent, type FleetAgentStatus, type FleetConfig, type FleetHandle, type FleetOptions, type FrameworkSection, type GazePolicy, type Gesture, type GraphEdge, type GraphNode, type Growth, type GrowthArea, type GrowthReport, type GrowthSnapshot, Guard, type GuardEntry, type GuardFilterResult, type GuardMiddleware, type GuardMiddlewareOptions, type GuardMiddlewareStats, type GuardMode, type GuardResult, type GuardViolation, type GuardWrapResult, type HFPushOptions, type HFPushResult, type HapticPolicy, type HubDetector, type IndexComparison, type IndexEntry, type Intervention, type InterventionRepertoire, type InterventionSource, type InterviewCallbacks, type InterviewProbe, type InterviewResponse, type InterviewResult, type IterationResult, type KnowledgeGraph, LEARNING_ORIENTATIONS, type LLMMessage, type LLMProvider, type LeaderboardEntry, type LeaderboardSubmission, type LearningOrientation, LocalMarketplaceBackend, type LogFormat, type MarketplaceAsset, type MarketplaceBackend, MarketplaceClient, type MarketplaceSearchQuery, type MarketplaceSearchResult, type Message, type Modality, type MonitoringCertificate, type Morphology, type MotionParameters, type NetworkCallbacks, type NetworkConfig, type NetworkNode, type NetworkResult, type NetworkSession, type NodeType, OllamaProvider, OpenAIProvider, type OutcomeReport, type OversightAction, type OversightMode, type OversightNotification, type OversightPolicy, PROVIDER_PARAMS, type PairingStrategy, type PatternCorrelation, type PatternDelta, type PatternReport, type PatternStatus, type PatternTracker, type PersonalitySpec, type PersonalityTier, type PhaseConfig, type PhysicalSafety, type PolicyIntent, type PreSessionDiagnosis, type Prescription, type Prosody, type Provider, type ProviderConfig, type ProxemicZone, type PublishRequest, type PublishedBenchmark, type RLHFExample, type ReACTAction, type ReACTContext, type ReACTReport, type ReACTReportOptions, type ReACTStep$1 as ReACTStep, type Registry, type RegistryEntry, type ReportStatistics, type RiskFinding, type RollingContext, STANDARD_PROBES, SURFACE_MULTIPLIERS, type SafetyEnvelope, type SelfAuditFlag, type SelfAuditResult, type SelfObservation, type SessionCallbacks, type SessionOptions, type SessionOutcome, type SessionSummary, type SessionTranscript, type SessionTurn, type Severity, type SharedIntervention, type SharedKnowledge, type SortField, type StagingDiff, type Surface, type SyncAnchor, type SyncProfile, type SyncRule, THERAPIST_META_SPEC, THERAPY_DIMENSIONS, THERAPY_PHASES, type TherapistPromptOptions, type TherapyDimensions, type TherapyMemory, type TherapyPhase, type TieredPersonality, type TrainingExport, type TraitAlignment, type TraitScores, type TreatmentGoal, type TreatmentPlan, type TreatmentProgressReport, type VerifyResult, type WatchCallbacks, type WatchEvent, type WatchHandle, type WatchOptions, type WrapAgentOptions, type WrapOptions, type WrappedAgent, addEdge, addNode, addSessionToMemory, agentHandleFromSpec, appendAuditEntry, appendEvolution, applyRecommendations, bigFiveSchema, buildAgentTherapistPrompt, buildAnonymizedReport, buildPatientSystemPrompt, buildReACTContext, buildReACTFraming, buildSharedKnowledge, buildTherapistSystemPrompt, checkApproval, checkIterationBudget, communicationSchema, compactEvolutionRun, compactIteration, compareBenchmarks, compareIndex, compile, compileCustomDetector, compileEmbodied, compileForOpenClaw, compileL0, compileL1, compileL2, compileTiered, compiledConfigSchema, compiledEmbodiedConfigSchema, computeDimensionScore, computeGazePolicy, computeMotionParameters, computeProsody, computeProxemics, computeSyncProfile, conversationLogSchema, conversationSchema, convertToHFFormat, corpusStats, createBehavioralMemory, createGist, createGraph, createGuardMiddleware, createIndex, createIndexEntry, createMemory, createProvider, createRepertoire, createTreatmentPlan, decayUnseenPatterns, deepMergeSpec, detectApologies, detectBoundaryIssues, detectFormalityIssues, detectHedging, detectRecoveryPatterns, detectRetrievalQuality, detectSentiment, detectVerbosity, discoverAgentData, discoverAgents, discoverNetworkAgents, domainSchema, embodimentSchema, emitBehavioralEvent, estimateConfidence, evaluateOutcome, expireOldEdges, exportTrainingData, expressionSchema, extractAlpacaExamples, extractDPOPairs, extractDPOPairsWithLLM, extractRLHFExamples, extractRecommendations, fetchLeaderboard, fetchPersonality, fetchRegistry, findCrossAgentCorrelations, findEdges, findNode, findNodesByType, formatComplianceReportMarkdown, formatGapSummary, formatPolicyYaml, formatReACTReportMarkdown, gazePolicySchema, generateBehavioralPolicy, generateBenchmarkMarkdown, generateComparisonMarkdown, generateComplianceReport, generateCredential, generateGapRecommendation, generateIndexMarkdown, generateMonitoringCertificate, generateMutations, generatePrescriptions, generateProgressReport, generateReACTReport, generateSystemPrompt, gestureSchema, getAdversarialCategories, getAdversarialScenarios, getAgentBehaviors, getArchetype, getArchetypesByCategory, getBehavioralMemorySummary, getBenchmarkScenarios, getBestCorrection, getCategories, getDetector, getDimension, getEvolutionSummary, getInheritanceChain, getInterviewContext, getMarketplaceClient, getMemoryContext, getNeighbors, getPhaseContext, getPreset, getScenarioById, getTotalSignalCount, getTrajectory, getTriggersForPattern, graphStats, growthAreaSchema, growthSchema, hapticPolicySchema, hashSpec, learnIntervention, listArchetypeIds, listDetectors, listDetectorsByCategory, listDetectorsByTag, listPresets, loadAuditLog, loadBehavioralMemory, loadBenchmarkResults, loadCorpus, loadCustomDetectors, loadEvolution, loadFleetConfig, loadGraph, loadLatestBenchmark, loadMemory, loadNetworkConfig, loadRepertoire, loadSpec, loadTranscripts, loadTreatmentPlan, mergeStores, messageSchema, modalitySchema, morphologySchema, motionParametersSchema, pairAgents, parseAnthropicAPILog, parseChatGPTExport, parseClaudeExport, parseConversationLog, parseConversationLogFromString, parseJSONLLog, parseMarkdownDetector, parseOTelGenAIExport, parseOpenAIAPILog, personalitySpecSchema, physicalSafetySchema, populateFromDiagnosis, populateFromEvolve, populateFromSession, prescribeDPOPairs, processReACTResponse, prosodySchema, providerSchema, proxemicZoneSchema, publishToLeaderboard, pushToHFHub, queryCorpus, queryInterventions, querySharedKnowledge, recommendTier, recordInterventionOutcome, recordObservation, recordSelfObservation, recordSessionOutcome, registerBuiltInDetectors, registerDetector, resetMarketplaceClient, resolveInheritance, resolveOversight, runAdversarialSuite, runAssessment, runAutopilot, runBenchmark, runDiagnosis, runEvolve, runInterview, runNetwork, runPreSessionDiagnosis, runSelfAudit, runTherapySession, safetyEnvelopeSchema, saveBehavioralMemory, saveBenchmarkResult, saveCredential, saveGraph, saveMemory, saveRepertoire, saveTranscript, saveTreatmentPlan, scoreLabel, scoreTraitsFromMessages, seedBuiltInPersonalities, selectIntervention, severityMeetsThreshold, severitySchema, shareAnonymizedPatterns, startFleet, startMCPServer, startWatch, summarize, summarizeSessionForMemory, summarizeTherapy, surfaceSchema, syncAnchorSchema, syncProfileSchema, syncRuleSchema, therapyDimensionsSchema, therapyScoreLabel, transferIntervention, unregisterDetector, updateEdgeWeight, validateDetectorConfig, verifyAuditChain, verifyCredential, wrapAgent };
5955
+ /**
5956
+ * LangChain / CrewAI / LlamaIndex Callback Handler
5957
+ *
5958
+ * Monitors LLM responses in real-time and detects behavioral anti-patterns.
5959
+ * Works with any LangChain-compatible framework that supports callback handlers.
5960
+ *
5961
+ * Usage:
5962
+ * import { HolomimeCallbackHandler } from "holomime/integrations/langchain";
5963
+ *
5964
+ * const handler = new HolomimeCallbackHandler({
5965
+ * mode: "monitor", // "monitor" | "enforce" | "strict"
5966
+ * personality: ".personality.json",
5967
+ * onViolation: (v) => console.warn("Behavioral drift:", v),
5968
+ * });
5969
+ *
5970
+ * // LangChain
5971
+ * const chain = prompt.pipe(model).pipe(parser);
5972
+ * await chain.invoke({ input: "hello" }, { callbacks: [handler] });
5973
+ *
5974
+ * // CrewAI — pass as LangChain callback on the underlying LLM
5975
+ * // LlamaIndex — use as a callback handler on the LLM
5976
+ */
5977
+
5978
+ type CallbackMode = "monitor" | "enforce" | "strict";
5979
+ interface CallbackViolation {
5980
+ patterns: DetectedPattern[];
5981
+ severity: "warning" | "concern";
5982
+ response: string;
5983
+ runId?: string;
5984
+ timestamp: string;
5985
+ }
5986
+ interface HolomimeCallbackOptions {
5987
+ /** Guard mode. Default: "monitor". */
5988
+ mode?: CallbackMode;
5989
+ /** Path to .personality.json or inline spec object. */
5990
+ personality?: string | object;
5991
+ /** Minimum severity to trigger. Default: "warning". */
5992
+ minSeverity?: "warning" | "concern";
5993
+ /** Callback fired on every violation. */
5994
+ onViolation?: (violation: CallbackViolation) => void;
5995
+ /** Agent name for reports. Default: "langchain-agent". */
5996
+ name?: string;
5997
+ /** Buffer size — number of messages to retain for context. Default: 50. */
5998
+ bufferSize?: number;
5999
+ }
6000
+ interface CallbackStats {
6001
+ totalResponses: number;
6002
+ passed: number;
6003
+ violated: number;
6004
+ blocked: number;
6005
+ patternCounts: Record<string, number>;
6006
+ }
6007
+ /**
6008
+ * HolomimeCallbackHandler — behavioral alignment monitor for LangChain-compatible frameworks.
6009
+ *
6010
+ * Implements the LangChain BaseCallbackHandler interface without importing langchain,
6011
+ * keeping it as an optional peer dependency. Works with LangChain, CrewAI, and any
6012
+ * framework that accepts { handleLLMEnd, handleLLMStart, handleLLMError } callbacks.
6013
+ */
6014
+ declare class HolomimeCallbackHandler {
6015
+ readonly name = "holomime";
6016
+ readonly lc_serializable = false;
6017
+ private guard;
6018
+ private mode;
6019
+ private minSeverity;
6020
+ private onViolation?;
6021
+ private messageBuffer;
6022
+ private bufferSize;
6023
+ private currentRunMessages;
6024
+ private _stats;
6025
+ constructor(options?: HolomimeCallbackOptions);
6026
+ /**
6027
+ * Called when an LLM starts generating.
6028
+ * Captures the input messages for context.
6029
+ */
6030
+ handleLLMStart(_llm: any, prompts: string[], runId?: string): void;
6031
+ /**
6032
+ * Called when an LLM finishes generating.
6033
+ * Runs behavioral analysis on the response.
6034
+ */
6035
+ handleLLMEnd(output: any, runId?: string): void;
6036
+ /**
6037
+ * Called on LLM errors. Clean up run tracking.
6038
+ */
6039
+ handleLLMError(_error: any, runId?: string): void;
6040
+ /**
6041
+ * Called when a chain starts. Captures input for context.
6042
+ */
6043
+ handleChainStart(_chain: any, inputs: Record<string, any>, runId?: string): void;
6044
+ /**
6045
+ * Get cumulative stats.
6046
+ */
6047
+ stats(): CallbackStats;
6048
+ /**
6049
+ * Reset the message buffer and stats.
6050
+ */
6051
+ reset(): void;
6052
+ /**
6053
+ * Get the current guard result for the buffered conversation.
6054
+ */
6055
+ diagnose(): GuardResult;
6056
+ private severityMeetsMin;
6057
+ private extractResponseText;
6058
+ }
6059
+ /**
6060
+ * Error thrown in strict mode when a concern-level violation is detected.
6061
+ */
6062
+ declare class HolomimeViolationError extends Error {
6063
+ readonly violation: CallbackViolation;
6064
+ constructor(violation: CallbackViolation);
6065
+ }
6066
+
6067
+ export { ARCHETYPES, ATTACHMENT_STYLES, type AdversarialCallbacks, type AdversarialCategory, type AdversarialReport, type AdversarialResult, type AdversarialRunOptions, type AdversarialScenario, type AlpacaExample, type AnonymizedPatternReport, AnthropicProvider, type ArchetypeTemplate, type AssessmentReport, type AssessmentResult, type AssetReview, type AssetType, type AttachmentStyle, type AuditEntry, type AuditEventType, type AutopilotResult, type AutopilotThreshold, type AwarenessDimension, BUILT_IN_DETECTORS, type BehavioralBaseline, type BehavioralCredential, type BehavioralEvent, type BehavioralEventType, type BehavioralGap, type BehavioralIndex, type BehavioralMemoryStore, type BehavioralPolicy, type BehavioralPolicyRule, type BehavioralPreset, type BenchmarkCallbacks, type BenchmarkComparison, type BenchmarkReport, type BenchmarkResult, type BenchmarkScenario, type BigFive, CATEGORIES, type CallbackMode, type CallbackStats, type CallbackViolation, type CertifyInput, type Communication, type CompactionResult, type CompactionSummary, type CompileInput, type CompiledConfig, type CompiledEmbodiedConfig, type ReACTStep as ComplianceReACTStep, type ComplianceReport, type ContextLayerInput, type Conversation, type ConversationLog, type CorpusFilter, type CorpusStats, type CorrectionRecord, type CrossAgentQuery, type CustomDetectorConfig, DEFAULT_OVERSIGHT, DIMENSIONS, type DPOPair, type DetectedPattern, type DetectorFactory, type DetectorFn$1 as DetectorFn, type DetectorOptions, type DiagnosisResult, type DimensionTrajectory, type Domain, type DriftTrigger, type EdgeType, type Embodiment, type EvolutionEntry, type EvolutionHistory, type EvolutionSummary, type EvolveCallbacks, type EvolveOptions, type EvolveResult, type Expression, type FleetAgent, type FleetAgentStatus, type FleetConfig, type FleetHandle, type FleetOptions, type FrameworkSection, type GazePolicy, type Gesture, type GraphEdge, type GraphNode, type Growth, type GrowthArea, type GrowthReport, type GrowthSnapshot, Guard, type GuardEntry, type GuardFilterResult, type GuardMiddleware, type GuardMiddlewareOptions, type GuardMiddlewareStats, type GuardMode, type GuardResult, type GuardViolation, type GuardWrapResult, type HFPushOptions, type HFPushResult, type HapticPolicy, HolomimeCallbackHandler, type HolomimeCallbackOptions, HolomimeViolationError, type HubDetector, type IndexComparison, type IndexEntry, type Intervention, type InterventionRepertoire, type InterventionSource, type InterviewCallbacks, type InterviewProbe, type InterviewResponse, type InterviewResult, type IterationResult, type KnowledgeGraph, LEARNING_ORIENTATIONS, type LLMMessage, type LLMProvider, type LeaderboardEntry, type LeaderboardSubmission, type LearningOrientation, LocalMarketplaceBackend, type LogFormat, type MarketplaceAsset, type MarketplaceBackend, MarketplaceClient, type MarketplaceSearchQuery, type MarketplaceSearchResult, type Message, type Modality, type MonitoringCertificate, type Morphology, type MotionParameters, type NetworkCallbacks, type NetworkConfig, type NetworkNode, type NetworkResult, type NetworkSession, type NodeType, OllamaProvider, OpenAIProvider, type OutcomeReport, type OversightAction, type OversightMode, type OversightNotification, type OversightPolicy, PROVIDER_PARAMS, type PairingStrategy, type PatternCorrelation, type PatternDelta, type PatternReport, type PatternStatus, type PatternTracker, type PersonalitySpec, type PersonalityTier, type PhaseConfig, type PhysicalSafety, type PolicyIntent, type PreSessionDiagnosis, type Prescription, type Prosody, type Provider, type ProviderConfig, type ProxemicZone, type PublishRequest, type PublishedBenchmark, type RLHFExample, type ReACTAction, type ReACTContext, type ReACTReport, type ReACTReportOptions, type ReACTStep$1 as ReACTStep, type Registry, type RegistryEntry, type ReportStatistics, type RiskFinding, type RollingContext, STANDARD_PROBES, SURFACE_MULTIPLIERS, type SafetyEnvelope, type SelfAuditFlag, type SelfAuditResult, type SelfObservation, type SessionCallbacks, type SessionOptions, type SessionOutcome, type SessionSummary, type SessionTranscript, type SessionTurn, type Severity, type SharedIntervention, type SharedKnowledge, type SortField, type StagingDiff, type Surface, type SyncAnchor, type SyncProfile, type SyncRule, THERAPIST_META_SPEC, THERAPY_DIMENSIONS, THERAPY_PHASES, type TherapistPromptOptions, type TherapyDimensions, type TherapyMemory, type TherapyPhase, type TieredPersonality, type TrainingExport, type TraitAlignment, type TraitScores, type TreatmentGoal, type TreatmentPlan, type TreatmentProgressReport, type VerifyResult, type WatchCallbacks, type WatchEvent, type WatchHandle, type WatchOptions, type WrapAgentOptions, type WrapOptions, type WrappedAgent, addEdge, addNode, addSessionToMemory, agentHandleFromSpec, appendAuditEntry, appendEvolution, applyRecommendations, bigFiveSchema, buildAgentTherapistPrompt, buildAnonymizedReport, buildPatientSystemPrompt, buildReACTContext, buildReACTFraming, buildSharedKnowledge, buildTherapistSystemPrompt, checkApproval, checkIterationBudget, communicationSchema, compactEvolutionRun, compactIteration, compareBenchmarks, compareIndex, compile, compileCustomDetector, compileEmbodied, compileForOpenClaw, compileL0, compileL1, compileL2, compileTiered, compiledConfigSchema, compiledEmbodiedConfigSchema, computeDimensionScore, computeGazePolicy, computeMotionParameters, computeProsody, computeProxemics, computeSyncProfile, conversationLogSchema, conversationSchema, convertToHFFormat, copyToClipboard, corpusStats, createBehavioralMemory, createGist, createGraph, createGuardMiddleware, createIndex, createIndexEntry, createMemory, createProvider, createRepertoire, createTreatmentPlan, decayUnseenPatterns, deepMergeSpec, detectApologies, detectBoundaryIssues, detectFormalityIssues, detectHedging, detectRecoveryPatterns, detectRetrievalQuality, detectSentiment, detectVerbosity, discoverAgentData, discoverAgents, discoverNetworkAgents, domainSchema, embodimentSchema, emitBehavioralEvent, encodeSnapshot, estimateConfidence, evaluateOutcome, expireOldEdges, exportTrainingData, expressionSchema, extractAlpacaExamples, extractDPOPairs, extractDPOPairsWithLLM, extractRLHFExamples, extractRecommendations, fetchLeaderboard, fetchPersonality, fetchRegistry, findCrossAgentCorrelations, findEdges, findNode, findNodesByType, formatComplianceReportMarkdown, formatGapSummary, formatPolicyYaml, formatReACTReportMarkdown, gazePolicySchema, generateBehavioralPolicy, generateBenchmarkMarkdown, generateComparisonMarkdown, generateComplianceReport, generateCredential, generateGapRecommendation, generateIndexMarkdown, generateMonitoringCertificate, generateMutations, generatePrescriptions, generateProgressReport, generateReACTReport, generateShareUrl, generateSystemPrompt, gestureSchema, getAdversarialCategories, getAdversarialScenarios, getAgentBehaviors, getArchetype, getArchetypesByCategory, getBehavioralMemorySummary, getBenchmarkScenarios, getBestCorrection, getCategories, getDetector, getDimension, getEvolutionSummary, getInheritanceChain, getInterviewContext, getMarketplaceClient, getMemoryContext, getNeighbors, getPhaseContext, getPreset, getScenarioById, getTotalSignalCount, getTrajectory, getTriggersForPattern, graphStats, growthAreaSchema, growthSchema, hapticPolicySchema, hashSpec, learnIntervention, listArchetypeIds, listDetectors, listDetectorsByCategory, listDetectorsByTag, listPresets, loadAuditLog, loadBehavioralMemory, loadBenchmarkResults, loadCorpus, loadCustomDetectors, loadEvolution, loadFleetConfig, loadGraph, loadLatestBenchmark, loadMemory, loadNetworkConfig, loadRepertoire, loadSpec, loadTranscripts, loadTreatmentPlan, mergeStores, messageSchema, modalitySchema, morphologySchema, motionParametersSchema, pairAgents, parseAnthropicAPILog, parseChatGPTExport, parseClaudeExport, parseConversationLog, parseConversationLogFromString, parseJSONLLog, parseMarkdownDetector, parseOTelGenAIExport, parseOpenAIAPILog, personalitySpecSchema, physicalSafetySchema, populateFromDiagnosis, populateFromEvolve, populateFromSession, prescribeDPOPairs, processReACTResponse, prosodySchema, providerSchema, proxemicZoneSchema, publishToLeaderboard, pushToHFHub, queryCorpus, queryInterventions, querySharedKnowledge, recommendTier, recordInterventionOutcome, recordObservation, recordSelfObservation, recordSessionOutcome, registerBuiltInDetectors, registerDetector, resetMarketplaceClient, resolveInheritance, resolveOversight, runAdversarialSuite, runAssessment, runAutopilot, runBenchmark, runDiagnosis, runEvolve, runInterview, runNetwork, runPreSessionDiagnosis, runSelfAudit, runTherapySession, safetyEnvelopeSchema, saveBehavioralMemory, saveBenchmarkResult, saveCredential, saveGraph, saveMemory, saveRepertoire, saveTranscript, saveTreatmentPlan, scoreLabel, scoreTraitsFromMessages, seedBuiltInPersonalities, selectIntervention, severityMeetsThreshold, severitySchema, shareAnonymizedPatterns, shareFromDiagnosis, startFleet, startMCPServer, startWatch, summarize, summarizeSessionForMemory, summarizeTherapy, surfaceSchema, syncAnchorSchema, syncProfileSchema, syncRuleSchema, therapyDimensionsSchema, therapyScoreLabel, transferIntervention, unregisterDetector, updateEdgeWeight, validateDetectorConfig, verifyAuditChain, verifyCredential, wrapAgent };
package/dist/index.js CHANGED
@@ -9419,6 +9419,208 @@ startMCPServer().catch((err) => {
9419
9419
  process.exit(1);
9420
9420
  });
9421
9421
 
9422
+ // src/live/snapshot.ts
9423
+ import { deflateSync } from "zlib";
9424
+ import { execSync } from "child_process";
9425
+ import chalk from "chalk";
9426
+
9427
+ // src/live/brain-mapper.ts
9428
+ var BRAIN_REGIONS = [
9429
+ {
9430
+ id: "prefrontal-cortex",
9431
+ name: "Prefrontal Cortex",
9432
+ function: "Executive Decisions",
9433
+ color: "#4488ff",
9434
+ detectors: ["boundary-violation", "over-verbose"]
9435
+ },
9436
+ {
9437
+ id: "brocas-area",
9438
+ name: "Broca's Area",
9439
+ function: "Language Generation",
9440
+ color: "#aa66ff",
9441
+ detectors: ["register-inconsistency", "hedge-stacking"]
9442
+ },
9443
+ {
9444
+ id: "wernickes-area",
9445
+ name: "Wernicke's Area",
9446
+ function: "Language Comprehension",
9447
+ color: "#ff66bb",
9448
+ detectors: ["sycophantic-tendency", "negative-skew"]
9449
+ },
9450
+ {
9451
+ id: "amygdala",
9452
+ name: "Amygdala",
9453
+ function: "Emotional Processing",
9454
+ color: "#ff5555",
9455
+ detectors: ["over-apologizing", "negative-skew"]
9456
+ },
9457
+ {
9458
+ id: "anterior-cingulate",
9459
+ name: "Anterior Cingulate",
9460
+ function: "Conflict Monitoring",
9461
+ color: "#ffcc22",
9462
+ detectors: ["sycophantic-tendency", "boundary-violation"]
9463
+ },
9464
+ {
9465
+ id: "hippocampus",
9466
+ name: "Hippocampus",
9467
+ function: "Memory & Context",
9468
+ color: "#44dd88",
9469
+ detectors: ["error-spiral"]
9470
+ },
9471
+ {
9472
+ id: "temporal-lobe",
9473
+ name: "Temporal Lobe",
9474
+ function: "Understanding & Tone",
9475
+ color: "#44dd88",
9476
+ detectors: ["negative-skew", "register-inconsistency"]
9477
+ },
9478
+ {
9479
+ id: "cerebellum",
9480
+ name: "Cerebellum",
9481
+ function: "Behavioral Fine-Tuning",
9482
+ color: "#22ccaa",
9483
+ detectors: ["register-inconsistency", "over-verbose"]
9484
+ },
9485
+ {
9486
+ id: "thalamus",
9487
+ name: "Thalamus",
9488
+ function: "Relay Hub",
9489
+ color: "#ff8844",
9490
+ detectors: []
9491
+ // activated by overall health, not specific detectors
9492
+ }
9493
+ ];
9494
+ var SEVERITY_INTENSITY = {
9495
+ info: 0.1,
9496
+ warning: 0.6,
9497
+ concern: 1
9498
+ };
9499
+ var AMBIENT_INTENSITY = 0.08;
9500
+ function healthToGrade(health) {
9501
+ if (health >= 85) return "A";
9502
+ if (health >= 70) return "B";
9503
+ if (health >= 50) return "C";
9504
+ if (health >= 30) return "D";
9505
+ return "F";
9506
+ }
9507
+ function calculateHealth(patterns) {
9508
+ if (patterns.length === 0) return 100;
9509
+ const penalties = patterns.map((p) => {
9510
+ if (p.severity === "concern") return 25;
9511
+ if (p.severity === "warning") return 15;
9512
+ return 5;
9513
+ });
9514
+ return Math.max(0, 100 - penalties.reduce((a, b) => a + b, 0));
9515
+ }
9516
+ function mapDiagnosisToBrainEvent(diagnosis, latestMessage) {
9517
+ const activePatternIds = new Set(diagnosis.patterns.map((p) => p.id));
9518
+ const regions = BRAIN_REGIONS.map((region) => {
9519
+ const activatingPatterns = region.detectors.filter((d) => activePatternIds.has(d));
9520
+ let intensity = AMBIENT_INTENSITY;
9521
+ if (activatingPatterns.length > 0) {
9522
+ const maxIntensity = Math.max(
9523
+ ...activatingPatterns.map((pid) => {
9524
+ const pattern = diagnosis.patterns.find((p) => p.id === pid);
9525
+ return pattern ? SEVERITY_INTENSITY[pattern.severity] || 0.3 : 0.3;
9526
+ })
9527
+ );
9528
+ intensity = maxIntensity;
9529
+ }
9530
+ if (region.id === "thalamus") {
9531
+ const health2 = calculateHealth(diagnosis.patterns);
9532
+ intensity = health2 < 70 ? (100 - health2) / 100 : AMBIENT_INTENSITY;
9533
+ }
9534
+ return {
9535
+ id: region.id,
9536
+ name: region.name,
9537
+ function: region.function,
9538
+ color: region.color,
9539
+ intensity,
9540
+ patterns: activatingPatterns
9541
+ };
9542
+ });
9543
+ const patterns = diagnosis.patterns.map((p) => ({
9544
+ id: p.id,
9545
+ name: p.name,
9546
+ severity: p.severity,
9547
+ percentage: p.percentage,
9548
+ description: p.description
9549
+ }));
9550
+ const health = calculateHealth(diagnosis.patterns);
9551
+ return {
9552
+ type: "diagnosis",
9553
+ timestamp: diagnosis.timestamp,
9554
+ health,
9555
+ grade: healthToGrade(health),
9556
+ messageCount: diagnosis.messagesAnalyzed,
9557
+ regions,
9558
+ patterns,
9559
+ activity: latestMessage ? {
9560
+ role: latestMessage.role,
9561
+ preview: latestMessage.content.slice(0, 80)
9562
+ } : null
9563
+ };
9564
+ }
9565
+
9566
+ // src/live/snapshot.ts
9567
+ var SHARE_BASE = "https://app.holomime.dev/brain";
9568
+ function encodeSnapshot(event, agentName) {
9569
+ const compact = {
9570
+ h: event.health,
9571
+ g: event.grade,
9572
+ m: event.messageCount,
9573
+ a: agentName,
9574
+ r: event.regions.filter((r) => r.intensity > 0).map((r) => ({ i: r.id, n: Math.round(r.intensity * 100) / 100 })),
9575
+ p: event.patterns.map((p) => ({
9576
+ i: p.id,
9577
+ s: p.severity,
9578
+ c: Math.round(p.percentage * 10) / 10
9579
+ }))
9580
+ };
9581
+ const json = JSON.stringify(compact);
9582
+ const compressed = deflateSync(Buffer.from(json));
9583
+ return compressed.toString("base64url");
9584
+ }
9585
+ function generateShareUrl(diagnosis, agentName) {
9586
+ const brainEvent = mapDiagnosisToBrainEvent(diagnosis);
9587
+ const encoded = encodeSnapshot(brainEvent, agentName ?? "agent");
9588
+ return `${SHARE_BASE}?d=${encoded}`;
9589
+ }
9590
+ function copyToClipboard(text) {
9591
+ try {
9592
+ if (process.platform === "darwin") {
9593
+ execSync("pbcopy", { input: text });
9594
+ return true;
9595
+ } else if (process.platform === "linux") {
9596
+ execSync("xclip -selection clipboard", { input: text });
9597
+ return true;
9598
+ } else if (process.platform === "win32") {
9599
+ execSync("clip", { input: text });
9600
+ return true;
9601
+ }
9602
+ } catch {
9603
+ }
9604
+ return false;
9605
+ }
9606
+ function printShareLink(url, copied) {
9607
+ console.log("");
9608
+ console.log(
9609
+ chalk.green(" \u2713 ") + chalk.bold("Share your agent's brain:")
9610
+ );
9611
+ console.log("");
9612
+ console.log(" " + chalk.cyan(url));
9613
+ console.log("");
9614
+ if (copied) {
9615
+ console.log(chalk.dim(" Link copied to clipboard."));
9616
+ }
9617
+ }
9618
+ function shareFromDiagnosis(diagnosis, agentName) {
9619
+ const url = generateShareUrl(diagnosis, agentName);
9620
+ const copied = copyToClipboard(url);
9621
+ printShareLink(url, copied);
9622
+ }
9623
+
9422
9624
  // src/core/oversight.ts
9423
9625
  var DEFAULT_OVERSIGHT = {
9424
9626
  mode: "review",
@@ -11740,6 +11942,172 @@ var syncProfileSchema = z5.object({
11740
11942
  hold: z5.array(z5.string()).default(["filled_pause", "gaze_away", "hand_raise"])
11741
11943
  }).default({})
11742
11944
  });
11945
+
11946
+ // src/integrations/langchain.ts
11947
+ var HolomimeCallbackHandler = class {
11948
+ name = "holomime";
11949
+ // LangChain expects these to be set
11950
+ lc_serializable = false;
11951
+ guard;
11952
+ mode;
11953
+ minSeverity;
11954
+ onViolation;
11955
+ messageBuffer = [];
11956
+ bufferSize;
11957
+ currentRunMessages = /* @__PURE__ */ new Map();
11958
+ _stats = {
11959
+ totalResponses: 0,
11960
+ passed: 0,
11961
+ violated: 0,
11962
+ blocked: 0,
11963
+ patternCounts: {}
11964
+ };
11965
+ constructor(options = {}) {
11966
+ this.mode = options.mode ?? "monitor";
11967
+ this.minSeverity = options.minSeverity ?? "warning";
11968
+ this.onViolation = options.onViolation;
11969
+ this.bufferSize = options.bufferSize ?? 50;
11970
+ const agentName = options.name ?? "langchain-agent";
11971
+ this.guard = Guard.create(agentName).useAll();
11972
+ if (options.personality) {
11973
+ if (typeof options.personality === "string") {
11974
+ loadSpec(options.personality);
11975
+ }
11976
+ }
11977
+ }
11978
+ /**
11979
+ * Called when an LLM starts generating.
11980
+ * Captures the input messages for context.
11981
+ */
11982
+ handleLLMStart(_llm, prompts, runId) {
11983
+ const key = runId ?? "default";
11984
+ const messages = prompts.map((p) => ({
11985
+ role: "user",
11986
+ content: p
11987
+ }));
11988
+ this.currentRunMessages.set(key, messages);
11989
+ }
11990
+ /**
11991
+ * Called when an LLM finishes generating.
11992
+ * Runs behavioral analysis on the response.
11993
+ */
11994
+ handleLLMEnd(output, runId) {
11995
+ const key = runId ?? "default";
11996
+ const responseText = this.extractResponseText(output);
11997
+ if (!responseText) return;
11998
+ this._stats.totalResponses++;
11999
+ const runMessages = this.currentRunMessages.get(key) ?? [];
12000
+ const contextMessages = [
12001
+ ...this.messageBuffer.slice(-this.bufferSize),
12002
+ ...runMessages,
12003
+ { role: "assistant", content: responseText }
12004
+ ];
12005
+ this.messageBuffer.push(
12006
+ ...runMessages,
12007
+ { role: "assistant", content: responseText }
12008
+ );
12009
+ if (this.messageBuffer.length > this.bufferSize) {
12010
+ this.messageBuffer = this.messageBuffer.slice(-this.bufferSize);
12011
+ }
12012
+ this.currentRunMessages.delete(key);
12013
+ const result = this.guard.run(contextMessages);
12014
+ if (result.passed || !this.severityMeetsMin(result.severity)) {
12015
+ this._stats.passed++;
12016
+ return;
12017
+ }
12018
+ this._stats.violated++;
12019
+ for (const p of result.patterns) {
12020
+ this._stats.patternCounts[p.id] = (this._stats.patternCounts[p.id] || 0) + 1;
12021
+ }
12022
+ const violation = {
12023
+ patterns: result.patterns,
12024
+ severity: result.severity,
12025
+ response: responseText,
12026
+ runId,
12027
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
12028
+ };
12029
+ this.onViolation?.(violation);
12030
+ if (this.mode === "strict" && result.severity === "concern") {
12031
+ this._stats.blocked++;
12032
+ throw new HolomimeViolationError(violation);
12033
+ }
12034
+ }
12035
+ /**
12036
+ * Called on LLM errors. Clean up run tracking.
12037
+ */
12038
+ handleLLMError(_error, runId) {
12039
+ const key = runId ?? "default";
12040
+ this.currentRunMessages.delete(key);
12041
+ }
12042
+ /**
12043
+ * Called when a chain starts. Captures input for context.
12044
+ */
12045
+ handleChainStart(_chain, inputs, runId) {
12046
+ const key = runId ?? "default";
12047
+ const inputText = inputs.input ?? inputs.question ?? inputs.query ?? "";
12048
+ if (typeof inputText === "string" && inputText) {
12049
+ const existing = this.currentRunMessages.get(key) ?? [];
12050
+ existing.push({ role: "user", content: inputText });
12051
+ this.currentRunMessages.set(key, existing);
12052
+ }
12053
+ }
12054
+ /**
12055
+ * Get cumulative stats.
12056
+ */
12057
+ stats() {
12058
+ return {
12059
+ ...this._stats,
12060
+ patternCounts: { ...this._stats.patternCounts }
12061
+ };
12062
+ }
12063
+ /**
12064
+ * Reset the message buffer and stats.
12065
+ */
12066
+ reset() {
12067
+ this.messageBuffer = [];
12068
+ this.currentRunMessages.clear();
12069
+ this._stats = {
12070
+ totalResponses: 0,
12071
+ passed: 0,
12072
+ violated: 0,
12073
+ blocked: 0,
12074
+ patternCounts: {}
12075
+ };
12076
+ }
12077
+ /**
12078
+ * Get the current guard result for the buffered conversation.
12079
+ */
12080
+ diagnose() {
12081
+ return this.guard.run(this.messageBuffer);
12082
+ }
12083
+ // ─── Private helpers ──────────────────────────────────────
12084
+ severityMeetsMin(severity) {
12085
+ if (this.minSeverity === "warning") return severity !== "clean";
12086
+ if (this.minSeverity === "concern") return severity === "concern";
12087
+ return false;
12088
+ }
12089
+ extractResponseText(output) {
12090
+ if (output?.generations?.[0]?.[0]?.text) {
12091
+ return output.generations[0][0].text;
12092
+ }
12093
+ if (output?.generations?.[0]?.[0]?.message?.content) {
12094
+ return output.generations[0][0].message.content;
12095
+ }
12096
+ if (typeof output === "string") {
12097
+ return output;
12098
+ }
12099
+ return null;
12100
+ }
12101
+ };
12102
+ var HolomimeViolationError = class extends Error {
12103
+ violation;
12104
+ constructor(violation) {
12105
+ const patternNames = violation.patterns.map((p) => p.name).join(", ");
12106
+ super(`HoloMime behavioral violation (${violation.severity}): ${patternNames}`);
12107
+ this.name = "HolomimeViolationError";
12108
+ this.violation = violation;
12109
+ }
12110
+ };
11743
12111
  export {
11744
12112
  ARCHETYPES,
11745
12113
  ATTACHMENT_STYLES,
@@ -11749,6 +12117,8 @@ export {
11749
12117
  DEFAULT_OVERSIGHT,
11750
12118
  DIMENSIONS,
11751
12119
  Guard,
12120
+ HolomimeCallbackHandler,
12121
+ HolomimeViolationError,
11752
12122
  LEARNING_ORIENTATIONS,
11753
12123
  LocalMarketplaceBackend,
11754
12124
  MarketplaceClient,
@@ -11801,6 +12171,7 @@ export {
11801
12171
  conversationLogSchema,
11802
12172
  conversationSchema,
11803
12173
  convertToHFFormat,
12174
+ copyToClipboard,
11804
12175
  corpusStats,
11805
12176
  createBehavioralMemory,
11806
12177
  createGist,
@@ -11828,6 +12199,7 @@ export {
11828
12199
  domainSchema,
11829
12200
  embodimentSchema,
11830
12201
  emitBehavioralEvent,
12202
+ encodeSnapshot,
11831
12203
  estimateConfidence,
11832
12204
  evaluateOutcome,
11833
12205
  expireOldEdges,
@@ -11862,6 +12234,7 @@ export {
11862
12234
  generatePrescriptions,
11863
12235
  generateProgressReport,
11864
12236
  generateReACTReport,
12237
+ generateShareUrl,
11865
12238
  generateSystemPrompt,
11866
12239
  gestureSchema,
11867
12240
  getAdversarialCategories,
@@ -11980,6 +12353,7 @@ export {
11980
12353
  severityMeetsThreshold2 as severityMeetsThreshold,
11981
12354
  severitySchema,
11982
12355
  shareAnonymizedPatterns,
12356
+ shareFromDiagnosis,
11983
12357
  startFleet,
11984
12358
  startMCPServer,
11985
12359
  startWatch,