v2/docs/sdk/SDK-ADVANCED-FEATURES-INTEGRATION.md
Version: 2.5.0-alpha.130 Date: 2025-09-30 Status: Design Phase
This document explores how to integrate two advanced Claude Code SDK features into Claude-Flow's swarm orchestration system:
// Discovered in @anthropic-ai/claude-code CLI source
interface NetworkPermission {
hostPattern: { host: string; port: number };
allow: boolean;
rememberForSession: boolean;
}
// Implementation pattern (inferred from minified code)
function promptNetworkAccess(
hostPattern: { host: string; port: number }
): Promise<NetworkPermissionResponse> {
// SDK prompts user for approval
// Returns: { allow: boolean, rememberForSession: boolean }
}
Key Capabilities:
Scenario: Different agents need different network access levels
Implementation:
// src/swarm/network-policy-manager.ts
import { AgentType, SwarmConfig } from './types';
interface AgentNetworkPolicy {
agentType: AgentType;
allowedHosts: Array<{ host: string; port: number }>;
deniedHosts: Array<{ host: string; port: number }>;
defaultBehavior: 'allow' | 'deny' | 'prompt';
}
export class NetworkPolicyManager {
private policies: Map<AgentType, AgentNetworkPolicy> = new Map();
constructor() {
this.initializeDefaultPolicies();
}
private initializeDefaultPolicies() {
// Research agent - broad access
this.policies.set('researcher', {
agentType: 'researcher',
allowedHosts: [
{ host: '*.anthropic.com', port: 443 },
{ host: '*.github.com', port: 443 },
{ host: '*.stackoverflow.com', port: 443 },
{ host: '*.npmjs.com', port: 443 }
],
deniedHosts: [],
defaultBehavior: 'prompt'
});
// Coder agent - restricted to documentation and package registries
this.policies.set('coder', {
agentType: 'coder',
allowedHosts: [
{ host: 'api.github.com', port: 443 },
{ host: 'registry.npmjs.org', port: 443 },
{ host: 'pypi.org', port: 443 }
],
deniedHosts: [],
defaultBehavior: 'deny'
});
// Analyst agent - no network access (sandboxed)
this.policies.set('analyst', {
agentType: 'analyst',
allowedHosts: [],
deniedHosts: [{ host: '*', port: '*' }],
defaultBehavior: 'deny'
});
// Optimizer agent - metrics endpoints only
this.policies.set('optimizer', {
agentType: 'optimizer',
allowedHosts: [
{ host: 'api.anthropic.com', port: 443 }
],
deniedHosts: [],
defaultBehavior: 'deny'
});
}
async checkNetworkAccess(
agentType: AgentType,
host: string,
port: number,
sessionId: string
): Promise<{ allowed: boolean; reason: string }> {
const policy = this.policies.get(agentType);
if (!policy) {
return { allowed: false, reason: 'No policy found for agent type' };
}
// Check explicit denials first
if (this.isHostDenied(host, port, policy.deniedHosts)) {
return {
allowed: false,
reason: `Host ${host}:${port} is explicitly denied for ${agentType} agents`
};
}
// Check explicit allows
if (this.isHostAllowed(host, port, policy.allowedHosts)) {
return {
allowed: true,
reason: `Host ${host}:${port} is whitelisted for ${agentType} agents`
};
}
// Apply default behavior
switch (policy.defaultBehavior) {
case 'allow':
return { allowed: true, reason: 'Default allow policy' };
case 'deny':
return { allowed: false, reason: 'Default deny policy' };
case 'prompt':
// Delegate to SDK's interactive prompt
return await this.promptUserForAccess(agentType, host, port, sessionId);
}
}
private isHostAllowed(
host: string,
port: number,
allowedHosts: Array<{ host: string; port: number }>
): boolean {
return allowedHosts.some(pattern =>
this.matchesPattern(host, pattern.host) &&
(pattern.port === '*' || pattern.port === port)
);
}
private isHostDenied(
host: string,
port: number,
deniedHosts: Array<{ host: string; port: number }>
): boolean {
return deniedHosts.some(pattern =>
this.matchesPattern(host, pattern.host) &&
(pattern.port === '*' || pattern.port === port)
);
}
private matchesPattern(host: string, pattern: string): boolean {
// Wildcard pattern matching
const regex = new RegExp(
'^' + pattern.replace(/\*/g, '.*').replace(/\./g, '\\.') + '$'
);
return regex.test(host);
}
private async promptUserForAccess(
agentType: AgentType,
host: string,
port: number,
sessionId: string
): Promise<{ allowed: boolean; reason: string }> {
// Use SDK's native network prompt
const response = await this.sdkNetworkPrompt({ host, port });
if (response.rememberForSession) {
// Cache decision for this session
this.cacheSessionDecision(sessionId, host, port, response.allow);
}
return {
allowed: response.allow,
reason: response.allow
? `User approved access to ${host}:${port}`
: `User denied access to ${host}:${port}`
};
}
async setAgentPolicy(agentType: AgentType, policy: AgentNetworkPolicy): Promise<void> {
this.policies.set(agentType, policy);
}
async getAgentPolicy(agentType: AgentType): Promise<AgentNetworkPolicy | undefined> {
return this.policies.get(agentType);
}
}
Scenario: Entire swarm operates in restricted network environment
// src/swarm/swarm-network-manager.ts
export class SwarmNetworkManager {
private policyManager: NetworkPolicyManager;
private swarmSessions: Map<string, NetworkSessionData> = new Map();
async initializeSwarm(
swarmId: string,
config: SwarmNetworkConfig
): Promise<void> {
this.swarmSessions.set(swarmId, {
isolationMode: config.isolationMode,
allowedHosts: config.allowedHosts || [],
deniedHosts: config.deniedHosts || [],
agentPermissions: new Map()
});
}
async beforeAgentNetworkRequest(
agentId: string,
agentType: AgentType,
request: NetworkRequest
): Promise<NetworkRequestResult> {
const swarmId = this.getSwarmIdForAgent(agentId);
const session = this.swarmSessions.get(swarmId);
if (!session) {
throw new Error(`No network session found for swarm ${swarmId}`);
}
// Check swarm-level restrictions first
if (session.isolationMode === 'strict') {
const swarmAllowed = this.isHostAllowedInSwarm(
request.host,
request.port,
session
);
if (!swarmAllowed) {
return {
allowed: false,
reason: `Swarm ${swarmId} operates in strict isolation mode`,
blockedBy: 'swarm-policy'
};
}
}
// Check agent-level policy
const agentCheck = await this.policyManager.checkNetworkAccess(
agentType,
request.host,
request.port,
agentId
);
if (!agentCheck.allowed) {
return {
allowed: false,
reason: agentCheck.reason,
blockedBy: 'agent-policy'
};
}
// Record permission grant for audit
this.recordNetworkAccess(swarmId, agentId, request);
return {
allowed: true,
reason: 'Approved by swarm and agent policies'
};
}
async getSwarmNetworkAudit(swarmId: string): Promise<NetworkAuditLog> {
// Return complete audit trail of network requests
return {
swarmId,
totalRequests: this.getTotalRequests(swarmId),
approvedRequests: this.getApprovedRequests(swarmId),
deniedRequests: this.getDeniedRequests(swarmId),
requestsByAgent: this.getRequestsByAgent(swarmId),
requestsByHost: this.getRequestsByHost(swarmId)
};
}
}
Scenario: Adjust network policies based on swarm behavior
// src/swarm/adaptive-network-policy.ts
export class AdaptiveNetworkPolicy {
async analyzeSwarmBehavior(swarmId: string): Promise<PolicyRecommendations> {
const audit = await this.networkManager.getSwarmNetworkAudit(swarmId);
const recommendations: PolicyRecommendations = {
expansions: [],
restrictions: [],
warnings: []
};
// Detect patterns of denied requests
const frequentlyDenied = this.findFrequentlyDeniedHosts(audit);
if (frequentlyDenied.length > 0) {
recommendations.warnings.push({
type: 'frequent-denials',
hosts: frequentlyDenied,
suggestion: 'Consider adding these hosts to allowlist if trusted'
});
}
// Detect suspicious network patterns
const suspiciousActivity = this.detectSuspiciousPatterns(audit);
if (suspiciousActivity.length > 0) {
recommendations.restrictions.push({
type: 'suspicious-activity',
details: suspiciousActivity,
action: 'Recommend restricting network access for affected agents'
});
}
return recommendations;
}
private detectSuspiciousPatterns(audit: NetworkAuditLog): SuspiciousPattern[] {
const patterns: SuspiciousPattern[] = [];
// Port scanning detection
const portScans = this.detectPortScanning(audit);
if (portScans.length > 0) {
patterns.push({
type: 'port-scan',
agents: portScans,
severity: 'high'
});
}
// Unusual TLD access
const unusualTLDs = this.detectUnusualTLDs(audit);
if (unusualTLDs.length > 0) {
patterns.push({
type: 'unusual-tld',
hosts: unusualTLDs,
severity: 'medium'
});
}
return patterns;
}
}
// Discovered in @anthropic-ai/claude-code CLI source
window.__REACT_DEVTOOLS_COMPONENT_FILTERS__
// SDK includes full React DevTools backend for TUI rendering
// React Fiber profiling
// Component tree inspection
// Performance timeline tracking
Key Capabilities:
Scenario: Real-time visualization of swarm topology and agent states
// src/ui/swarm-devtools.tsx
import React, { useEffect, useState } from 'react';
import { Box, Text, useApp } from 'ink';
interface SwarmNode {
id: string;
type: string;
status: 'idle' | 'busy' | 'failed';
connections: string[];
metrics: {
tasksCompleted: number;
avgExecutionTime: number;
errorRate: number;
};
}
export const SwarmDevToolsDashboard: React.FC<{
swarmId: string;
}> = ({ swarmId }) => {
const [topology, setTopology] = useState<SwarmNode[]>([]);
const [selectedNode, setSelectedNode] = useState<string | null>(null);
useEffect(() => {
// Subscribe to swarm state updates
const unsubscribe = SwarmMonitor.subscribe(swarmId, (state) => {
setTopology(state.agents);
});
return unsubscribe;
}, [swarmId]);
return (
<Box flexDirection="column" padding={1}>
<Box borderStyle="round" borderColor="cyan">
<Text bold color="cyan">
🐝 Swarm Topology: {swarmId}
</Text>
</Box>
<Box flexDirection="row" marginTop={1}>
<Box flexDirection="column" width="50%">
{topology.map((node) => (
<AgentCard
key={node.id}
node={node}
selected={selectedNode === node.id}
onSelect={() => setSelectedNode(node.id)}
/>
))}
</Box>
<Box flexDirection="column" width="50%" paddingLeft={2}>
{selectedNode && (
<AgentDetailsPanel
node={topology.find((n) => n.id === selectedNode)!}
/>
)}
</Box>
</Box>
<Box marginTop={2}>
<SwarmNetworkGraph topology={topology} />
</Box>
</Box>
);
};
Scenario: Profile individual agent performance using React Fiber data
// src/profiling/agent-profiler.ts
export class AgentProfiler {
private fiberData: Map<string, FiberPerformanceData> = new Map();
async captureAgentProfile(agentId: string): Promise<AgentProfile> {
// Hook into React DevTools profiling API
const profiler = this.getReactProfiler();
// Start profiling
profiler.startProfiling();
// Let agent execute
await this.executeAgentTasks(agentId);
// Stop and collect data
const profilingData = profiler.stopProfiling();
return this.analyzeProfilingData(agentId, profilingData);
}
private analyzeProfilingData(
agentId: string,
data: ReactProfilingData
): AgentProfile {
return {
agentId,
totalRenderTime: data.commitTime,
componentBreakdown: data.durations.map(([id, duration]) => ({
component: this.getComponentName(id),
renderTime: duration,
percentage: (duration / data.commitTime) * 100
})),
slowestComponents: this.findSlowestComponents(data),
renderCount: data.durations.length,
recommendations: this.generateOptimizationRecommendations(data)
};
}
private generateOptimizationRecommendations(
data: ReactProfilingData
): Recommendation[] {
const recommendations: Recommendation[] = [];
// Detect unnecessary re-renders
const unnecessaryRerenders = this.detectUnnecessaryRerenders(data);
if (unnecessaryRerenders.length > 0) {
recommendations.push({
type: 'unnecessary-rerenders',
severity: 'medium',
components: unnecessaryRerenders,
suggestion: 'Add React.memo or useMemo to prevent unnecessary renders'
});
}
// Detect expensive computations
const expensiveComputations = this.detectExpensiveComputations(data);
if (expensiveComputations.length > 0) {
recommendations.push({
type: 'expensive-computations',
severity: 'high',
components: expensiveComputations,
suggestion: 'Move expensive computations to useMemo or worker threads'
});
}
return recommendations;
}
}
Scenario: Live dashboard showing all swarm activity
// src/ui/swarm-monitor.tsx
export const SwarmMonitorUI: React.FC = () => {
const [swarms, setSwarms] = useState<SwarmState[]>([]);
const [metrics, setMetrics] = useState<SwarmMetrics>({});
useEffect(() => {
// Enable React DevTools bridge
if (typeof window !== 'undefined') {
window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = {
inject: (renderer) => {
// Hook into React renderer for swarm components
this.interceptSwarmComponents(renderer);
}
};
}
// Subscribe to swarm updates
const unsubscribe = SwarmCoordinator.subscribeToAll((updates) => {
setSwarms(updates.swarms);
setMetrics(updates.metrics);
});
return unsubscribe;
}, []);
return (
<Box flexDirection="column">
<Box borderStyle="double" borderColor="green">
<Text bold color="green">
🌊 Claude-Flow Swarm Monitor v2.5.0
</Text>
</Box>
<Box flexDirection="row" flexWrap="wrap" marginTop={1}>
{swarms.map((swarm) => (
<SwarmCard
key={swarm.id}
swarm={swarm}
metrics={metrics[swarm.id]}
/>
))}
</Box>
<Box marginTop={2} borderStyle="single" borderColor="cyan">
<GlobalMetricsPanel metrics={this.aggregateMetrics(metrics)} />
</Box>
<Box marginTop={2}>
<PerformanceTimeline swarms={swarms} />
</Box>
</Box>
);
};
NetworkPolicyManager class| Metric | Target | Measurement |
|---|---|---|
| Network Policy Violations | 0 | Audit log analysis |
| Dashboard Render Performance | <16ms | React DevTools profiler |
| Agent Profile Collection Overhead | <5% | Benchmark comparison |
| Network Request Latency | <2ms added | Performance tests |
// claude-flow.config.ts
export default {
swarm: {
networkPolicies: {
researcher: {
allowedHosts: ['*.github.com', '*.stackoverflow.com'],
defaultBehavior: 'prompt'
},
coder: {
allowedHosts: ['registry.npmjs.org', 'pypi.org'],
defaultBehavior: 'deny'
},
analyst: {
allowedHosts: [],
defaultBehavior: 'deny' // Fully sandboxed
}
},
networkIsolation: {
mode: 'strict', // 'strict' | 'permissive' | 'audit-only'
allowedGlobalHosts: ['api.anthropic.com']
}
},
devTools: {
enabled: true,
dashboard: {
port: 3000,
enableProfiling: true,
updateInterval: 1000
}
}
};
Integration design for Claude-Flow v2.5.0-alpha.130