agentic-qe 2.8.0 → 2.8.2
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/CHANGELOG.md +148 -0
- package/README.md +1 -1
- package/dist/agents/BaseAgent.d.ts +329 -0
- package/dist/agents/BaseAgent.d.ts.map +1 -1
- package/dist/agents/BaseAgent.js +657 -0
- package/dist/agents/BaseAgent.js.map +1 -1
- package/dist/cli/commands/supabase/index.d.ts +20 -0
- package/dist/cli/commands/supabase/index.d.ts.map +1 -0
- package/dist/cli/commands/supabase/index.js +632 -0
- package/dist/cli/commands/supabase/index.js.map +1 -0
- package/dist/cli/index.js +3 -0
- package/dist/cli/index.js.map +1 -1
- package/dist/code-intelligence/embeddings/EmbeddingCacheFactory.d.ts +135 -0
- package/dist/code-intelligence/embeddings/EmbeddingCacheFactory.d.ts.map +1 -0
- package/dist/code-intelligence/embeddings/EmbeddingCacheFactory.js +301 -0
- package/dist/code-intelligence/embeddings/EmbeddingCacheFactory.js.map +1 -0
- package/dist/code-intelligence/embeddings/NomicEmbedder.d.ts +78 -6
- package/dist/code-intelligence/embeddings/NomicEmbedder.d.ts.map +1 -1
- package/dist/code-intelligence/embeddings/NomicEmbedder.js +162 -21
- package/dist/code-intelligence/embeddings/NomicEmbedder.js.map +1 -1
- package/dist/code-intelligence/embeddings/backends/MemoryBackend.d.ts +59 -0
- package/dist/code-intelligence/embeddings/backends/MemoryBackend.d.ts.map +1 -0
- package/dist/code-intelligence/embeddings/backends/MemoryBackend.js +173 -0
- package/dist/code-intelligence/embeddings/backends/MemoryBackend.js.map +1 -0
- package/dist/code-intelligence/embeddings/backends/RedisBackend.d.ts +50 -0
- package/dist/code-intelligence/embeddings/backends/RedisBackend.d.ts.map +1 -0
- package/dist/code-intelligence/embeddings/backends/RedisBackend.js +279 -0
- package/dist/code-intelligence/embeddings/backends/RedisBackend.js.map +1 -0
- package/dist/code-intelligence/embeddings/backends/SQLiteBackend.d.ts +64 -0
- package/dist/code-intelligence/embeddings/backends/SQLiteBackend.d.ts.map +1 -0
- package/dist/code-intelligence/embeddings/backends/SQLiteBackend.js +314 -0
- package/dist/code-intelligence/embeddings/backends/SQLiteBackend.js.map +1 -0
- package/dist/code-intelligence/embeddings/backends/index.d.ts +16 -0
- package/dist/code-intelligence/embeddings/backends/index.d.ts.map +1 -0
- package/dist/code-intelligence/embeddings/backends/index.js +28 -0
- package/dist/code-intelligence/embeddings/backends/index.js.map +1 -0
- package/dist/code-intelligence/embeddings/backends/types.d.ts +177 -0
- package/dist/code-intelligence/embeddings/backends/types.d.ts.map +1 -0
- package/dist/code-intelligence/embeddings/backends/types.js +30 -0
- package/dist/code-intelligence/embeddings/backends/types.js.map +1 -0
- package/dist/code-intelligence/embeddings/index.d.ts +7 -0
- package/dist/code-intelligence/embeddings/index.d.ts.map +1 -1
- package/dist/code-intelligence/embeddings/index.js +16 -1
- package/dist/code-intelligence/embeddings/index.js.map +1 -1
- package/dist/core/memory/HNSWVectorMemory.js +1 -1
- package/dist/infrastructure/index.d.ts +15 -0
- package/dist/infrastructure/index.d.ts.map +1 -0
- package/dist/infrastructure/index.js +44 -0
- package/dist/infrastructure/index.js.map +1 -0
- package/dist/infrastructure/network/AgentRateLimiter.d.ts +59 -0
- package/dist/infrastructure/network/AgentRateLimiter.d.ts.map +1 -0
- package/dist/infrastructure/network/AgentRateLimiter.js +186 -0
- package/dist/infrastructure/network/AgentRateLimiter.js.map +1 -0
- package/dist/infrastructure/network/AuditLogger.d.ts +102 -0
- package/dist/infrastructure/network/AuditLogger.d.ts.map +1 -0
- package/dist/infrastructure/network/AuditLogger.js +284 -0
- package/dist/infrastructure/network/AuditLogger.js.map +1 -0
- package/dist/infrastructure/network/DomainWhitelist.d.ts +111 -0
- package/dist/infrastructure/network/DomainWhitelist.d.ts.map +1 -0
- package/dist/infrastructure/network/DomainWhitelist.js +216 -0
- package/dist/infrastructure/network/DomainWhitelist.js.map +1 -0
- package/dist/infrastructure/network/NetworkPolicyManager.d.ts +97 -0
- package/dist/infrastructure/network/NetworkPolicyManager.d.ts.map +1 -0
- package/dist/infrastructure/network/NetworkPolicyManager.js +309 -0
- package/dist/infrastructure/network/NetworkPolicyManager.js.map +1 -0
- package/dist/infrastructure/network/index.d.ts +19 -0
- package/dist/infrastructure/network/index.d.ts.map +1 -0
- package/dist/infrastructure/network/index.js +46 -0
- package/dist/infrastructure/network/index.js.map +1 -0
- package/dist/infrastructure/network/policies/default-policies.d.ts +78 -0
- package/dist/infrastructure/network/policies/default-policies.d.ts.map +1 -0
- package/dist/infrastructure/network/policies/default-policies.js +312 -0
- package/dist/infrastructure/network/policies/default-policies.js.map +1 -0
- package/dist/infrastructure/network/types.d.ts +214 -0
- package/dist/infrastructure/network/types.d.ts.map +1 -0
- package/dist/infrastructure/network/types.js +25 -0
- package/dist/infrastructure/network/types.js.map +1 -0
- package/dist/infrastructure/sandbox/ResourceMonitor.d.ts +124 -0
- package/dist/infrastructure/sandbox/ResourceMonitor.d.ts.map +1 -0
- package/dist/infrastructure/sandbox/ResourceMonitor.js +305 -0
- package/dist/infrastructure/sandbox/ResourceMonitor.js.map +1 -0
- package/dist/infrastructure/sandbox/SandboxManager.d.ts +122 -0
- package/dist/infrastructure/sandbox/SandboxManager.d.ts.map +1 -0
- package/dist/infrastructure/sandbox/SandboxManager.js +527 -0
- package/dist/infrastructure/sandbox/SandboxManager.js.map +1 -0
- package/dist/infrastructure/sandbox/index.d.ts +18 -0
- package/dist/infrastructure/sandbox/index.d.ts.map +1 -0
- package/dist/infrastructure/sandbox/index.js +38 -0
- package/dist/infrastructure/sandbox/index.js.map +1 -0
- package/dist/infrastructure/sandbox/profiles/agent-profiles.d.ts +53 -0
- package/dist/infrastructure/sandbox/profiles/agent-profiles.d.ts.map +1 -0
- package/dist/infrastructure/sandbox/profiles/agent-profiles.js +433 -0
- package/dist/infrastructure/sandbox/profiles/agent-profiles.js.map +1 -0
- package/dist/infrastructure/sandbox/types.d.ts +227 -0
- package/dist/infrastructure/sandbox/types.d.ts.map +1 -0
- package/dist/infrastructure/sandbox/types.js +63 -0
- package/dist/infrastructure/sandbox/types.js.map +1 -0
- package/dist/mcp/handlers/NewDomainToolsHandler.d.ts +8 -8
- package/dist/mcp/handlers/NewDomainToolsHandler.d.ts.map +1 -1
- package/dist/mcp/handlers/NewDomainToolsHandler.js.map +1 -1
- package/dist/mcp/handlers/ruvector/RuVectorHandler.d.ts +54 -0
- package/dist/mcp/handlers/ruvector/RuVectorHandler.d.ts.map +1 -0
- package/dist/mcp/handlers/ruvector/RuVectorHandler.js +325 -0
- package/dist/mcp/handlers/ruvector/RuVectorHandler.js.map +1 -0
- package/dist/mcp/handlers/ruvector/index.d.ts +5 -0
- package/dist/mcp/handlers/ruvector/index.d.ts.map +1 -0
- package/dist/mcp/handlers/ruvector/index.js +9 -0
- package/dist/mcp/handlers/ruvector/index.js.map +1 -0
- package/dist/mcp/server-instructions.d.ts +1 -1
- package/dist/mcp/server-instructions.js +1 -1
- package/dist/mcp/server.d.ts.map +1 -1
- package/dist/mcp/server.js +100 -22
- package/dist/mcp/server.js.map +1 -1
- package/dist/nervous-system/adapters/BTSPAdapter.d.ts +342 -0
- package/dist/nervous-system/adapters/BTSPAdapter.d.ts.map +1 -0
- package/dist/nervous-system/adapters/BTSPAdapter.js +494 -0
- package/dist/nervous-system/adapters/BTSPAdapter.js.map +1 -0
- package/dist/nervous-system/adapters/CircadianController.d.ts +560 -0
- package/dist/nervous-system/adapters/CircadianController.d.ts.map +1 -0
- package/dist/nervous-system/adapters/CircadianController.js +882 -0
- package/dist/nervous-system/adapters/CircadianController.js.map +1 -0
- package/dist/nervous-system/adapters/GlobalWorkspaceAdapter.d.ts +337 -0
- package/dist/nervous-system/adapters/GlobalWorkspaceAdapter.d.ts.map +1 -0
- package/dist/nervous-system/adapters/GlobalWorkspaceAdapter.js +532 -0
- package/dist/nervous-system/adapters/GlobalWorkspaceAdapter.js.map +1 -0
- package/dist/nervous-system/adapters/HdcMemoryAdapter.d.ts +444 -0
- package/dist/nervous-system/adapters/HdcMemoryAdapter.d.ts.map +1 -0
- package/dist/nervous-system/adapters/HdcMemoryAdapter.js +715 -0
- package/dist/nervous-system/adapters/HdcMemoryAdapter.js.map +1 -0
- package/dist/nervous-system/adapters/ReflexLayer.d.ts +231 -0
- package/dist/nervous-system/adapters/ReflexLayer.d.ts.map +1 -0
- package/dist/nervous-system/adapters/ReflexLayer.js +309 -0
- package/dist/nervous-system/adapters/ReflexLayer.js.map +1 -0
- package/dist/nervous-system/index.d.ts +25 -0
- package/dist/nervous-system/index.d.ts.map +1 -0
- package/dist/nervous-system/index.js +80 -0
- package/dist/nervous-system/index.js.map +1 -0
- package/dist/nervous-system/integration/BTSPLearningEngine.d.ts +266 -0
- package/dist/nervous-system/integration/BTSPLearningEngine.d.ts.map +1 -0
- package/dist/nervous-system/integration/BTSPLearningEngine.js +587 -0
- package/dist/nervous-system/integration/BTSPLearningEngine.js.map +1 -0
- package/dist/nervous-system/integration/CircadianAgent.d.ts +389 -0
- package/dist/nervous-system/integration/CircadianAgent.d.ts.map +1 -0
- package/dist/nervous-system/integration/CircadianAgent.js +696 -0
- package/dist/nervous-system/integration/CircadianAgent.js.map +1 -0
- package/dist/nervous-system/integration/HybridPatternStore.d.ts +244 -0
- package/dist/nervous-system/integration/HybridPatternStore.d.ts.map +1 -0
- package/dist/nervous-system/integration/HybridPatternStore.js +622 -0
- package/dist/nervous-system/integration/HybridPatternStore.js.map +1 -0
- package/dist/nervous-system/integration/NervousSystemEnhancement.d.ts +459 -0
- package/dist/nervous-system/integration/NervousSystemEnhancement.d.ts.map +1 -0
- package/dist/nervous-system/integration/NervousSystemEnhancement.js +921 -0
- package/dist/nervous-system/integration/NervousSystemEnhancement.js.map +1 -0
- package/dist/nervous-system/integration/WorkspaceAgent.d.ts +398 -0
- package/dist/nervous-system/integration/WorkspaceAgent.d.ts.map +1 -0
- package/dist/nervous-system/integration/WorkspaceAgent.js +722 -0
- package/dist/nervous-system/integration/WorkspaceAgent.js.map +1 -0
- package/dist/nervous-system/integration/index.d.ts +22 -0
- package/dist/nervous-system/integration/index.d.ts.map +1 -0
- package/dist/nervous-system/integration/index.js +44 -0
- package/dist/nervous-system/integration/index.js.map +1 -0
- package/dist/nervous-system/persistence/BTSPSerializer.d.ts +96 -0
- package/dist/nervous-system/persistence/BTSPSerializer.d.ts.map +1 -0
- package/dist/nervous-system/persistence/BTSPSerializer.js +223 -0
- package/dist/nervous-system/persistence/BTSPSerializer.js.map +1 -0
- package/dist/nervous-system/persistence/CircadianSerializer.d.ts +90 -0
- package/dist/nervous-system/persistence/CircadianSerializer.d.ts.map +1 -0
- package/dist/nervous-system/persistence/CircadianSerializer.js +239 -0
- package/dist/nervous-system/persistence/CircadianSerializer.js.map +1 -0
- package/dist/nervous-system/persistence/HdcSerializer.d.ts +100 -0
- package/dist/nervous-system/persistence/HdcSerializer.d.ts.map +1 -0
- package/dist/nervous-system/persistence/HdcSerializer.js +259 -0
- package/dist/nervous-system/persistence/HdcSerializer.js.map +1 -0
- package/dist/nervous-system/persistence/INervousSystemStore.d.ts +208 -0
- package/dist/nervous-system/persistence/INervousSystemStore.d.ts.map +1 -0
- package/dist/nervous-system/persistence/INervousSystemStore.js +11 -0
- package/dist/nervous-system/persistence/INervousSystemStore.js.map +1 -0
- package/dist/nervous-system/persistence/NervousSystemPersistenceManager.d.ts +187 -0
- package/dist/nervous-system/persistence/NervousSystemPersistenceManager.d.ts.map +1 -0
- package/dist/nervous-system/persistence/NervousSystemPersistenceManager.js +411 -0
- package/dist/nervous-system/persistence/NervousSystemPersistenceManager.js.map +1 -0
- package/dist/nervous-system/persistence/SQLiteNervousSystemStore.d.ts +98 -0
- package/dist/nervous-system/persistence/SQLiteNervousSystemStore.d.ts.map +1 -0
- package/dist/nervous-system/persistence/SQLiteNervousSystemStore.js +510 -0
- package/dist/nervous-system/persistence/SQLiteNervousSystemStore.js.map +1 -0
- package/dist/nervous-system/persistence/index.d.ts +22 -0
- package/dist/nervous-system/persistence/index.d.ts.map +1 -0
- package/dist/nervous-system/persistence/index.js +45 -0
- package/dist/nervous-system/persistence/index.js.map +1 -0
- package/dist/nervous-system/wasm-loader.d.ts +52 -0
- package/dist/nervous-system/wasm-loader.d.ts.map +1 -0
- package/dist/nervous-system/wasm-loader.js +188 -0
- package/dist/nervous-system/wasm-loader.js.map +1 -0
- package/dist/persistence/HybridPersistenceProvider.d.ts +184 -0
- package/dist/persistence/HybridPersistenceProvider.d.ts.map +1 -0
- package/dist/persistence/HybridPersistenceProvider.js +1086 -0
- package/dist/persistence/HybridPersistenceProvider.js.map +1 -0
- package/dist/persistence/IPersistenceProvider.d.ts +657 -0
- package/dist/persistence/IPersistenceProvider.d.ts.map +1 -0
- package/dist/persistence/IPersistenceProvider.js +11 -0
- package/dist/persistence/IPersistenceProvider.js.map +1 -0
- package/dist/persistence/SupabaseConfig.d.ts +176 -0
- package/dist/persistence/SupabaseConfig.d.ts.map +1 -0
- package/dist/persistence/SupabaseConfig.js +277 -0
- package/dist/persistence/SupabaseConfig.js.map +1 -0
- package/dist/persistence/SupabasePersistenceProvider.d.ts +143 -0
- package/dist/persistence/SupabasePersistenceProvider.d.ts.map +1 -0
- package/dist/persistence/SupabasePersistenceProvider.js +959 -0
- package/dist/persistence/SupabasePersistenceProvider.js.map +1 -0
- package/dist/persistence/adapters/CodeIntelligenceSyncAdapter.d.ts +213 -0
- package/dist/persistence/adapters/CodeIntelligenceSyncAdapter.d.ts.map +1 -0
- package/dist/persistence/adapters/CodeIntelligenceSyncAdapter.js +468 -0
- package/dist/persistence/adapters/CodeIntelligenceSyncAdapter.js.map +1 -0
- package/dist/persistence/adapters/MemorySyncAdapter.d.ts +115 -0
- package/dist/persistence/adapters/MemorySyncAdapter.d.ts.map +1 -0
- package/dist/persistence/adapters/MemorySyncAdapter.js +291 -0
- package/dist/persistence/adapters/MemorySyncAdapter.js.map +1 -0
- package/dist/persistence/adapters/index.d.ts +11 -0
- package/dist/persistence/adapters/index.d.ts.map +1 -0
- package/dist/persistence/adapters/index.js +20 -0
- package/dist/persistence/adapters/index.js.map +1 -0
- package/dist/persistence/index.d.ts +14 -0
- package/dist/persistence/index.d.ts.map +1 -1
- package/dist/persistence/index.js +36 -1
- package/dist/persistence/index.js.map +1 -1
- package/package.json +7 -1
|
@@ -0,0 +1,921 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* NervousSystemEnhancement - Mixin to Wire Nervous System into QE BaseAgent
|
|
4
|
+
*
|
|
5
|
+
* This module provides a mixin/enhancement to wire all nervous system integration
|
|
6
|
+
* components into QE BaseAgent, enabling:
|
|
7
|
+
* - HDC-accelerated pattern storage (50ns binding operations)
|
|
8
|
+
* - BTSP one-shot learning from failures (vs 10+ examples with RL)
|
|
9
|
+
* - Global Workspace attention coordination (Miller's Law: 7+/-2 items)
|
|
10
|
+
* - Circadian duty cycling (5-50x compute savings)
|
|
11
|
+
*
|
|
12
|
+
* Architecture:
|
|
13
|
+
* - enhanceWithNervousSystem(): Factory function to add capabilities to existing agent
|
|
14
|
+
* - WithNervousSystem(): Class decorator for auto-enhancement
|
|
15
|
+
* - NervousSystemFleetCoordinator: Fleet-wide coordination manager
|
|
16
|
+
*
|
|
17
|
+
* @module nervous-system/integration/NervousSystemEnhancement
|
|
18
|
+
* @version 1.0.0
|
|
19
|
+
*/
|
|
20
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
21
|
+
exports.createWorkspaceCoordinator = exports.createBTSPLearningEngine = exports.createHybridPatternStore = exports.NervousSystemFleetCoordinator = void 0;
|
|
22
|
+
exports.enhanceWithNervousSystem = enhanceWithNervousSystem;
|
|
23
|
+
exports.saveNervousSystemState = saveNervousSystemState;
|
|
24
|
+
exports.restoreNervousSystemState = restoreNervousSystemState;
|
|
25
|
+
exports.hasNervousSystemState = hasNervousSystemState;
|
|
26
|
+
exports.getNervousSystemState = getNervousSystemState;
|
|
27
|
+
exports.WithNervousSystem = WithNervousSystem;
|
|
28
|
+
const events_1 = require("events");
|
|
29
|
+
const Logger_js_1 = require("../../utils/Logger.js");
|
|
30
|
+
// Import all integration components
|
|
31
|
+
const HybridPatternStore_js_1 = require("./HybridPatternStore.js");
|
|
32
|
+
Object.defineProperty(exports, "createHybridPatternStore", { enumerable: true, get: function () { return HybridPatternStore_js_1.createHybridPatternStore; } });
|
|
33
|
+
const BTSPLearningEngine_js_1 = require("./BTSPLearningEngine.js");
|
|
34
|
+
Object.defineProperty(exports, "createBTSPLearningEngine", { enumerable: true, get: function () { return BTSPLearningEngine_js_1.createBTSPLearningEngine; } });
|
|
35
|
+
const WorkspaceAgent_js_1 = require("./WorkspaceAgent.js");
|
|
36
|
+
Object.defineProperty(exports, "createWorkspaceCoordinator", { enumerable: true, get: function () { return WorkspaceAgent_js_1.createWorkspaceCoordinator; } });
|
|
37
|
+
const CircadianAgent_js_1 = require("./CircadianAgent.js");
|
|
38
|
+
const CircadianController_js_1 = require("../adapters/CircadianController.js");
|
|
39
|
+
const SwarmMemoryManager_js_1 = require("../../core/memory/SwarmMemoryManager.js");
|
|
40
|
+
const HdcSerializer_js_1 = require("../persistence/HdcSerializer.js");
|
|
41
|
+
const BTSPSerializer_js_1 = require("../persistence/BTSPSerializer.js");
|
|
42
|
+
const CircadianSerializer_js_1 = require("../persistence/CircadianSerializer.js");
|
|
43
|
+
const wasm_loader_js_1 = require("../wasm-loader.js");
|
|
44
|
+
// WeakMap to store state without modifying agent prototype chain
|
|
45
|
+
const nervousSystemStates = new WeakMap();
|
|
46
|
+
// ============================================================================
|
|
47
|
+
// Enhancement Factory Function
|
|
48
|
+
// ============================================================================
|
|
49
|
+
/**
|
|
50
|
+
* Factory function to enhance a BaseAgent with nervous system capabilities
|
|
51
|
+
*
|
|
52
|
+
* This function adds nervous system features to an existing agent instance
|
|
53
|
+
* without modifying its class definition. It uses a mixin pattern to add
|
|
54
|
+
* new methods while preserving the original agent's functionality.
|
|
55
|
+
*
|
|
56
|
+
* @param agent - The BaseAgent instance to enhance
|
|
57
|
+
* @param config - Configuration for nervous system features
|
|
58
|
+
* @returns The enhanced agent with nervous system capabilities
|
|
59
|
+
*
|
|
60
|
+
* @example
|
|
61
|
+
* ```typescript
|
|
62
|
+
* const agent = await TestGeneratorAgent.create();
|
|
63
|
+
* const enhancedAgent = await enhanceWithNervousSystem(agent, {
|
|
64
|
+
* enableHdcPatterns: true,
|
|
65
|
+
* enableOneShotLearning: true,
|
|
66
|
+
* enableWorkspaceCoordination: true,
|
|
67
|
+
* enableCircadianCycling: true,
|
|
68
|
+
* });
|
|
69
|
+
*
|
|
70
|
+
* // Use HDC patterns
|
|
71
|
+
* await enhancedAgent.storePatternHdc(pattern);
|
|
72
|
+
* const results = await enhancedAgent.searchPatternsHdc(embedding, 10);
|
|
73
|
+
*
|
|
74
|
+
* // Use one-shot learning
|
|
75
|
+
* await enhancedAgent.learnOneShot({ taskId: 'task-1', error: 'Timeout', state, timestamp: Date.now() });
|
|
76
|
+
* const strategy = await enhancedAgent.recallStrategy(currentState);
|
|
77
|
+
*
|
|
78
|
+
* // Check workspace attention
|
|
79
|
+
* if (await enhancedAgent.hasAttention()) {
|
|
80
|
+
* // Proceed with full execution
|
|
81
|
+
* }
|
|
82
|
+
*
|
|
83
|
+
* // Check circadian phase
|
|
84
|
+
* if (enhancedAgent.shouldBeActive()) {
|
|
85
|
+
* // Run compute-intensive operations
|
|
86
|
+
* }
|
|
87
|
+
*
|
|
88
|
+
* // Get comprehensive stats
|
|
89
|
+
* const stats = enhancedAgent.getNervousSystemStats();
|
|
90
|
+
* ```
|
|
91
|
+
*/
|
|
92
|
+
async function enhanceWithNervousSystem(agent, config) {
|
|
93
|
+
const logger = Logger_js_1.Logger.getInstance();
|
|
94
|
+
const agentId = agent.getAgentId();
|
|
95
|
+
// Initialize state
|
|
96
|
+
const state = {
|
|
97
|
+
config,
|
|
98
|
+
initialized: false,
|
|
99
|
+
logger,
|
|
100
|
+
registeredWithWorkspace: false,
|
|
101
|
+
registeredWithCircadian: false,
|
|
102
|
+
};
|
|
103
|
+
nervousSystemStates.set(agent, state);
|
|
104
|
+
// Initialize HDC Pattern Store
|
|
105
|
+
if (config.enableHdcPatterns) {
|
|
106
|
+
try {
|
|
107
|
+
state.patternStore = (0, HybridPatternStore_js_1.createHybridPatternStore)({
|
|
108
|
+
dimension: 384,
|
|
109
|
+
metric: 'cosine',
|
|
110
|
+
enableMetrics: true,
|
|
111
|
+
hdc: {
|
|
112
|
+
similarityThreshold: 0.7,
|
|
113
|
+
maxRetrievalResults: 100,
|
|
114
|
+
autoInit: true,
|
|
115
|
+
...config.hdcConfig,
|
|
116
|
+
},
|
|
117
|
+
...config.patternStoreConfig,
|
|
118
|
+
});
|
|
119
|
+
await state.patternStore.initialize();
|
|
120
|
+
log(state, `HDC Pattern Store initialized for agent ${agentId.id}`);
|
|
121
|
+
}
|
|
122
|
+
catch (error) {
|
|
123
|
+
logWarn(state, `HDC Pattern Store initialization failed: ${error.message}`);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
// Initialize BTSP Learning Engine
|
|
127
|
+
if (config.enableOneShotLearning) {
|
|
128
|
+
try {
|
|
129
|
+
// Get memory store from agent
|
|
130
|
+
const memoryStore = getAgentMemoryStore(agent);
|
|
131
|
+
if (memoryStore instanceof SwarmMemoryManager_js_1.SwarmMemoryManager) {
|
|
132
|
+
state.btspEngine = (0, BTSPLearningEngine_js_1.createBTSPLearningEngine)(agentId.id, memoryStore, {
|
|
133
|
+
oneShotThreshold: 0,
|
|
134
|
+
recallConfidenceThreshold: 0.6,
|
|
135
|
+
consolidationInterval: 100,
|
|
136
|
+
autoConsolidate: true,
|
|
137
|
+
btspWeight: 0.7,
|
|
138
|
+
btsp: config.btspConfig,
|
|
139
|
+
...config.btspLearningConfig,
|
|
140
|
+
});
|
|
141
|
+
await state.btspEngine.initialize();
|
|
142
|
+
log(state, `BTSP Learning Engine initialized for agent ${agentId.id}`);
|
|
143
|
+
}
|
|
144
|
+
else {
|
|
145
|
+
logWarn(state, 'BTSP requires SwarmMemoryManager');
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
catch (error) {
|
|
149
|
+
logWarn(state, `BTSP Learning Engine initialization failed: ${error.message}`);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
// Initialize Workspace Coordinator (will be connected to fleet coordinator if available)
|
|
153
|
+
if (config.enableWorkspaceCoordination) {
|
|
154
|
+
try {
|
|
155
|
+
state.workspaceCoordinator = await (0, WorkspaceAgent_js_1.createWorkspaceCoordinator)();
|
|
156
|
+
await state.workspaceCoordinator.registerAgent(agent);
|
|
157
|
+
state.registeredWithWorkspace = true;
|
|
158
|
+
log(state, `Workspace Coordinator initialized for agent ${agentId.id}`);
|
|
159
|
+
}
|
|
160
|
+
catch (error) {
|
|
161
|
+
logWarn(state, `Workspace Coordinator initialization failed: ${error.message}`);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
// Initialize Circadian Manager
|
|
165
|
+
if (config.enableCircadianCycling) {
|
|
166
|
+
try {
|
|
167
|
+
// Create a circadian controller for this agent
|
|
168
|
+
state.circadianController = await (0, CircadianController_js_1.createTestingController)(60000); // 1 minute cycles for testing
|
|
169
|
+
state.circadianManager = new CircadianAgent_js_1.CircadianAgentManager({
|
|
170
|
+
controller: state.circadianController,
|
|
171
|
+
defaultCriticality: 'medium',
|
|
172
|
+
autoRegister: true,
|
|
173
|
+
checkIntervalMs: 1000,
|
|
174
|
+
debug: config.debug ?? false,
|
|
175
|
+
});
|
|
176
|
+
// Register agent with circadian manager
|
|
177
|
+
const phaseConfig = {
|
|
178
|
+
agentId: agentId.id,
|
|
179
|
+
agentType: agentId.type,
|
|
180
|
+
criticalityLevel: config.agentPhaseConfig?.criticalityLevel ?? 'medium',
|
|
181
|
+
minActiveHours: config.agentPhaseConfig?.minActiveHours ?? 4,
|
|
182
|
+
canRest: config.agentPhaseConfig?.canRest ?? true,
|
|
183
|
+
customDutyFactor: config.agentPhaseConfig?.customDutyFactor,
|
|
184
|
+
tags: config.agentPhaseConfig?.tags,
|
|
185
|
+
};
|
|
186
|
+
await state.circadianManager.registerAgent(agent, phaseConfig);
|
|
187
|
+
state.circadianManager.start();
|
|
188
|
+
state.registeredWithCircadian = true;
|
|
189
|
+
log(state, `Circadian Manager initialized for agent ${agentId.id}`);
|
|
190
|
+
}
|
|
191
|
+
catch (error) {
|
|
192
|
+
logWarn(state, `Circadian Manager initialization failed: ${error.message}`);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
state.initialized = true;
|
|
196
|
+
// Attach methods to agent
|
|
197
|
+
const enhancedAgent = agent;
|
|
198
|
+
// HDC Pattern methods
|
|
199
|
+
if (state.patternStore) {
|
|
200
|
+
enhancedAgent.storePatternHdc = async (pattern) => {
|
|
201
|
+
const st = nervousSystemStates.get(agent);
|
|
202
|
+
if (!st?.patternStore)
|
|
203
|
+
throw new Error('HDC Pattern Store not available');
|
|
204
|
+
await st.patternStore.storePattern(pattern);
|
|
205
|
+
};
|
|
206
|
+
enhancedAgent.searchPatternsHdc = async (embedding, k) => {
|
|
207
|
+
const st = nervousSystemStates.get(agent);
|
|
208
|
+
if (!st?.patternStore)
|
|
209
|
+
return [];
|
|
210
|
+
return st.patternStore.searchSimilar(embedding, { k });
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
// BTSP Learning methods
|
|
214
|
+
if (state.btspEngine) {
|
|
215
|
+
enhancedAgent.learnOneShot = async (failure) => {
|
|
216
|
+
const st = nervousSystemStates.get(agent);
|
|
217
|
+
if (!st?.btspEngine)
|
|
218
|
+
throw new Error('BTSP Learning Engine not available');
|
|
219
|
+
// Convert failure to learning experience
|
|
220
|
+
const feedback = {
|
|
221
|
+
taskId: failure.taskId,
|
|
222
|
+
rating: 0,
|
|
223
|
+
issues: [failure.error],
|
|
224
|
+
suggestions: [],
|
|
225
|
+
timestamp: new Date(failure.timestamp),
|
|
226
|
+
source: 'system',
|
|
227
|
+
};
|
|
228
|
+
await st.btspEngine.learnFromExecution({ type: 'failure-task', payload: { taskId: failure.taskId, context: failure.context } }, { success: false, error: failure.error }, feedback);
|
|
229
|
+
};
|
|
230
|
+
enhancedAgent.recallStrategy = async (taskState) => {
|
|
231
|
+
const st = nervousSystemStates.get(agent);
|
|
232
|
+
if (!st?.btspEngine)
|
|
233
|
+
return null;
|
|
234
|
+
const recommendation = await st.btspEngine.recommendWithBTSP(taskState);
|
|
235
|
+
return {
|
|
236
|
+
strategy: recommendation.strategy,
|
|
237
|
+
confidence: recommendation.confidence,
|
|
238
|
+
expectedImprovement: recommendation.expectedImprovement,
|
|
239
|
+
reasoning: recommendation.reasoning,
|
|
240
|
+
alternatives: recommendation.alternatives?.map(a => typeof a === 'string' ? a : a.strategy),
|
|
241
|
+
};
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
// Workspace coordination methods
|
|
245
|
+
if (state.workspaceCoordinator) {
|
|
246
|
+
enhancedAgent.broadcastToWorkspace = async (item) => {
|
|
247
|
+
const st = nervousSystemStates.get(agent);
|
|
248
|
+
if (!st?.workspaceCoordinator)
|
|
249
|
+
return false;
|
|
250
|
+
const workspaceItem = {
|
|
251
|
+
id: item.id,
|
|
252
|
+
agentId: agentId.id,
|
|
253
|
+
agentType: agentId.type,
|
|
254
|
+
content: item.content,
|
|
255
|
+
priority: item.priority,
|
|
256
|
+
relevance: item.relevance,
|
|
257
|
+
timestamp: Date.now(),
|
|
258
|
+
metadata: item.metadata,
|
|
259
|
+
};
|
|
260
|
+
return st.workspaceCoordinator.agentBroadcast(agentId.id, workspaceItem);
|
|
261
|
+
};
|
|
262
|
+
enhancedAgent.getWorkspaceItems = async () => {
|
|
263
|
+
const st = nervousSystemStates.get(agent);
|
|
264
|
+
if (!st?.workspaceCoordinator)
|
|
265
|
+
return [];
|
|
266
|
+
return st.workspaceCoordinator.getRelevantItems(agentId.type);
|
|
267
|
+
};
|
|
268
|
+
enhancedAgent.hasAttention = async () => {
|
|
269
|
+
const st = nervousSystemStates.get(agent);
|
|
270
|
+
if (!st?.workspaceCoordinator)
|
|
271
|
+
return true; // Default to true if not using workspace
|
|
272
|
+
return st.workspaceCoordinator.hasAttention(agentId.id);
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
// Circadian methods
|
|
276
|
+
if (state.circadianManager && state.circadianController) {
|
|
277
|
+
enhancedAgent.getCurrentPhase = () => {
|
|
278
|
+
const st = nervousSystemStates.get(agent);
|
|
279
|
+
if (!st?.circadianController)
|
|
280
|
+
return 'Active';
|
|
281
|
+
return st.circadianController.getPhase();
|
|
282
|
+
};
|
|
283
|
+
enhancedAgent.shouldBeActive = () => {
|
|
284
|
+
const st = nervousSystemStates.get(agent);
|
|
285
|
+
if (!st?.circadianManager)
|
|
286
|
+
return true;
|
|
287
|
+
return st.circadianManager.shouldBeActive(agentId.id);
|
|
288
|
+
};
|
|
289
|
+
enhancedAgent.getEnergySavings = () => {
|
|
290
|
+
const st = nervousSystemStates.get(agent);
|
|
291
|
+
if (!st?.circadianManager) {
|
|
292
|
+
return {
|
|
293
|
+
savedCycles: 0,
|
|
294
|
+
savingsPercentage: 0,
|
|
295
|
+
totalRestTime: 0,
|
|
296
|
+
totalActiveTime: 0,
|
|
297
|
+
averageDutyFactor: 1,
|
|
298
|
+
costReductionFactor: 1,
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
return st.circadianManager.getEnergySavings();
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
// Combined stats method
|
|
305
|
+
enhancedAgent.getNervousSystemStats = () => {
|
|
306
|
+
const st = nervousSystemStates.get(agent);
|
|
307
|
+
if (!st) {
|
|
308
|
+
return { initialized: false };
|
|
309
|
+
}
|
|
310
|
+
const stats = {
|
|
311
|
+
initialized: st.initialized,
|
|
312
|
+
};
|
|
313
|
+
// HDC stats
|
|
314
|
+
if (st.patternStore) {
|
|
315
|
+
const hdcMetrics = st.patternStore.getHdcMetrics();
|
|
316
|
+
stats.hdc = {
|
|
317
|
+
enabled: true,
|
|
318
|
+
patternCount: 0, // Will be populated asynchronously
|
|
319
|
+
hdcAvailable: st.patternStore.isHdcAvailable(),
|
|
320
|
+
avgSearchTimeNs: hdcMetrics.avgSearchTime,
|
|
321
|
+
hdcHitRate: hdcMetrics.hdcHitRate,
|
|
322
|
+
};
|
|
323
|
+
// Async stats - populate pattern count
|
|
324
|
+
st.patternStore.getStats().then(patternStats => {
|
|
325
|
+
if (stats.hdc) {
|
|
326
|
+
stats.hdc.patternCount = patternStats.count;
|
|
327
|
+
}
|
|
328
|
+
}).catch(() => { });
|
|
329
|
+
}
|
|
330
|
+
// BTSP stats
|
|
331
|
+
if (st.btspEngine) {
|
|
332
|
+
const btspMetrics = st.btspEngine.getMetrics();
|
|
333
|
+
stats.btsp = {
|
|
334
|
+
enabled: true,
|
|
335
|
+
totalExperiences: btspMetrics.totalExperiences,
|
|
336
|
+
oneShotLearnings: btspMetrics.btspLearningCount,
|
|
337
|
+
avgRecallConfidence: btspMetrics.avgBTSPRecallConfidence,
|
|
338
|
+
capacityUtilization: btspMetrics.btspCapacityUtilization,
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
// Workspace stats
|
|
342
|
+
if (st.workspaceCoordinator) {
|
|
343
|
+
const occupancy = st.workspaceCoordinator.getOccupancy();
|
|
344
|
+
const agentInfo = st.workspaceCoordinator.getAgentInfo(agentId.id);
|
|
345
|
+
stats.workspace = {
|
|
346
|
+
enabled: true,
|
|
347
|
+
registeredAgents: st.workspaceCoordinator.getAgentCount(),
|
|
348
|
+
occupancy,
|
|
349
|
+
hasAttention: agentInfo?.hasAttention ?? false,
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
// Circadian stats
|
|
353
|
+
if (st.circadianManager && st.circadianController) {
|
|
354
|
+
const savings = st.circadianManager.getEnergySavings();
|
|
355
|
+
stats.circadian = {
|
|
356
|
+
enabled: true,
|
|
357
|
+
currentPhase: st.circadianController.getPhase(),
|
|
358
|
+
savingsPercentage: savings.savingsPercentage,
|
|
359
|
+
costReductionFactor: savings.costReductionFactor,
|
|
360
|
+
isActive: st.circadianManager.shouldBeActive(agentId.id),
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
return stats;
|
|
364
|
+
};
|
|
365
|
+
log(state, `Agent ${agentId.id} enhanced with nervous system capabilities`);
|
|
366
|
+
return enhancedAgent;
|
|
367
|
+
}
|
|
368
|
+
// ============================================================================
|
|
369
|
+
// Persistence Functions
|
|
370
|
+
// ============================================================================
|
|
371
|
+
/**
|
|
372
|
+
* Save nervous system state for an agent
|
|
373
|
+
*
|
|
374
|
+
* Serializes all nervous system components (HDC, BTSP, Circadian) and saves
|
|
375
|
+
* them using the persistence manager. Call this in agent terminate() to
|
|
376
|
+
* preserve learned patterns across sessions.
|
|
377
|
+
*
|
|
378
|
+
* @param agent - The agent to save state for
|
|
379
|
+
* @param persistenceManager - The persistence manager to use
|
|
380
|
+
* @returns Promise resolving when state is saved
|
|
381
|
+
*
|
|
382
|
+
* @example
|
|
383
|
+
* ```typescript
|
|
384
|
+
* // In agent terminate():
|
|
385
|
+
* await saveNervousSystemState(this, persistenceManager);
|
|
386
|
+
* ```
|
|
387
|
+
*/
|
|
388
|
+
async function saveNervousSystemState(agent, persistenceManager) {
|
|
389
|
+
const state = nervousSystemStates.get(agent);
|
|
390
|
+
if (!state || !state.initialized) {
|
|
391
|
+
return; // No nervous system state to save
|
|
392
|
+
}
|
|
393
|
+
const agentId = agent.getAgentId().id;
|
|
394
|
+
const logger = state.logger;
|
|
395
|
+
try {
|
|
396
|
+
const savePromises = [];
|
|
397
|
+
// Save HDC state
|
|
398
|
+
if (state.patternStore) {
|
|
399
|
+
const hdcAdapter = state.patternStore.getHdcAdapter();
|
|
400
|
+
if (hdcAdapter && hdcAdapter.isInitialized()) {
|
|
401
|
+
const hdcState = (0, HdcSerializer_js_1.serializeHdcMemory)(hdcAdapter);
|
|
402
|
+
savePromises.push(persistenceManager.saveHdcState(agentId, hdcState));
|
|
403
|
+
logger.debug(`[${agentId}] Serialized HDC state: ${hdcState.patterns.length} patterns`);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
// Save BTSP state
|
|
407
|
+
if (state.btspEngine) {
|
|
408
|
+
const btspAdapter = state.btspEngine.getBTSPAdapter();
|
|
409
|
+
if (btspAdapter && btspAdapter.isInitialized()) {
|
|
410
|
+
const btspState = (0, BTSPSerializer_js_1.serializeBTSP)(btspAdapter);
|
|
411
|
+
savePromises.push(persistenceManager.saveBtspState(agentId, btspState));
|
|
412
|
+
logger.debug(`[${agentId}] Serialized BTSP state: ${btspState.associationCount} associations`);
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
// Save Circadian state
|
|
416
|
+
if (state.circadianController) {
|
|
417
|
+
const circadianState = (0, CircadianSerializer_js_1.serializeCircadian)(state.circadianController);
|
|
418
|
+
savePromises.push(persistenceManager.saveCircadianState(agentId, circadianState));
|
|
419
|
+
logger.debug(`[${agentId}] Serialized Circadian state: phase=${circadianState.state.phase}`);
|
|
420
|
+
}
|
|
421
|
+
await Promise.all(savePromises);
|
|
422
|
+
logger.info(`[${agentId}] Nervous system state saved successfully`);
|
|
423
|
+
}
|
|
424
|
+
catch (error) {
|
|
425
|
+
logger.warn(`[${agentId}] Failed to save nervous system state:`, error);
|
|
426
|
+
throw error;
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
/**
|
|
430
|
+
* Restore nervous system state for an agent
|
|
431
|
+
*
|
|
432
|
+
* Loads serialized state from the persistence manager and restores it into
|
|
433
|
+
* the agent's nervous system components. Call this in agent initialize()
|
|
434
|
+
* after nervous system enhancement to restore prior learnings.
|
|
435
|
+
*
|
|
436
|
+
* @param agent - The agent to restore state for
|
|
437
|
+
* @param persistenceManager - The persistence manager to use
|
|
438
|
+
* @returns Promise resolving when state is restored
|
|
439
|
+
*
|
|
440
|
+
* @example
|
|
441
|
+
* ```typescript
|
|
442
|
+
* // In agent initialize() after nervous system init:
|
|
443
|
+
* await restoreNervousSystemState(this, persistenceManager);
|
|
444
|
+
* ```
|
|
445
|
+
*/
|
|
446
|
+
async function restoreNervousSystemState(agent, persistenceManager) {
|
|
447
|
+
const state = nervousSystemStates.get(agent);
|
|
448
|
+
if (!state || !state.initialized) {
|
|
449
|
+
return; // No nervous system to restore into
|
|
450
|
+
}
|
|
451
|
+
const agentId = agent.getAgentId().id;
|
|
452
|
+
const logger = state.logger;
|
|
453
|
+
try {
|
|
454
|
+
// Load all states in parallel
|
|
455
|
+
const [hdcState, btspState, circadianState] = await Promise.all([
|
|
456
|
+
persistenceManager.loadHdcState(agentId),
|
|
457
|
+
persistenceManager.loadBtspState(agentId),
|
|
458
|
+
persistenceManager.loadCircadianState(agentId),
|
|
459
|
+
]);
|
|
460
|
+
// Restore HDC state
|
|
461
|
+
if (hdcState && state.patternStore) {
|
|
462
|
+
const hdcAdapter = state.patternStore.getHdcAdapter();
|
|
463
|
+
if (hdcAdapter && hdcAdapter.isInitialized()) {
|
|
464
|
+
(0, HdcSerializer_js_1.deserializeHdcMemory)(hdcState, hdcAdapter, wasm_loader_js_1.Hypervector);
|
|
465
|
+
logger.info(`[${agentId}] Restored HDC state: ${hdcState.patterns.length} patterns`);
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
// Restore BTSP state
|
|
469
|
+
if (btspState && state.btspEngine) {
|
|
470
|
+
const btspAdapter = state.btspEngine.getBTSPAdapter();
|
|
471
|
+
if (btspAdapter && btspAdapter.isInitialized()) {
|
|
472
|
+
(0, BTSPSerializer_js_1.deserializeBTSP)(btspState, btspAdapter);
|
|
473
|
+
logger.info(`[${agentId}] Restored BTSP state: ${btspState.associationCount} associations`);
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
// Restore Circadian state
|
|
477
|
+
if (circadianState && state.circadianController) {
|
|
478
|
+
(0, CircadianSerializer_js_1.deserializeCircadian)(circadianState, state.circadianController);
|
|
479
|
+
logger.info(`[${agentId}] Restored Circadian state: phase=${circadianState.state.phase}`);
|
|
480
|
+
}
|
|
481
|
+
logger.info(`[${agentId}] Nervous system state restored successfully`);
|
|
482
|
+
}
|
|
483
|
+
catch (error) {
|
|
484
|
+
logger.warn(`[${agentId}] Failed to restore nervous system state:`, error);
|
|
485
|
+
// Don't throw - agent can work with fresh state
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
/**
|
|
489
|
+
* Check if an agent has nervous system state that needs saving
|
|
490
|
+
*
|
|
491
|
+
* @param agent - The agent to check
|
|
492
|
+
* @returns True if agent has initialized nervous system
|
|
493
|
+
*/
|
|
494
|
+
function hasNervousSystemState(agent) {
|
|
495
|
+
const state = nervousSystemStates.get(agent);
|
|
496
|
+
return state?.initialized ?? false;
|
|
497
|
+
}
|
|
498
|
+
/**
|
|
499
|
+
* Get nervous system state for an agent (for advanced use cases)
|
|
500
|
+
*
|
|
501
|
+
* @param agent - The agent to get state for
|
|
502
|
+
* @returns The internal state or undefined
|
|
503
|
+
*/
|
|
504
|
+
function getNervousSystemState(agent) {
|
|
505
|
+
return nervousSystemStates.get(agent);
|
|
506
|
+
}
|
|
507
|
+
// ============================================================================
|
|
508
|
+
// Class Decorator
|
|
509
|
+
// ============================================================================
|
|
510
|
+
/**
|
|
511
|
+
* Decorator for agent class to auto-enhance with nervous system
|
|
512
|
+
*
|
|
513
|
+
* This decorator wraps the agent class constructor to automatically
|
|
514
|
+
* enhance instances with nervous system capabilities. The decorator
|
|
515
|
+
* intercepts the initialize() method to add nervous system enhancement.
|
|
516
|
+
*
|
|
517
|
+
* @param config - Configuration for nervous system features
|
|
518
|
+
* @returns Class decorator function
|
|
519
|
+
*
|
|
520
|
+
* @example
|
|
521
|
+
* ```typescript
|
|
522
|
+
* @WithNervousSystem({
|
|
523
|
+
* enableHdcPatterns: true,
|
|
524
|
+
* enableOneShotLearning: true,
|
|
525
|
+
* enableWorkspaceCoordination: true,
|
|
526
|
+
* enableCircadianCycling: true,
|
|
527
|
+
* })
|
|
528
|
+
* class MyTestAgent extends BaseAgent {
|
|
529
|
+
* // ... agent implementation
|
|
530
|
+
* }
|
|
531
|
+
*
|
|
532
|
+
* // Instances are automatically enhanced
|
|
533
|
+
* const agent = new MyTestAgent(config);
|
|
534
|
+
* await agent.initialize();
|
|
535
|
+
* // Now has all nervous system methods available
|
|
536
|
+
* ```
|
|
537
|
+
*/
|
|
538
|
+
function WithNervousSystem(config) {
|
|
539
|
+
return function (constructor) {
|
|
540
|
+
// Store the original initialize method
|
|
541
|
+
const originalInitialize = constructor.prototype.initialize;
|
|
542
|
+
// Override the initialize method on the prototype
|
|
543
|
+
constructor.prototype.initialize = async function () {
|
|
544
|
+
// Call the original initialize
|
|
545
|
+
await originalInitialize.call(this);
|
|
546
|
+
// Check if already enhanced
|
|
547
|
+
const existingState = nervousSystemStates.get(this);
|
|
548
|
+
if (!existingState?.initialized) {
|
|
549
|
+
// Enhance with nervous system
|
|
550
|
+
await enhanceWithNervousSystem(this, config);
|
|
551
|
+
}
|
|
552
|
+
};
|
|
553
|
+
// Add a marker to identify enhanced classes
|
|
554
|
+
Object.defineProperty(constructor, '_nervousSystemConfig', {
|
|
555
|
+
value: config,
|
|
556
|
+
writable: false,
|
|
557
|
+
enumerable: false,
|
|
558
|
+
});
|
|
559
|
+
return constructor;
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
// ============================================================================
|
|
563
|
+
// Fleet Coordinator
|
|
564
|
+
// ============================================================================
|
|
565
|
+
/**
|
|
566
|
+
* Global coordinator for fleet-wide nervous system management
|
|
567
|
+
*
|
|
568
|
+
* Manages workspace coordination and circadian cycling across all agents
|
|
569
|
+
* in a fleet, enabling coordinated attention and duty cycling.
|
|
570
|
+
*
|
|
571
|
+
* @example
|
|
572
|
+
* ```typescript
|
|
573
|
+
* const fleetCoordinator = new NervousSystemFleetCoordinator();
|
|
574
|
+
* await fleetCoordinator.initialize();
|
|
575
|
+
*
|
|
576
|
+
* // Register agents
|
|
577
|
+
* for (const agent of fleet.getAgents()) {
|
|
578
|
+
* await fleetCoordinator.registerAgent(agent, {
|
|
579
|
+
* enableWorkspaceCoordination: true,
|
|
580
|
+
* enableCircadianCycling: true,
|
|
581
|
+
* });
|
|
582
|
+
* }
|
|
583
|
+
*
|
|
584
|
+
* // Fleet-wide operations
|
|
585
|
+
* await fleetCoordinator.broadcastToAllAgents({
|
|
586
|
+
* id: 'fleet-alert',
|
|
587
|
+
* content: { type: 'priority-change' },
|
|
588
|
+
* priority: 0.9,
|
|
589
|
+
* relevance: 1.0,
|
|
590
|
+
* });
|
|
591
|
+
*
|
|
592
|
+
* // Enter rest phase for compute savings
|
|
593
|
+
* await fleetCoordinator.enterFleetRestPhase();
|
|
594
|
+
*
|
|
595
|
+
* // Get fleet statistics
|
|
596
|
+
* const stats = fleetCoordinator.getFleetStats();
|
|
597
|
+
* console.log(`Fleet savings: ${stats.circadianStats?.savingsPercentage}%`);
|
|
598
|
+
* ```
|
|
599
|
+
*/
|
|
600
|
+
class NervousSystemFleetCoordinator extends events_1.EventEmitter {
|
|
601
|
+
constructor(options) {
|
|
602
|
+
super();
|
|
603
|
+
this.logger = Logger_js_1.Logger.getInstance();
|
|
604
|
+
this.registeredAgents = new Map();
|
|
605
|
+
this.initialized = false;
|
|
606
|
+
this.debug = options?.debug ?? false;
|
|
607
|
+
}
|
|
608
|
+
/**
|
|
609
|
+
* Initialize the fleet coordinator
|
|
610
|
+
*/
|
|
611
|
+
async initialize() {
|
|
612
|
+
if (this.initialized)
|
|
613
|
+
return;
|
|
614
|
+
try {
|
|
615
|
+
// Initialize workspace coordinator
|
|
616
|
+
this.workspaceCoordinator = await (0, WorkspaceAgent_js_1.createWorkspaceCoordinator)();
|
|
617
|
+
this.log('Fleet workspace coordinator initialized');
|
|
618
|
+
// Initialize circadian controller and manager
|
|
619
|
+
this.circadianController = await (0, CircadianController_js_1.createTestingController)(60000);
|
|
620
|
+
this.circadianManager = new CircadianAgent_js_1.CircadianAgentManager({
|
|
621
|
+
controller: this.circadianController,
|
|
622
|
+
defaultCriticality: 'medium',
|
|
623
|
+
autoRegister: false,
|
|
624
|
+
checkIntervalMs: 1000,
|
|
625
|
+
debug: this.debug,
|
|
626
|
+
});
|
|
627
|
+
this.circadianManager.start();
|
|
628
|
+
this.log('Fleet circadian manager initialized');
|
|
629
|
+
this.initialized = true;
|
|
630
|
+
}
|
|
631
|
+
catch (error) {
|
|
632
|
+
this.logger.error('Fleet coordinator initialization failed:', error);
|
|
633
|
+
throw error;
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
/**
|
|
637
|
+
* Ensure coordinator is initialized
|
|
638
|
+
*/
|
|
639
|
+
ensureInitialized() {
|
|
640
|
+
if (!this.initialized) {
|
|
641
|
+
throw new Error('NervousSystemFleetCoordinator not initialized. Call initialize() first.');
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
/**
|
|
645
|
+
* Register an agent for fleet-wide nervous system coordination
|
|
646
|
+
*
|
|
647
|
+
* @param agent - The agent to register
|
|
648
|
+
* @param config - Nervous system configuration for this agent
|
|
649
|
+
*/
|
|
650
|
+
async registerAgent(agent, config) {
|
|
651
|
+
this.ensureInitialized();
|
|
652
|
+
const agentId = agent.getAgentId();
|
|
653
|
+
// Register with workspace coordinator if enabled
|
|
654
|
+
if (config.enableWorkspaceCoordination && this.workspaceCoordinator) {
|
|
655
|
+
await this.workspaceCoordinator.registerAgent(agent);
|
|
656
|
+
this.log(`Agent ${agentId.id} registered with fleet workspace`);
|
|
657
|
+
}
|
|
658
|
+
// Register with circadian manager if enabled
|
|
659
|
+
if (config.enableCircadianCycling && this.circadianManager) {
|
|
660
|
+
const phaseConfig = {
|
|
661
|
+
agentId: agentId.id,
|
|
662
|
+
agentType: agentId.type,
|
|
663
|
+
criticalityLevel: config.agentPhaseConfig?.criticalityLevel ?? 'medium',
|
|
664
|
+
minActiveHours: config.agentPhaseConfig?.minActiveHours ?? 4,
|
|
665
|
+
canRest: config.agentPhaseConfig?.canRest ?? true,
|
|
666
|
+
customDutyFactor: config.agentPhaseConfig?.customDutyFactor,
|
|
667
|
+
tags: config.agentPhaseConfig?.tags,
|
|
668
|
+
};
|
|
669
|
+
await this.circadianManager.registerAgent(agent, phaseConfig);
|
|
670
|
+
this.log(`Agent ${agentId.id} registered with fleet circadian manager`);
|
|
671
|
+
}
|
|
672
|
+
this.registeredAgents.set(agentId.id, { agent, config });
|
|
673
|
+
this.emit('agent:registered', { agentId: agentId.id, agentType: agentId.type });
|
|
674
|
+
}
|
|
675
|
+
/**
|
|
676
|
+
* Unregister an agent from fleet coordination
|
|
677
|
+
*
|
|
678
|
+
* @param agentId - ID of the agent to unregister
|
|
679
|
+
*/
|
|
680
|
+
async unregisterAgent(agentId) {
|
|
681
|
+
this.ensureInitialized();
|
|
682
|
+
const entry = this.registeredAgents.get(agentId);
|
|
683
|
+
if (!entry)
|
|
684
|
+
return;
|
|
685
|
+
// Unregister from workspace
|
|
686
|
+
if (entry.config.enableWorkspaceCoordination && this.workspaceCoordinator) {
|
|
687
|
+
await this.workspaceCoordinator.unregisterAgent(agentId);
|
|
688
|
+
}
|
|
689
|
+
// Unregister from circadian
|
|
690
|
+
if (entry.config.enableCircadianCycling && this.circadianManager) {
|
|
691
|
+
await this.circadianManager.unregisterAgent(agentId);
|
|
692
|
+
}
|
|
693
|
+
this.registeredAgents.delete(agentId);
|
|
694
|
+
this.emit('agent:unregistered', { agentId });
|
|
695
|
+
this.log(`Agent ${agentId} unregistered from fleet`);
|
|
696
|
+
}
|
|
697
|
+
// ============================================================================
|
|
698
|
+
// Fleet-Wide Operations
|
|
699
|
+
// ============================================================================
|
|
700
|
+
/**
|
|
701
|
+
* Broadcast a workspace item to all agents in the fleet
|
|
702
|
+
*
|
|
703
|
+
* @param item - The workspace item to broadcast
|
|
704
|
+
*/
|
|
705
|
+
async broadcastToAllAgents(item) {
|
|
706
|
+
this.ensureInitialized();
|
|
707
|
+
if (!this.workspaceCoordinator) {
|
|
708
|
+
throw new Error('Workspace coordinator not available');
|
|
709
|
+
}
|
|
710
|
+
// Broadcast to workspace - all registered agents will receive it
|
|
711
|
+
const entries = Array.from(this.registeredAgents.entries());
|
|
712
|
+
for (const [agentId, entry] of entries) {
|
|
713
|
+
if (entry.config.enableWorkspaceCoordination) {
|
|
714
|
+
const workspaceItem = {
|
|
715
|
+
id: `${item.id}-${agentId}`,
|
|
716
|
+
agentId,
|
|
717
|
+
agentType: entry.agent.getAgentId().type,
|
|
718
|
+
content: item.content,
|
|
719
|
+
priority: item.priority,
|
|
720
|
+
relevance: item.relevance,
|
|
721
|
+
timestamp: Date.now(),
|
|
722
|
+
metadata: item.metadata,
|
|
723
|
+
};
|
|
724
|
+
await this.workspaceCoordinator.agentBroadcast(agentId, workspaceItem);
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
// Run competition to allocate attention
|
|
728
|
+
await this.workspaceCoordinator.runCompetition();
|
|
729
|
+
this.log(`Broadcast item ${item.id} to ${this.registeredAgents.size} agents`);
|
|
730
|
+
}
|
|
731
|
+
/**
|
|
732
|
+
* Enter fleet-wide rest phase for compute savings
|
|
733
|
+
*/
|
|
734
|
+
async enterFleetRestPhase() {
|
|
735
|
+
this.ensureInitialized();
|
|
736
|
+
if (!this.circadianManager) {
|
|
737
|
+
throw new Error('Circadian manager not available');
|
|
738
|
+
}
|
|
739
|
+
await this.circadianManager.enterRestPhase();
|
|
740
|
+
this.emit('fleet:rest', { timestamp: Date.now() });
|
|
741
|
+
this.log('Fleet entered rest phase');
|
|
742
|
+
}
|
|
743
|
+
/**
|
|
744
|
+
* Wake the fleet from rest phase
|
|
745
|
+
*/
|
|
746
|
+
async wakeFleet() {
|
|
747
|
+
this.ensureInitialized();
|
|
748
|
+
if (!this.circadianManager) {
|
|
749
|
+
throw new Error('Circadian manager not available');
|
|
750
|
+
}
|
|
751
|
+
await this.circadianManager.enterActivePhase();
|
|
752
|
+
this.emit('fleet:wake', { timestamp: Date.now() });
|
|
753
|
+
this.log('Fleet woke from rest phase');
|
|
754
|
+
}
|
|
755
|
+
/**
|
|
756
|
+
* Coordinate a task across multiple agents
|
|
757
|
+
*
|
|
758
|
+
* @param request - Task coordination request
|
|
759
|
+
* @returns Coordination result
|
|
760
|
+
*/
|
|
761
|
+
async coordinateTask(request) {
|
|
762
|
+
this.ensureInitialized();
|
|
763
|
+
if (!this.workspaceCoordinator) {
|
|
764
|
+
throw new Error('Workspace coordinator not available');
|
|
765
|
+
}
|
|
766
|
+
return this.workspaceCoordinator.coordinateTask(request);
|
|
767
|
+
}
|
|
768
|
+
// ============================================================================
|
|
769
|
+
// Statistics and Monitoring
|
|
770
|
+
// ============================================================================
|
|
771
|
+
/**
|
|
772
|
+
* Get comprehensive fleet-wide statistics
|
|
773
|
+
*
|
|
774
|
+
* @returns Fleet nervous system statistics
|
|
775
|
+
*/
|
|
776
|
+
getFleetStats() {
|
|
777
|
+
const stats = {
|
|
778
|
+
totalAgents: this.registeredAgents.size,
|
|
779
|
+
enhancedAgents: 0,
|
|
780
|
+
};
|
|
781
|
+
// Count enhanced agents
|
|
782
|
+
const allEntries = Array.from(this.registeredAgents.values());
|
|
783
|
+
for (const entry of allEntries) {
|
|
784
|
+
if (entry.config.enableHdcPatterns ||
|
|
785
|
+
entry.config.enableOneShotLearning ||
|
|
786
|
+
entry.config.enableWorkspaceCoordination ||
|
|
787
|
+
entry.config.enableCircadianCycling) {
|
|
788
|
+
stats.enhancedAgents++;
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
// Workspace stats
|
|
792
|
+
if (this.workspaceCoordinator) {
|
|
793
|
+
const occupancy = this.workspaceCoordinator.getOccupancy();
|
|
794
|
+
const winners = this.workspaceCoordinator.getAttentionWinners();
|
|
795
|
+
stats.workspaceStats = {
|
|
796
|
+
occupancy,
|
|
797
|
+
attentionWinners: winners.map(w => w.agentId),
|
|
798
|
+
};
|
|
799
|
+
}
|
|
800
|
+
// Circadian stats
|
|
801
|
+
if (this.circadianManager && this.circadianController) {
|
|
802
|
+
const managerStats = this.circadianManager.getStats();
|
|
803
|
+
stats.circadianStats = {
|
|
804
|
+
phase: this.circadianController.getPhase(),
|
|
805
|
+
activeAgents: managerStats.activeAgents,
|
|
806
|
+
sleepingAgents: managerStats.sleepingAgents,
|
|
807
|
+
savingsPercentage: managerStats.savings.savingsPercentage,
|
|
808
|
+
};
|
|
809
|
+
}
|
|
810
|
+
return stats;
|
|
811
|
+
}
|
|
812
|
+
/**
|
|
813
|
+
* Get current attention winners
|
|
814
|
+
*
|
|
815
|
+
* @returns Array of agents that currently have attention
|
|
816
|
+
*/
|
|
817
|
+
getAttentionWinners() {
|
|
818
|
+
if (!this.workspaceCoordinator)
|
|
819
|
+
return [];
|
|
820
|
+
return this.workspaceCoordinator.getAttentionWinners();
|
|
821
|
+
}
|
|
822
|
+
/**
|
|
823
|
+
* Get current circadian phase
|
|
824
|
+
*
|
|
825
|
+
* @returns Current phase
|
|
826
|
+
*/
|
|
827
|
+
getCurrentPhase() {
|
|
828
|
+
if (!this.circadianController)
|
|
829
|
+
return 'Active';
|
|
830
|
+
return this.circadianController.getPhase();
|
|
831
|
+
}
|
|
832
|
+
/**
|
|
833
|
+
* Get fleet energy savings report
|
|
834
|
+
*
|
|
835
|
+
* @returns Energy savings report
|
|
836
|
+
*/
|
|
837
|
+
getEnergySavings() {
|
|
838
|
+
if (!this.circadianManager) {
|
|
839
|
+
return {
|
|
840
|
+
savedCycles: 0,
|
|
841
|
+
savingsPercentage: 0,
|
|
842
|
+
totalRestTime: 0,
|
|
843
|
+
totalActiveTime: 0,
|
|
844
|
+
averageDutyFactor: 1,
|
|
845
|
+
costReductionFactor: 1,
|
|
846
|
+
};
|
|
847
|
+
}
|
|
848
|
+
return this.circadianManager.getEnergySavings();
|
|
849
|
+
}
|
|
850
|
+
/**
|
|
851
|
+
* Advance circadian time (for testing/simulation)
|
|
852
|
+
*
|
|
853
|
+
* @param dt - Time to advance in milliseconds
|
|
854
|
+
*/
|
|
855
|
+
advanceTime(dt) {
|
|
856
|
+
if (this.circadianManager) {
|
|
857
|
+
this.circadianManager.advance(dt);
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
/**
|
|
861
|
+
* Cleanup and dispose of resources
|
|
862
|
+
*/
|
|
863
|
+
async dispose() {
|
|
864
|
+
// Unregister all agents
|
|
865
|
+
const agentIds = Array.from(this.registeredAgents.keys());
|
|
866
|
+
for (const agentId of agentIds) {
|
|
867
|
+
await this.unregisterAgent(agentId);
|
|
868
|
+
}
|
|
869
|
+
// Dispose components
|
|
870
|
+
if (this.workspaceCoordinator) {
|
|
871
|
+
this.workspaceCoordinator.dispose();
|
|
872
|
+
this.workspaceCoordinator = undefined;
|
|
873
|
+
}
|
|
874
|
+
if (this.circadianManager) {
|
|
875
|
+
await this.circadianManager.stop();
|
|
876
|
+
this.circadianManager = undefined;
|
|
877
|
+
}
|
|
878
|
+
if (this.circadianController) {
|
|
879
|
+
this.circadianController.dispose();
|
|
880
|
+
this.circadianController = undefined;
|
|
881
|
+
}
|
|
882
|
+
this.registeredAgents.clear();
|
|
883
|
+
this.initialized = false;
|
|
884
|
+
this.removeAllListeners();
|
|
885
|
+
this.log('Fleet coordinator disposed');
|
|
886
|
+
}
|
|
887
|
+
// ============================================================================
|
|
888
|
+
// Private Helpers
|
|
889
|
+
// ============================================================================
|
|
890
|
+
log(message) {
|
|
891
|
+
if (this.debug) {
|
|
892
|
+
console.log(`[NervousSystemFleetCoordinator] ${message}`);
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
exports.NervousSystemFleetCoordinator = NervousSystemFleetCoordinator;
|
|
897
|
+
// ============================================================================
|
|
898
|
+
// Utility Functions
|
|
899
|
+
// ============================================================================
|
|
900
|
+
/**
|
|
901
|
+
* Get the memory store from an agent (via reflection)
|
|
902
|
+
*/
|
|
903
|
+
function getAgentMemoryStore(agent) {
|
|
904
|
+
// Access protected member via any cast
|
|
905
|
+
return agent.memoryStore;
|
|
906
|
+
}
|
|
907
|
+
/**
|
|
908
|
+
* Log message if debug enabled
|
|
909
|
+
*/
|
|
910
|
+
function log(state, message) {
|
|
911
|
+
if (state.config.debug) {
|
|
912
|
+
console.log(`[NervousSystemEnhancement] ${message}`);
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
/**
|
|
916
|
+
* Log warning
|
|
917
|
+
*/
|
|
918
|
+
function logWarn(state, message) {
|
|
919
|
+
state.logger.warn(`[NervousSystemEnhancement] ${message}`);
|
|
920
|
+
}
|
|
921
|
+
//# sourceMappingURL=NervousSystemEnhancement.js.map
|