克劳德参议员
❌ 在建: 该项目正在大力建设中,不打算供公众使用/也没有发布到npm。下面README中的信息可能已经过时,建议用户自行决定。
A. 模型上下文协议(MCP) 服务器 克劳德人之间的沟通与语境共享。使Claude实例能够协作、共享上下文和分叉对话,而不会中断。
 ](https://www.npmjs.com/package/claude-senator)  ](https://nodejs.org/)
哲学
对人类来说简单,对克劳德来说丰富。
- 人:扩展到超丰富上下文的一行命令
- 克劳德:具有智能指针的密集协作智能
- 建筑:基于零依赖文件的IPC,具有漂亮的ASCII UI
安装
要求:
npm install -g claude-senator来自shell:
claude mcp add claude-senator -- npx claude-senator从内部克劳德 (需要重新启动):
Add this to our global mcp config: npx claude-senator从任何手动配置 mcp.json:(光标、风帆等)
{
"mcpServers": {
"claude-senator": {
"command": "npx",
"args": ["claude-senator"],
"env": {}
}
}
}特性
🏛️ Current:克劳德间信息系统
三功能界面
# Share context with other Claude instances
claude-senator send_context --target_pid 98471 --context_request "Help with documentation"
# Receive context from other Claude instances
claude-senator receive_context
# Live status of all Claude instances with collaboration recommendations
claude-senator status智能指针架构
使用指向现有上下文的指针进行超轻量级上下文共享 ~/.claude/projects/ 数据而不是复制内容:
// Instead of copying data (expensive)
const heavyMessage = {
conversationHistory: [
/* 1000s of messages */
],
fileContents: [
/* large file contents */
],
};
// We use smart pointers (lightweight)
const smartMessage = {
ctx_pointers: {
projects_dir: `~/.claude/projects/${projectEncoded}`,
conversation_history: this.getConversationPointer(),
git_context: this.getGitContextString(),
active_files: this.getActiveFilesArray(),
},
};漂亮的ASCII UI
╔═ 🏛️ ═══════════════════════════════════════════════════════════════════
║ → Claude 98471 • "Help with documentation..." • ~/.claude pointers sent
║ 🔄 Context shared • Ready for collaboration
╚═ 🚀 2 contexts processed • Rich collaboration network active🔄 新增:上下文分叉系统
问题
你有克劳德在工作(318,9.3k代币),想在不打断的情况下提问。
解决方案
上下文分叉创建具有继承上下文的新Claude实例,同时保留工作的Claude状态。
# Fork context from working Claude
claude-senator fork_claude --source_pid 98471 --query "What's the documentation structure?"
# Result: New session with full context + your question
# Working Claude continues uninterrupted技术架构
目录结构
/tmp/claude-senator/
├── instances/ # Each Claude writes {pid}.json with status/info
├── messages/ # Individual message files in JSONL format
└── commands/ # Command injection files for input manipulation智能指针系统
现有参考文献 ~/.claude/projects/ 数据而不是复制:
interface ContextPointers {
projects_dir: string; // `~/.claude/projects/${encoded_path}`
conversation_history: string; // Recent conversation file path
git_context: string; // Compact git state (branch@commit+dirty)
active_files: string[]; // Recently modified files
current_task: string; // What Claude is working on
collaboration_intent: string; // Why reaching out to other Claude
}消息格式
具有上下文重建功能的超密集消息传递:
interface InterClaudeMessage {
id: string;
from: number; // Sender Claude PID
to: number | 'all'; // Target Claude PID or broadcast
type: 'ultra_dense_message';
content: string; // Human-readable request
timestamp: number;
options: {
claudeContext: {
h: string; // Human message
pid: number; // Claude PID
ts: number; // Timestamp
cwd: string; // Working directory
ctx_pointers: ContextPointers; // Smart pointers to data
};
};
}实现细节
当前消息系统
会话管理器核心方法
createMessage(humanMessage: string)
使用智能指针创建超密集上下文消息:
- 目的:轻量级上下文共享
- 输入:人工消息字符串
- 输出:具有协作智能的智能指针上下文对象
- 使用:
send_context工具
private createMessage(humanMessage: string): any {
const workingDir = process.cwd();
const claudeDir = join(homedir(), '.claude');
const projectEncoded = workingDir.replace(/\//g, '-').replace(/^-/, '');
const pid = process.ppid || process.pid;
return {
h: humanMessage,
pid: pid,
ts: Date.now(),
cwd: workingDir,
ctx_pointers: {
projects_dir: `~/.claude/projects/${projectEncoded}`,
conversation_history: this.getConversationPointer(),
git_context: this.getGitContextString(),
active_files: this.getActiveFilesArray(),
current_task: this.getCurrentTaskFromContext(),
collaboration_intent: this.determineCollaborationIntent(humanMessage)
}
};
}reconstructRichContext(message: any)
从智能指针重建完整上下文:
- 目的:接收端的上下文重建
- 输入:带有智能指针的消息
- 输出:具有对话历史记录的完整上下文对象
- 使用:
receive_context工具
private reconstructRichContext(message: any): any {
const ctx = message.options?.claudeContext;
if (!ctx?.ctx_pointers) return null;
const pointers = ctx.ctx_pointers;
const reconstructed = {
sender_info: {
human_message: ctx.h,
pid: ctx.pid,
working_directory: ctx.cwd,
timestamp: ctx.ts
},
collaboration_context: {
current_task: pointers.current_task,
intent: pointers.collaboration_intent,
git_state: pointers.git_context,
active_files: pointers.active_files
},
shared_data_access: {
projects_dir: pointers.projects_dir,
conversation_history: pointers.conversation_history
}
};
// Load conversation history if pointer exists
if (pointers.conversation_history) {
reconstructed.conversation_snippet = this.loadConversationSnippet(pointers.conversation_history);
}
return reconstructed;
}generateRichContextDisplay(instance: any, activity: any)
通过协作评分创建实时状态:
- 目的:实时上下文显示,无需传输
- 输入:Claude实例数据和活动
- 输出:丰富的上下文和协作准备度得分
- 使用:
status工具
private generateRichContextDisplay(instance: any, activity: any): any {
const workingDir = instance.cwd || instance.projectPath || '/unknown';
const encodedPath = String(workingDir).replace(/\//g, '-').replace(/^-/, '');
const contextPointers = {
projectsDir: `~/.claude/projects/${encodedPath}`,
conversationHistory: this.getConversationPointer(workingDir),
gitContext: this.getGitContextString(workingDir),
activeFiles: this.getActiveFilesArray(workingDir),
currentTask: activity.task || 'Active',
collaborationIntent: this.determineCollaborationReadiness(activity, instance)
};
const collaborationMetrics = {
hasRecentActivity: activity.lastActivity > Date.now() - 300000,
hasActiveFiles: contextPointers.activeFiles.length > 0,
hasCleanGitState: !contextPointers.gitContext.includes('dirty'),
isWorkingOnKnownTask: activity.task && activity.task !== 'Active',
projectType: this.detectProjectType(workingDir)
};
return {
...contextPointers,
collaborationMetrics,
collaborationReason: this.getCollaborationReason(collaborationMetrics),
readinessScore: this.calculateReadinessScore(collaborationMetrics)
};
}协作评分算法
private calculateCollaborationScore(contextData: any): number {
const metrics = contextData.collaborationMetrics;
if (!metrics) return 0;
let score = 0;
if (metrics.hasRecentActivity) score += 0.3;
if (metrics.hasActiveFiles) score += 0.2;
if (metrics.hasCleanGitState) score += 0.2;
if (metrics.isWorkingOnKnownTask) score += 0.2;
if (metrics.projectType !== 'unknown') score += 0.1;
return Math.min(score, 1.0);
}上下文指针辅助工具
private getConversationPointer(): string | null {
const claudeDir = join(homedir(), '.claude');
const projectEncoded = process.cwd().replace(/\//g, '-').replace(/^-/, '');
const projectDir = join(claudeDir, 'projects', projectEncoded);
if (existsSync(projectDir)) {
const files = readdirSync(projectDir).filter(f => f.includes('conversation'));
if (files.length > 0) {
return `~/.claude/projects/${projectEncoded}/${files[files.length - 1]}`;
}
}
return null;
}
private getGitContextString(): string {
try {
const branch = execSync('git branch --show-current 2>/dev/null', { encoding: 'utf8' }).trim();
const commit = execSync('git rev-parse --short HEAD 2>/dev/null', { encoding: 'utf8' }).trim();
const status = execSync('git status --porcelain 2>/dev/null', { encoding: 'utf8' }).trim();
const dirty = status ? '+dirty' : '';
return `${branch}@${commit}${dirty}`;
} catch (error) {
return 'no-git';
}
}
private getActiveFilesArray(): string[] {
try {
const recentFiles = execSync('git diff --name-only HEAD~1 2>/dev/null', {
encoding: 'utf8'
}).trim().split('\n').filter(f => f);
return recentFiles.slice(0, 5);
} catch (error) {
return [];
}
}新的上下文分叉系统
核心实施
// New MCP tool
{
name: 'fork_claude',
description: 'Create new Claude session with full context from target Claude',
inputSchema: {
source_pid: { type: 'number', description: 'Claude to copy from' },
query: { type: 'string', description: 'Your question for the new Claude' }
}
}
// Implementation
case 'fork_claude': {
const sourcePid = args?.source_pid as number;
const query = args?.query as string;
// Find source Claude's conversation
const sourceActivity = this.sessionManager.parseLiveActivity(sourcePid);
const conversationPath = this.findConversationPath(sourcePid);
// Copy conversation to new session
const newSessionId = this.createForkedSession(conversationPath, query);
return {
content: [{
type: 'text',
text: `╔═ 🔄 Context Forked ═══════════════════════════════════════════════════
║ 📸 Copied: ${sourceActivity.task} • Full conversation history
║ 🆕 New session: ${newSessionId}
║ 🎯 Ready for: "${query}"
╚═ ✨ Run: claude --session ${newSessionId} to start new Claude with context`
}]
};
}会话创建
private createForkedSession(sourcePath: string, newQuery: string): string {
const timestamp = new Date().toISOString().replace(/[:.]/g, '');
const newSessionId = `fork_${timestamp}`;
const newSessionPath = join(homedir(), '.claude', 'sessions', newSessionId);
// Create new session directory
mkdirSync(newSessionPath, { recursive: true });
// Copy conversation history
if (existsSync(sourcePath)) {
const conversationContent = readFileSync(sourcePath, 'utf8');
const newConversationPath = join(newSessionPath, 'conversation.jsonl');
writeFileSync(newConversationPath, conversationContent);
// Add new query as next message
const queryMessage = {
type: 'user',
message: { content: newQuery },
timestamp: Date.now()
};
appendFileSync(newConversationPath, '\n' + JSON.stringify(queryMessage));
}
return newSessionId;
}使用示例
基本消息传递工作流
# 1. Check who's available for collaboration
claude-senator status
# Output:
╔═ 🏛️ ═══════════════════════════════════════════════════════════════════
║ 3 Claudes active • rich context network
║ 🟢 Claude 98471 • rust-project • debugging memory leak • main@a1b2c3
╚═ 🔄 Live status • Smart pointer network active
# 2. Send context to specific Claude
claude-senator send_context --target_pid 98471 --context_request "Need help with async Rust debugging"
# Output:
╔═ 🏛️ ═══════════════════════════════════════════════════════════════════
║ → Claude 98471 • "Need help with async Rust debugging" • ~/.claude pointers sent
║ 🔄 Context shared • Ready for collaboration
╚═ 🚀 Context transmitted • Collaboration network active
# 3. Receive context from other Claudes
claude-senator receive_context
# Output:
╔═ 🏛️ ═══════════════════════════════════════════════════════════════════
║ "Debug memory leak in tokio runtime" • debugging_assistance • rust-project
║ 📊 Rich context: git state, active files, current task
╚═ 📨 1 context processed • Ready for collaboration上下文分叉工作流
# Scenario: Claude deep in documentation work, want to ask questions
claude-senator status
# Output shows Claude 98471 working on documentation (318s, 9.3k tokens)
╔═ 🏛️ ═══════════════════════════════════════════════════════════════════
║ 1 Claude active • rich context network
║ 🟡 Claude 98471 • docs-project • Writing API documentation • main@x1y2z3
╚═ 🔄 Live status • Smart pointer network active
# Fork context without interrupting
claude-senator fork_claude --source_pid 98471 --query "What's the current API documentation structure?"
# Output:
╔═ 🔄 Context Forked ═══════════════════════════════════════════════════════
║ 📸 Copied: Writing API documentation • 9.3k tokens • Full conversation
║ 🆕 New session: fork_20250716_141509
║ 🎯 Ready for: "What's the current API documentation structure?"
╚═ ✨ Run: claude --session fork_20250716_141509 to start new Claude
# Start new Claude with inherited context
claude --session fork_20250716_141509
# New Claude starts with full context + your question already asked架构优势
零依赖
- 除了@modelcontextprotocol/sdk之外没有npm包
- 无外部服务(Redis、数据库等)
- 无系统依赖关系
- 没有提升权限
代币效率
- 智能指针可防止数据重复
- 按需重建上下文
- 最小内存占用
- 高效的git状态跟踪
可扩展性
- 2-20条款:性能优异(\<10ms操作)
- 20-100个条款:性能良好,文件系统开销最小
- 100+条:可能受益于SQLite升级(请参阅未来部分)
可靠性
- 每个Claude都拥有自己的文件(没有共享写入)
- 自动清理死实例
- 优雅的错误处理
- 自愈目录结构
UI设计理念
3行ASCII格式
╔═ 🏛️ ═══════════════════════════════════════════════════════════════════
║ [CONTENT LINE - exactly fits terminal width]
║ [STATUS LINE - shows current state and metrics]
╚═ [FOOTER LINE - shows next action or network status]截断规则
- 内容被截断以适应终端宽度
- 重要信息优先
- 用于快速扫描的表情符号指示器
- 一致的间距和对齐
特定于工具的表情符号
- 🏛️ 始终处于领先地位(克劳德参议员身份)
- 🔄 上下文共享操作
- 📨 消息接收
- 🔄 上下文分叉
- 🚀 网络活动
文件结构
核心文件
src/
├── index.ts # MCP server and tool handlers
├── session.ts # SessionManager - core messaging logic
├── memory.ts # MemoryManager - conversation search
├── injection.ts # CommandInjector - input manipulation
└── types.ts # TypeScript interfaces关键类
会话管理器 (src/session.ts)
- 目的:核心信息传递和上下文管理
- 关键方法:
createMessage,reconstructRichContext,generateRichContextDisplay - 手柄:智能指针、上下文重建、协作评分
内存管理器 (src/memory.ts)
- 目的:对话历史搜索和分析
- 关键方法:待定(未来实施)
- 手柄:历史上下文检索、记忆模式
CommandInjector (src/injection.ts)
- 目的:输入操作和命令路由
- 关键方法:待定(未来实施)
- 手柄:Inter-Claude命令注入,工作流自动化
未来的增强功能
消息系统扩展
// Planned tools
{
name: 'broadcast_context',
description: 'Send context to all active Claude instances'
}
{
name: 'handoff_context',
description: 'Transfer work to another Claude with full context'
}
{
name: 'sync_context',
description: 'Synchronize context across multiple Claude instances'
}上下文分叉改进
// Selective inheritance
{
name: 'fork_claude_selective',
inputSchema: {
source_pid: number,
query: string,
include_conversation: boolean,
include_files: boolean,
include_git_state: boolean
}
}
// Context merging
{
name: 'merge_context',
description: 'Merge insights from forked Claude back to parent'
}性能优化
- 上下文缓存:用于频繁访问上下文的LRU缓存
- 压缩:Gzip压缩用于大型对话历史记录
- 流媒体:随着工作的进展实时更新上下文
- SQLite升级:用于100多个并发的Claude实例
集成可能性
- IDE插件:VS代码、游标、Windsurf集成
- CI/CD:构建管道中的自动上下文共享
- 监控:实时协作网络可视化
- 分析:上下文共享模式和优化
项目拆分指南
如果拆分为单独的项目:
核心信息 (克劳德参议员消息)
- 文件:
src/session.ts(第1-883行、第1075-1451行),src/types.ts - 依赖项:
src/memory.ts用于对话搜索 - 特性:
send_context,receive_context,status - 尺寸:约1400条线路,全消息系统
上下文分叉 (克劳德参议员分叉)
- 文件:新的实施
src/forking.ts - 依赖项:
src/session.ts(会话查找方法) - 特性:
fork_claude工具 - 尺寸:约50行,最少执行
共享基础设施 (克劳德参议员核心)
- 文件:
src/types.ts,目录管理实用程序 - 目的:通用接口和实用程序
- 尺寸:约200行,基本类型和助手
迁移策略
- 提取核心类型:将接口移动到共享包
- 拆分会话管理器:独立的消息传递和分叉逻辑
- 保持兼容性:确保两个系统可以共存
- 文档接口:清晰的API用于集成
发展
git clone https://github.com/yourusername/claude-senator
cd claude-senator
npm install
npm run build
npm test贡献
- 分叉存储库并创建功能分支
- 在提交PR之前,使用多个Claude实例进行测试
- 遵循TypeScript严格模式和MCP协议标准
- 记录任何新的智能指针模式
测试
- 测试2-5个Claude实例之间的消息传递
- 验证上下文重建的准确性
- 使用大量对话历史记录进行测试分叉
- 跨终端验证ASCII UI格式
许可证
______________________________________________________________________
_Claude Senator通过智能上下文共享和无中断分叉实现了Claude实例之间前所未有的协作。专为需要AI助手像他们一样无缝协作的开发人员而设计。_
