chore: baseline Agent Workbench 1.0.0
This commit is contained in:
@@ -0,0 +1,193 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { lastSessionFailure } from './diagnostics.mjs';
|
||||
|
||||
export const now = () => new Date().toISOString();
|
||||
|
||||
export function atomicJson(file, value) {
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
const temporary = file + '.' + randomUUID() + '.tmp';
|
||||
const handle = fs.openSync(temporary, 'wx', 0o600);
|
||||
try {
|
||||
fs.writeFileSync(handle, JSON.stringify(value, null, 2), 'utf8');
|
||||
fs.fsyncSync(handle);
|
||||
} finally { fs.closeSync(handle); }
|
||||
try {
|
||||
if (fs.existsSync(file)) fs.copyFileSync(file, file + '.bak');
|
||||
fs.renameSync(temporary, file);
|
||||
} finally { if (fs.existsSync(temporary)) fs.unlinkSync(temporary); }
|
||||
}
|
||||
|
||||
export function readJson(file, fallback) {
|
||||
for (const candidate of [file, file + '.bak']) {
|
||||
if (!fs.existsSync(candidate)) continue;
|
||||
try { return JSON.parse(fs.readFileSync(candidate, 'utf8')); }
|
||||
catch { if (candidate === file) fs.copyFileSync(candidate, candidate + '.corrupt-' + Date.now()); }
|
||||
}
|
||||
return structuredClone(fallback);
|
||||
}
|
||||
|
||||
export function repairToolPairs(messages) {
|
||||
const result = [];
|
||||
let interrupted = 0, dropped = 0;
|
||||
for (let index = 0; index < messages.length; index++) {
|
||||
const message = messages[index];
|
||||
if (message.role === 'tool') { dropped++; continue; }
|
||||
result.push(message);
|
||||
if (message.role !== 'assistant' || !message.tool_calls?.length) continue;
|
||||
const received = new Map();
|
||||
while (messages[index + 1]?.role === 'tool') {
|
||||
const tool = messages[++index];
|
||||
if (!received.has(tool.tool_call_id)) received.set(tool.tool_call_id, tool);
|
||||
else dropped++;
|
||||
}
|
||||
for (const call of message.tool_calls) {
|
||||
if (received.has(call.id)) result.push(received.get(call.id));
|
||||
else {
|
||||
interrupted++;
|
||||
result.push({ role: 'tool', tool_call_id: call.id, content: JSON.stringify({
|
||||
status: 'interrupted', requires_verification: true,
|
||||
message: '服务重启时没有收到这次工具调用的完成结果。请核对当前项目状态;终端命令重新执行需要再次确认。',
|
||||
}) });
|
||||
}
|
||||
}
|
||||
dropped += [...received.keys()].filter(id => !message.tool_calls.some(call => call.id === id)).length;
|
||||
}
|
||||
return { messages: result, interrupted, changed: interrupted > 0 || dropped > 0 };
|
||||
}
|
||||
|
||||
export class Store extends EventEmitter {
|
||||
constructor(directory) {
|
||||
super();
|
||||
this.directory = path.resolve(directory);
|
||||
this.sessions = new Map();
|
||||
fs.mkdirSync(path.join(this.directory, 'sessions'), { recursive: true });
|
||||
this.config = readJson(path.join(this.directory, 'config.json'), {
|
||||
mode: 'demo', baseUrl: 'http://127.0.0.1:11434/v1', model: '',
|
||||
contextLimit: 16000, maxSteps: 12, maxOutputTokens: 2048,
|
||||
});
|
||||
delete this.config.apiKey;
|
||||
this.projects = readJson(path.join(this.directory, 'projects.json'), []);
|
||||
for (const file of fs.readdirSync(path.join(this.directory, 'sessions'))) {
|
||||
if (!/^[a-f0-9-]+\.json$/.test(file)) continue;
|
||||
const session = readJson(path.join(this.directory, 'sessions', file), null);
|
||||
if (!session?.id || !session.projectId) continue;
|
||||
let changed = false;
|
||||
if (['running', 'awaiting_approval', 'stopping'].includes(session.status)) {
|
||||
session.status = 'paused';
|
||||
session.recoveryNotice = '上次任务被中断。继续前请核对执行记录与文件状态。';
|
||||
changed = true;
|
||||
}
|
||||
for (const event of session.events ?? []) {
|
||||
if (['running', 'waiting', 'retrying'].includes(event.phase)) {
|
||||
event.phase = 'interrupted';
|
||||
event.finishedAt = now();
|
||||
event.output = event.kind === 'model' ? '上次模型请求已中断,可以从已保存记录继续。' : event.executedAt
|
||||
? '调用已进入执行阶段,服务中断后未记录完成结果。实际结果需要核对。'
|
||||
: '这次调用没有完成;不会自动重放。';
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
for (const approval of session.approvals ?? []) {
|
||||
if (approval.status === 'pending') {
|
||||
approval.status = 'interrupted';
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
const repaired = repairToolPairs(session.providerMessages ?? []);
|
||||
if (repaired.changed) {
|
||||
session.providerMessages = repaired.messages;
|
||||
session.recoveryNotice = repaired.interrupted
|
||||
? '已为 ' + repaired.interrupted + ' 个未完成工具调用记录中断结果。不会自动重放命令。'
|
||||
: '已整理会话中的工具结果配对。请核对执行记录后继续。';
|
||||
changed = true;
|
||||
}
|
||||
this.sessions.set(session.id, session);
|
||||
if (changed) this.save(session);
|
||||
}
|
||||
}
|
||||
|
||||
save(session) {
|
||||
session.revision = (session.revision ?? 0) + 1;
|
||||
session.updatedAt = now();
|
||||
atomicJson(path.join(this.directory, 'sessions', session.id + '.json'), session);
|
||||
this.emit('update', this.publicSession(session));
|
||||
return session;
|
||||
}
|
||||
|
||||
saveConfig(config) {
|
||||
this.config = { ...this.config, ...config };
|
||||
delete this.config.apiKey;
|
||||
atomicJson(path.join(this.directory, 'config.json'), this.config);
|
||||
return this.config;
|
||||
}
|
||||
|
||||
addProject(root) {
|
||||
const resolved = fs.realpathSync.native(path.resolve(root));
|
||||
if (!fs.statSync(resolved).isDirectory()) throw new Error('请选择项目文件夹。');
|
||||
const key = process.platform === 'win32' ? resolved.toLowerCase() : resolved;
|
||||
const existing = this.projects.find(project => (process.platform === 'win32' ? project.root.toLowerCase() : project.root) === key);
|
||||
if (existing) return existing;
|
||||
const project = { id: randomUUID(), root: resolved, name: path.basename(resolved), addedAt: now() };
|
||||
this.projects.unshift(project);
|
||||
atomicJson(path.join(this.directory, 'projects.json'), this.projects);
|
||||
return project;
|
||||
}
|
||||
|
||||
project(id) {
|
||||
const project = this.projects.find(item => item.id === id);
|
||||
if (!project) throw Object.assign(new Error('项目不存在。'), { status: 404 });
|
||||
return project;
|
||||
}
|
||||
|
||||
createSession(projectId, title = '新任务') {
|
||||
this.project(projectId);
|
||||
const session = {
|
||||
id: randomUUID(), projectId, title, status: 'idle', createdAt: now(), updatedAt: now(),
|
||||
messages: [], providerMessages: [], events: [], changes: [], approvals: [],
|
||||
failure: null, lastFailure: null,
|
||||
compactions: 0, estimatedTokens: 0, usage: null, archived: false,
|
||||
};
|
||||
this.sessions.set(session.id, session);
|
||||
this.save(session);
|
||||
return session;
|
||||
}
|
||||
|
||||
session(id) {
|
||||
const session = this.sessions.get(id);
|
||||
if (!session) throw Object.assign(new Error('会话不存在。'), { status: 404 });
|
||||
return session;
|
||||
}
|
||||
|
||||
publicSession(session) {
|
||||
const { providerMessages, ...visible } = session;
|
||||
visible.lastFailure = lastSessionFailure(session);
|
||||
if (session.status === 'failed' && !visible.failure && visible.lastFailure) {
|
||||
visible.failure = { ...visible.lastFailure, messageId: session.messages.findLast(message => message.role === 'system')?.id };
|
||||
}
|
||||
return structuredClone(visible);
|
||||
}
|
||||
|
||||
listSessions() {
|
||||
return [...this.sessions.values()].filter(session => !session.archived)
|
||||
.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))
|
||||
.map(session => ({ id: session.id, projectId: session.projectId, title: session.title,
|
||||
status: session.status, revision: session.revision ?? 0, updatedAt: session.updatedAt, changeCount: session.changes.filter(change => ['pending', 'conflict'].includes(change.status)).length }));
|
||||
}
|
||||
|
||||
event(session, event) {
|
||||
const entry = { id: randomUUID(), createdAt: now(), ...event };
|
||||
session.events.push(entry);
|
||||
this.save(session);
|
||||
return entry;
|
||||
}
|
||||
|
||||
message(session, role, content) {
|
||||
const message = { id: randomUUID(), role, content, createdAt: now() };
|
||||
session.messages.push(message);
|
||||
this.save(session);
|
||||
return message;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user