5. 上下文管理
5.1 环境信息收集
typescript
class EnvironmentContext {
async collect(): Promise<string> {
const info = {
// 基本信息
os: process.platform,
cwd: process.cwd(),
shell: process.env.SHELL,
// 项目信息
packageJson: await this.readPackageJson(),
gitStatus: await this.getGitStatus(),
// 文件结构
projectStructure: await this.getProjectStructure()
};
return this.format(info);
}
async getGitStatus(): Promise<string> {
try {
const branch = await exec('git branch --show-current');
const status = await exec('git status --short');
const recentCommits = await exec('git log --oneline -5');
return `Branch: ${branch}
Status:
${status}
Recent commits:
${recentCommits}`;
} catch {
return 'Not a git repository';
}
}
async getProjectStructure(): Promise<string> {
// 生成项目文件树(排除 node_modules 等)
const tree = await generateTree(process.cwd(), {
ignore: ['node_modules', '.git', 'dist', 'build']
});
return tree;
}
}5.2 终端状态追踪
typescript
class TerminalTracker {
private terminals: Map<string, TerminalState> = new Map();
track(id: string, state: TerminalState) {
this.terminals.set(id, {
...state,
lastUpdated: Date.now()
});
}
getContext(): string {
const active = [...this.terminals.values()]
.filter(t => this.isActive(t));
if (active.length === 0) {
return 'No active terminals';
}
return active.map(t => `
Terminal ${t.id}:
CWD: ${t.cwd}
Last command: ${t.lastCommand}
${t.isRunning ? `Running: ${t.currentCommand}` : `Exit code: ${t.lastExitCode}`}
`).join('\n');
}
}