FiberWise Node.js SDK (v1.0.0)

Complete Node.js and browser SDK for the FiberWise Platform.

Installation

The Node.js SDK is included with your Fiberwise installation. Reference it locally in your apps:

# Navigate to the SDK directory
cd fiber-sdk-nodejs

# Install dependencies
npm install

💡 Requirements

  • Node.js 14+ or modern browser
  • ES6 support

Quick Start

Basic Setup (JavaScript/ES Modules)

import FiberWise from 'fiberwise';

// Initialize with configuration
const fiber = new Fiberwise({
  baseUrl: 'https://api.fiberwise.ai/api/v1',
  apiKey: 'your-api-key', 
  appId: 'your-app-id'
});

// Example usage
async function main() {
  try {
    // List data items
    const users = await fiber.data.listItems('users');
    console.log('Users:', users);

    // Run a function
    const result = await fiber.functions.activate('processData', { param: 'value' });
    
    // Real-time communication
    fiber.realtime.on('message', (msg) => {
      console.log('Received message:', msg);
    });
    
    await fiber.realtime.connect();
  } catch (error) {
    console.error('Realtime connection error:', error);
    throw error; // Re-throw to allow caller to handle
  }
}

main();

Basic Setup (CommonJS)

const FiberWise = require('fiberwise');

// Initialize with configuration
const fiber = new Fiberwise({
  baseUrl: 'https://api.fiberwise.ai/api/v1',
  apiKey: process.env.FIBERWISE_API_KEY,
  appId: process.env.FIBERWISE_APP_ID
});

// Example usage
async function main() {
  try {
    // Get app details
    const app = await fiber.apps.getDetails();
    console.log('App:', app.name);

    // Stream agent responses
    const controller = await fiber.agents.activateStreaming(
      'chat-agent',
      { message: 'Hello' },
      {},
      {},
      {
        onMessage: (chunk) => console.log('Stream chunk:', chunk),
        onComplete: (result) => console.log('Stream completed:', result),
        onError: (error) => console.error('Stream error:', error)
      }
    );
    
    // Close stream when done
    setTimeout(() => {
      try {
        controller.close();
      } catch (closeError) {
        console.error('Error closing stream:', closeError);
      }
    }, 5000);
  } catch (error) {
    console.error('Agent activation error:', error);
    throw error;
  }
}

main();

Core Components

1. FiberApp - Main SDK Entry Point

import { FiberApp, FiberConfig } from '@fiberwise/sdk';

interface FiberConfig {
  baseUrl: string;
  apiKey: string;
  appId?: string;
  agentApiKey?: string;
  sessionId?: string;
  useLocal?: boolean;
}

// Production configuration
const productionConfig: FiberConfig = {
  baseUrl: 'https://api.fiberwise.ai/api/v1',
  apiKey: 'fw_1234567890abcdef1234567890abcdef',
  appId: 'my-node-app',
  sessionId: 'session_abc123'
};

// Development configuration
const devConfig: FiberConfig = {
  appId: 'my-dev-app',
  useLocal: true
};

const fiber = new FiberApp(productionConfig);

// Access services
const agents = fiber.agents;       // 🤖 Agent management
const data = fiber.data;           // 📊 Dynamic data storage
const storage = fiber.storage;     // 📁 File storage
const realtime = fiber.realtime;   // ⚡ Real-time messaging
const oauth = fiber.oauth;         // 🔐 OAuth management

2. Agent Management

// List and filter agents
const agents = await fiber.agents.list({
  page: 1,
  pageSize: 25,
  orderBy: 'created',
  orderDirection: 'DESC',
  activeOnly: true
});

// Get specific agent
const agent = await fiber.agents.get('agent-123');
console.log(`Agent: ${agent.name} (${agent.agentType})`);

// Create new agent
const newAgent = await fiber.agents.create({
  name: 'Content Analyzer',
  description: 'Analyzes content for key insights',
  systemPrompt: 'You are a content analysis expert.',
  model: 'gpt-4',
  temperature: 0.7,
  maxTokens: 1000,
  tools: [
    {
      type: 'function',
      function: {
        name: 'analyze_sentiment',
        description: 'Analyze text sentiment',
        parameters: {
          type: 'object',
          properties: {
            text: { type: 'string' }
          }
        }
      }
    }
  ]
});

// Activate agent
const result = await fiber.agents.activate(newAgent.id, {
  text: 'This is amazing technology!',
  analysis_type: 'comprehensive'
});

console.log('Analysis result:', result.output);

3. Streaming Responses

// Stream agent responses with callbacks
const stream = await fiber.agents.activateStreaming(
  'agent-123',
  { prompt: 'Write a story about AI' },
  {
    onMessage: (chunk) => {
      try {
        process.stdout.write(chunk);
      } catch (writeError) {
        console.error('Error writing chunk:', writeError);
      }
    },
    onComplete: (result) => {
      console.log('\nStream completed successfully:', result);
    },
    onError: (error) => {
      console.error('Stream encountered an error:', error);
      throw error; // Re-throw to propagate
    }
  }
);

// Alternative: async iterator approach
for await (const chunk of stream) {
  process.stdout.write(chunk);
}

4. Dynamic Data Operations

// Key-value operations
fiber.data.set('userPreferences', {
  theme: 'dark',
  language: 'en',
  notifications: true
});

const preferences = fiber.data.get('userPreferences');
const theme = fiber.data.get('theme', 'light'); // with default

// Structured data models
const userInteraction = await fiber.data.create('user_interactions', {
  userId: 'user-12345',
  action: 'chat_message',
  content: 'Hello, AI assistant!',
  timestamp: new Date().toISOString(),
  metadata: {
    sessionId: 'session-789',
    source: 'web_app'
  }
});

// Query data
const recentInteractions = await fiber.data.query('user_interactions', {
  filters: {
    userId: 'user-12345',
    action: 'chat_message'
  },
  orderBy: 'timestamp',
  orderDirection: 'DESC',
  limit: 10
});

5. File Storage

import fs from 'fs';

// Upload file
const fileBuffer = fs.readFileSync('document.pdf');
const fileUrl = await fiber.storage.upload({
  file: fileBuffer,
  filename: 'document.pdf',
  contentType: 'application/pdf',
  metadata: { category: 'docs', userId: 'user-123' }
});

// Store data as file
await fiber.storage.store('report_2024', {
  results: [1, 2, 3],
  summary: 'Analysis complete'
}, { type: 'json_report' });

// Retrieve files
const fileData = await fiber.storage.retrieve('report_2024');
const downloadUrl = await fiber.storage.getUrl('document.pdf');

// List files
const files = await fiber.storage.list({
  prefix: 'reports/',
  limit: 20
});

Browser Testing Integration

Node.js Testing with Playwright

import { test, expect } from '@playwright/test';
import FiberWise from 'fiberwise';

// Integration test combining browser automation and SDK
test('complete agent workflow test', async ({ page }) => {
  // Initialize SDK
  const fiber = new Fiberwise({
    baseUrl: 'http://localhost:6701',
    apiKey: 'test-api-key'
  });

  try {
    // Step 1: Create test agent via SDK
    const agent = await fiber.agents.create({
      name: 'Test Chat Agent',
      description: 'Agent for browser testing',
      systemPrompt: 'You are a helpful test assistant.',
      model: 'gpt-3.5-turbo'
    });

    // Step 2: Test agent creation in browser
    await page.goto('http://localhost:6701/agents');

    // Verify agent appears in UI
    await expect(page.locator(`text=${agent.name}`)).toBeVisible();

    // Step 3: Test agent activation through UI
    await page.click(`[data-agent-id="${agent.id}"]`);
    await page.fill('#message-input', 'Hello, test agent!');
    await page.click('#send-button');

    // Step 4: Verify response
    await expect(page.locator('.agent-response')).toBeVisible();

    // Step 5: Validate via SDK
    const activationResult = await fiber.agents.activate(agent.id, {
      message: 'SDK validation test'
    });

    expect(activationResult.status).toBe('success');

  } catch (error) {
    console.error('Test failed:', error);
    throw error;
  } finally {
    // Clean up resources if needed
    try {
      if (fiber.realtime && fiber.realtime.isConnected) {
        await fiber.realtime.disconnect();
      }
    } catch (cleanupError) {
      console.error('Cleanup error:', cleanupError);
    }
  }
});

Automated Testing Workflow

// automated-test-runner.ts
import { spawn } from 'child_process';
import FiberWise from 'fiberwise';
import fs from 'fs/promises';

/**
 * @typedef {Object} TestScript
 * @property {string} script_name
 * @property {string} description
 * @property {Object} settings
 * @property {boolean} settings.headless
 * @property {number} settings.slow_motion
 * @property {boolean} settings.video_recording
 * @property {Array} steps
 * @property {string} steps.id
 * @property {string} steps.type
 * @property {string} steps.action
 * @property {any} steps.config
 */

class NodeJsTestRunner {
  private fiber: FiberWise;

  constructor(config: any) {
    this.fiber = new FiberApp(config);
  }

  async runTestScript(script: TestScript): Promise {
    console.log(`Running test: ${script.script_name}`);

    try {
      // Save script to temp file
      const scriptPath = './temp-test-script.json';
      await fs.writeFile(scriptPath, JSON.stringify(script, null, 2));

      // Run Python script runner
      const result = await this.runPythonScript(scriptPath);

      if (result.success) {
        console.log('✅ Browser test completed successfully');

        // Validate results with SDK
        await this.validateResults(script);
        return true;
      } else {
        console.error('❌ Browser test failed:', result.error);
        return false;
      }
    } catch (error) {
      console.error('Test runner error:', error);
      return false;
    }
  }

  private async runPythonScript(scriptPath) {
    return new Promise((resolve) => {
      const python = spawn('python', [
        'json_script_runner_modular.py',
        scriptPath
      ], {
        cwd: '../fiberwise-browser-tests'
      });

      let output = '';
      let error = '';

      python.stdout.on('data', (data) => {
        output += data.toString();
      });

      python.stderr.on('data', (data) => {
        error += data.toString();
      });

      python.on('close', (code) => {
        if (code !== 0) {
          console.error('Python script failed:', error);
        }
        resolve({
          success: code === 0,
          error: code !== 0 ? error : undefined
        });
      });

      python.on('error', (err) => {
        console.error('Python process error:', err);
        resolve({
          success: false,
          error: err.message
        });
      });
    });
  }

  private async validateResults(script: TestScript): Promise {
    // Validate test results using SDK
    for (const step of script.steps) {
      if (step.type === 'agent' && step.action === 'create') {
        // Check if agent was created
        const agents = await this.fiber.agents.list();
        const testAgent = agents.find(a => a.name.includes('Test'));

        if (testAgent) {
          console.log(`✅ Validation: Agent ${testAgent.name} created successfully`);

          // Test activation
          const result = await this.fiber.agents.activate(testAgent.id, {
            test: 'validation'
          });

          console.log(`✅ Validation: Agent activation successful`);
        }
      }
    }
  }

  async close(): Promise {
    await this.fiber.close();
  }
}

// Usage example
async function runAutomatedTests() {
  const testRunner = new NodeJsTestRunner({
    baseUrl: 'https://api.fiberwise.ai/api/v1',
    apiKey: process.env.FIBERWISE_API_KEY
  });

  const testScript: TestScript = {
    script_name: 'nodejs_integration_test',
    description: 'Complete Node.js SDK integration test',
    settings: {
      headless: false,
      slow_motion: 500,
      video_recording: true
    },
    steps: [
      {
        id: 'create_instance',
        type: 'instance',
        action: 'create',
        config: {
          port: 'random',
          bootstrap: true
        }
      },
      {
        id: 'test_agent_workflow',
        type: 'browser',
        action: 'test_complete_workflow',
        config: {
          test_type: 'agent_creation_and_activation'
        }
      }
    ]
  };

  try {
    const success = await testRunner.runTestScript(testScript);
    console.log(`Test completed: ${success ? 'PASSED' : 'FAILED'}`);
  } finally {
    await testRunner.close();
  }
}

if (require.main === module) {
  runAutomatedTests();
}