7. 通信与状态管理
7.1 通信工具
typescript
const communicationTools = [
{
name: "message_user",
description: `Send a message to the user.
Use cases:
- Progress updates for long tasks
- Ask clarifying questions
- Report completion or errors
- Share intermediate results
Format:
- Be clear and concise
- Use markdown for formatting
- Include relevant details`,
parameters: {
type: "object",
properties: {
content: { type: "string" },
attachments: {
type: "array",
items: { type: "string" },
description: "File paths to attach"
},
type: {
type: "string",
enum: ["info", "question", "progress", "success", "error"]
}
},
required: ["content"]
}
},
{
name: "request_confirmation",
description: "Ask user to confirm before proceeding with sensitive action",
parameters: {
type: "object",
properties: {
action: { type: "string", description: "What action needs confirmation" },
reason: { type: "string", description: "Why confirmation is needed" }
},
required: ["action"]
}
}
];7.2 EventStream 实现
typescript
class EventStreamManager {
private events: Event[] = [];
private subscribers: Set<(event: Event) => void> = new Set();
emit(event: Event): void {
this.events.push({
...event,
timestamp: Date.now()
});
// 通知订阅者
this.subscribers.forEach(callback => callback(event));
}
// 任务开始
taskStarted(taskId: string, description: string): void {
this.emit({
type: 'task_started',
taskId,
data: { description }
});
}
// 步骤进度
stepProgress(taskId: string, step: number, total: number, message: string): void {
this.emit({
type: 'step_progress',
taskId,
data: { step, total, message }
});
}
// 工具调用
toolInvoked(taskId: string, tool: string, params: any): void {
this.emit({
type: 'tool_invoked',
taskId,
data: { tool, params }
});
}
// 工具结果
toolResult(taskId: string, tool: string, result: any): void {
this.emit({
type: 'tool_result',
taskId,
data: { tool, result }
});
}
// 任务完成
taskCompleted(taskId: string, deliverables: string[]): void {
this.emit({
type: 'task_completed',
taskId,
data: { deliverables }
});
}
// 获取任务历史
getTaskHistory(taskId: string): Event[] {
return this.events.filter(e => e.taskId === taskId);
}
}7.3 状态管理
typescript
interface AgentState {
// 任务信息
task: {
id: string;
description: string;
plan: TaskPlan;
currentStep: number;
};
// 执行环境
sandbox: {
id: string;
status: 'running' | 'paused' | 'stopped';
cwd: string;
};
// 浏览器状态
browser: {
url: string;
title: string;
lastScreenshot: string;
};
// 执行历史
history: {
actions: Action[];
errors: Error[];
};
// 产出物
artifacts: {
files: string[];
data: any;
};
}
class StateManager {
private state: AgentState;
private checkpoints: AgentState[] = [];
// 保存检查点(用于回滚)
checkpoint(): string {
const id = `checkpoint-${Date.now()}`;
this.checkpoints.push({
...JSON.parse(JSON.stringify(this.state)),
checkpointId: id
});
return id;
}
// 回滚到检查点
rollback(checkpointId: string): boolean {
const checkpoint = this.checkpoints.find(c => c.checkpointId === checkpointId);
if (checkpoint) {
this.state = JSON.parse(JSON.stringify(checkpoint));
return true;
}
return false;
}
// 获取上下文摘要(用于 LLM)
getContextSummary(): string {
return `
## Current State
**Task**: ${this.state.task.description}
**Progress**: Step ${this.state.task.currentStep} of ${this.state.task.plan.steps.length}
**Browser**:
- URL: ${this.state.browser.url}
- Title: ${this.state.browser.title}
**Recent Actions**:
${this.state.history.actions.slice(-5).map(a => `- ${a.tool}: ${a.summary}`).join('\n')}
**Files Created**:
${this.state.artifacts.files.join('\n')}
`;
}
}