feat: add durable isolated Git workspaces and source-bound delivery
This commit is contained in:
+33
-1
@@ -4,6 +4,8 @@ import { listFiles, readText, proposeFile, proposePatch, applyChange } from './f
|
||||
import { APP_VERSION, executionEnvironment, sessionSnapshot } from './diagnostics.mjs';
|
||||
import { inspectProject } from '../core/project-inspector.mjs';
|
||||
import { assertProposalUnsealed } from '../shared/contracts/change-sets.mjs';
|
||||
import { assertWorkspacesResolved } from '../shared/contracts/workspaces.mjs';
|
||||
import { verifyWorkspaceProject } from '../core/workspaces/git-workspaces.mjs';
|
||||
|
||||
export function createSessionPublisher(clients) {
|
||||
return session => {
|
||||
@@ -121,6 +123,7 @@ return async (request, response) => {
|
||||
const projectMatch = route.match(/^\/api\/projects\/([a-f0-9-]+)\/(files|file|inspection|code-index|code-query)$/);
|
||||
if (method === 'GET' && projectMatch) {
|
||||
const project = store.project(projectMatch[1]);
|
||||
await verifyWorkspaceProject(store, project);
|
||||
if (projectMatch[2] === 'inspection') return json(response, await inspectProject(project));
|
||||
if (['code-index', 'code-query'].includes(projectMatch[2])) {
|
||||
const indexer = runtime.projectIndexer(), index = await indexer.refresh(project);
|
||||
@@ -134,6 +137,7 @@ return async (request, response) => {
|
||||
if (method === 'GET' && route === '/api/sessions') return json(response, store.listSessions());
|
||||
if (method === 'POST' && route === '/api/sessions') {
|
||||
const input = await body(request);
|
||||
await verifyWorkspaceProject(store, store.project(input.projectId));
|
||||
return json(response, store.publicSession(store.createSession(input.projectId)), 201);
|
||||
}
|
||||
const sessionMatch = route.match(/^\/api\/sessions\/([a-f0-9-]+)(?:\/(.*))?$/);
|
||||
@@ -142,6 +146,30 @@ return async (request, response) => {
|
||||
const session = store.session(id);
|
||||
if (method === 'GET' && !action) return json(response, store.publicSession(session));
|
||||
if (method === 'GET' && action === 'execution') return json(response, store.executionSnapshot(session));
|
||||
if (method === 'GET' && action === 'workspaces') return json(response, store.executionSnapshot(session).workspaces);
|
||||
if (method === 'POST' && action === 'workspaces') {
|
||||
const input = await body(request);
|
||||
return json(response, await runtime.workspaceManager().prepare(session, input.label), 201);
|
||||
}
|
||||
const workspace = action.match(/^workspaces\/([a-f0-9-]+)(?:\/(create|reconcile|acknowledge|discard|open|stop))?$/);
|
||||
if (workspace && method === 'GET' && !workspace[2]) return json(response, store.owned('workspace', workspace[1], id));
|
||||
if (workspace && method === 'POST' && workspace[2]) {
|
||||
const input = await body(request), record = store.owned('workspace', workspace[1], id);
|
||||
if (workspace[2] === 'open') {
|
||||
if (record.status !== 'ready') throw Object.assign(new Error('工作区尚未完整确认,请先核对创建结果。'), { status: 409 });
|
||||
const project = store.project(record.childProjectId), child = store.session(record.childSessionId);
|
||||
await verifyWorkspaceProject(store, project);
|
||||
if (child.projectId !== project.id || child.archived) throw Object.assign(new Error('原工作区会话已归档或归属变化,请从项目栏打开该项目的当前会话。'), { status: 409 });
|
||||
return json(response, { workspace: record, project, session: store.publicSession(child) });
|
||||
}
|
||||
const manager = runtime.workspaceManager();
|
||||
if (workspace[2] === 'create') await manager.start(session, record.id, input.fingerprint);
|
||||
else if (workspace[2] === 'reconcile') await manager.reconcile(session, record.id, input.fingerprint);
|
||||
else if (workspace[2] === 'acknowledge') await manager.acknowledge(session, record.id, input.fingerprint, input.observationFingerprint);
|
||||
else if (workspace[2] === 'discard') manager.discard(session, record.id, input.fingerprint);
|
||||
else await manager.stop(id);
|
||||
return json(response, record, workspace[2] === 'create' ? 202 : 200);
|
||||
}
|
||||
if (method === 'GET' && action === 'context-plans') {
|
||||
const runId = url.searchParams.get('run'); if (runId) store.owned('run', runId, id);
|
||||
return json(response, [...store.core.context_plan.values()].filter(plan => plan.sessionId === id && (!runId || plan.runId === runId)).slice(-100));
|
||||
@@ -261,6 +289,8 @@ return async (request, response) => {
|
||||
if (method === 'POST' && change) {
|
||||
await body(request);
|
||||
if (runtime.projectHasActivity(session.projectId)) throw Object.assign(new Error('项目正在执行任务或检查,请等待结束或停止后再审查文件改动。'), { status: 409 });
|
||||
assertWorkspacesResolved(store, session.projectId, { includePrepared: true });
|
||||
await verifyWorkspaceProject(store, store.project(session.projectId));
|
||||
if (change[2] === 'apply') applyChange(store, session, change[1]);
|
||||
else {
|
||||
const item = session.changes.find(candidate => candidate.id === change[1]);
|
||||
@@ -274,7 +304,9 @@ return async (request, response) => {
|
||||
}
|
||||
if (method === 'POST' && ['proposals', 'patch-proposals'].includes(action)) {
|
||||
const input = await body(request);
|
||||
if (runtime.checks?.projectActive(session.projectId) || runtime.deliveries?.projectActive(session.projectId) || runtime.changeSets?.projectActive(session.projectId)) throw Object.assign(new Error('工程检查、Git交付或文件批次正在执行,请等待结束后再编辑文件。'), { status: 409 });
|
||||
if (runtime.checks?.projectActive(session.projectId) || runtime.deliveries?.projectActive(session.projectId) || runtime.changeSets?.projectActive(session.projectId) || runtime.workspaces?.projectActive(session.projectId)) throw Object.assign(new Error('工程检查、Git交付、文件批次或工作区正在执行,请等待结束后再编辑文件。'), { status: 409 });
|
||||
assertWorkspacesResolved(store, session.projectId, { includePrepared: true });
|
||||
await verifyWorkspaceProject(store, store.project(session.projectId));
|
||||
if (action === 'patch-proposals') proposePatch(store, session, input);
|
||||
else proposeFile(store, session, input);
|
||||
return json(response, store.publicSession(session), 201);
|
||||
|
||||
@@ -4,6 +4,7 @@ import { createHash, randomUUID } from 'node:crypto';
|
||||
import { diffLines } from 'diff';
|
||||
import { now } from './store.mjs';
|
||||
import { assertChangeSetsResolved, assertProposalUnsealed } from '../shared/contracts/change-sets.mjs';
|
||||
import { assertWorkspacePath, assertWorkspacesResolved } from '../shared/contracts/workspaces.mjs';
|
||||
|
||||
export const hash = bytes => createHash('sha256').update(bytes).digest('hex');
|
||||
const ignored = new Set(['node_modules', '.git', '.next', '.data', 'bin', 'obj', 'dist', 'dist-client', 'dist-server', '__pycache__']);
|
||||
@@ -17,6 +18,7 @@ export function excludedFromInventory(relative) {
|
||||
}
|
||||
|
||||
export function safePath(project, relative = '', allowMissing = false) {
|
||||
assertWorkspacePath(project);
|
||||
if (typeof relative !== 'string' || relative.includes('\0') || relative.includes(':') || path.isAbsolute(relative) || path.win32.isAbsolute(relative)) throw new Error('路径必须相对于项目文件夹。');
|
||||
const portable = relative.replaceAll('\\', '/');
|
||||
if (portable.split('/').includes('..') || secretName.test(portable) || portable.split('/').some(part => part.toLowerCase() === '.git')) throw new Error('该路径不在可读取的项目范围内。');
|
||||
@@ -111,6 +113,7 @@ export function searchFiles(project, args) {
|
||||
|
||||
export function proposeFile(store, session, args, { patch = null } = {}) {
|
||||
assertChangeSetsResolved(store, session.projectId);
|
||||
assertWorkspacesResolved(store, session.projectId, { includePrepared: true });
|
||||
if (typeof args.path !== 'string' || typeof args.content !== 'string') throw new Error('文件提案需要文本路径和完整文本内容。');
|
||||
const project = store.project(session.projectId);
|
||||
const target = safePath(project, args.path, true);
|
||||
@@ -173,6 +176,7 @@ export function proposePatch(store, session, args) {
|
||||
|
||||
export function applyChange(store, session, id) {
|
||||
assertChangeSetsResolved(store, session.projectId);
|
||||
assertWorkspacesResolved(store, session.projectId, { includePrepared: true });
|
||||
const change = session.changes.find(item => item.id === id);
|
||||
if (!change || change.status !== 'pending') throw new Error('这项改动不处于待审查状态。');
|
||||
assertProposalUnsealed(store, change);
|
||||
|
||||
@@ -11,13 +11,13 @@ import { APP_VERSION } from './diagnostics.mjs';
|
||||
export function installUpgrade(context, { appDirectory, updateServiceInfo = true }) {
|
||||
const { server, store, provider, runtime, token, clients, started, exampleProject, shutdown } = context;
|
||||
if (!server?.listening || !store || !provider || !runtime || !clients || !token) throw new Error('The existing Workbench context is incomplete.');
|
||||
if (runtime.active.size || runtime.waiters.size || runtime.checks?.active.size || runtime.deliveries?.active.size || runtime.changeSets?.projects.size) throw new Error('Wait for active tasks, checks, Git deliveries, file batches and approvals to finish before upgrading.');
|
||||
if (runtime.active.size || runtime.waiters.size || runtime.checks?.active.size || runtime.deliveries?.active.size || runtime.changeSets?.projects.size || runtime.workspaces?.projects.size || runtime.workspaces?.pending.size) throw new Error('Wait for active tasks, checks, Git deliveries, file batches, workspaces and approvals to finish before upgrading.');
|
||||
const root = fs.realpathSync.native(path.resolve(appDirectory));
|
||||
if (!fs.existsSync(path.join(root, 'dist-client', 'index.html'))) throw new Error('The new client bundle is missing.');
|
||||
const oldHandlers = server.listeners('request');
|
||||
const oldPrototypes = [Object.getPrototypeOf(store), Object.getPrototypeOf(provider), Object.getPrototypeOf(runtime)];
|
||||
const oldStoreProperties = { ...store };
|
||||
const oldRuntimeProperties = { appDirectory: runtime.appDirectory, checks: runtime.checks, deliveries: runtime.deliveries, codeIndex: runtime.codeIndex, changeSets: runtime.changeSets, contextPlans: runtime.contextPlans };
|
||||
const oldRuntimeProperties = { appDirectory: runtime.appDirectory, checks: runtime.checks, deliveries: runtime.deliveries, codeIndex: runtime.codeIndex, changeSets: runtime.changeSets, contextPlans: runtime.contextPlans, workspaces: runtime.workspaces };
|
||||
const oldUpdates = store.listeners('update');
|
||||
const closeStorage = () => store.close();
|
||||
if (oldUpdates.length > 1) throw new Error('Unexpected Store observers; preserve their ownership before upgrading.');
|
||||
@@ -27,7 +27,7 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
|
||||
Object.setPrototypeOf(store, Store.prototype);
|
||||
Object.setPrototypeOf(provider, Provider.prototype);
|
||||
Object.setPrototypeOf(runtime, Runtime.prototype);
|
||||
runtime.appDirectory = root; runtime.checks = null; runtime.deliveries = null; runtime.codeIndex = null; runtime.changeSets = null; runtime.contextPlans = null;
|
||||
runtime.appDirectory = root; runtime.checks = null; runtime.deliveries = null; runtime.codeIndex = null; runtime.changeSets = null; runtime.contextPlans = null; runtime.workspaces = null;
|
||||
store.ensureStorage(); store.claimRuntime();
|
||||
store.removeAllListeners('update'); store.on('update', createSessionPublisher(clients));
|
||||
server.removeAllListeners('request'); server.on('request', handler);
|
||||
|
||||
+20
-9
@@ -16,6 +16,8 @@ import { artifactPage, readMessageBudget, recordArtifactRead, clearReadStreak }
|
||||
import { ChangeSetManager } from '../core/workspaces/change-sets.mjs';
|
||||
import { assertChangeSetsResolved } from '../shared/contracts/change-sets.mjs';
|
||||
import { pendingDeliveryReview } from '../shared/contracts/delivery-review.mjs';
|
||||
import { WorkspaceManager, verifyWorkspaceProject } from '../core/workspaces/git-workspaces.mjs';
|
||||
import { assertWorkspacesResolved, projectWorkspaceIdentity } from '../shared/contracts/workspaces.mjs';
|
||||
|
||||
const labels = { inspect_session: '核对工作台运行记录', inspect_project: '识别工程与Git基线', index_project: '建立工程符号索引', query_code: '定位工程符号与导入', propose_patch: '准备精确补丁', plan_checks: '准备工程检查计划', run_checks: '执行工程检查', plan_delivery: '准备Git交付预览', delivery_report: '生成工程证据报告', read_artifact: '读取执行日志工件', list_files: '查看项目文件', read_file: '读取文件', search_files: '搜索项目', propose_file: '准备文件改动', run_command: '运行终端命令' };
|
||||
|
||||
@@ -47,34 +49,42 @@ export class Runtime {
|
||||
this.appDirectory = appDirectory;
|
||||
this.active = new Map(); this.waiters = new Map();
|
||||
}
|
||||
isActive(id) { return this.active.has(id) || !!this.checks?.isActive(id) || !!this.deliveries?.isActive(id) || !!this.changeSets?.isActive(id); }
|
||||
hasActivity() { return this.active.size > 0 || (this.checks?.active.size ?? 0) > 0 || (this.deliveries?.active.size ?? 0) > 0 || (this.changeSets?.projects.size ?? 0) > 0; }
|
||||
isActive(id) { return this.active.has(id) || !!this.checks?.isActive(id) || !!this.deliveries?.isActive(id) || !!this.changeSets?.isActive(id) || !!this.workspaces?.isActive(id); }
|
||||
hasActivity() { return this.active.size > 0 || (this.checks?.active.size ?? 0) > 0 || (this.deliveries?.active.size ?? 0) > 0 || (this.changeSets?.projects.size ?? 0) > 0 || (this.workspaces?.projects.size ?? 0) > 0 || (this.workspaces?.pending.size ?? 0) > 0; }
|
||||
projectIndexer() { return this.codeIndex ??= new ProjectIndex(); }
|
||||
requestPlanner() { return this.contextPlans ??= new RequestPlanner(this.store); }
|
||||
projectHasActivity(projectId, exceptSessionId = null) {
|
||||
return [...this.active.entries()].some(([id, run]) => id !== exceptSessionId && run.project.id === projectId) || !!this.checks?.projectActive(projectId) || !!this.deliveries?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId);
|
||||
return [...this.active.entries()].some(([id, run]) => id !== exceptSessionId && run.project.id === projectId) || !!this.checks?.projectActive(projectId) || !!this.deliveries?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId) || !!this.workspaces?.projectActive(projectId);
|
||||
}
|
||||
workspaceManager() {
|
||||
return this.workspaces ??= new WorkspaceManager(this.store, { initialize: this.store.core.workspace.size === 0,
|
||||
redact: value => this.provider.redact(value), projectBusy: projectId =>
|
||||
[...this.active.values()].some(run => run.project.id === projectId) || !!this.checks?.projectActive(projectId)
|
||||
|| !!this.deliveries?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId) });
|
||||
}
|
||||
changeSetManager() {
|
||||
return this.changeSets ??= new ChangeSetManager(this.store, { projectBusy: (projectId, exceptId) =>
|
||||
[...this.active.entries()].some(([id, run]) => id !== exceptId && run.project.id === projectId)
|
||||
|| !!this.checks?.projectActive(projectId) || !!this.deliveries?.projectActive(projectId) });
|
||||
|| !!this.checks?.projectActive(projectId) || !!this.deliveries?.projectActive(projectId) || !!this.workspaces?.projectActive(projectId) });
|
||||
}
|
||||
checkRunner() {
|
||||
return this.checks ??= new CheckRunner(this.store, { redact: value => this.provider.redact(value), runtimeDirectory: this.appDirectory ? path.join(this.appDirectory, 'runtime') : null,
|
||||
projectBusy: (projectId, exceptId) => [...this.active.entries()].some(([id, run]) => id !== exceptId && run.project.id === projectId) || !!this.deliveries?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId) });
|
||||
projectBusy: (projectId, exceptId) => [...this.active.entries()].some(([id, run]) => id !== exceptId && run.project.id === projectId) || !!this.deliveries?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId) || !!this.workspaces?.projectActive(projectId) });
|
||||
}
|
||||
gitDelivery() {
|
||||
return this.deliveries ??= new GitDelivery(this.store, { redact: value => this.provider.redact(value),
|
||||
projectBusy: (projectId, exceptId) => [...this.active.entries()].some(([id, run]) => id !== exceptId && run.project.id === projectId) || !!this.checks?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId) });
|
||||
projectBusy: (projectId, exceptId) => [...this.active.entries()].some(([id, run]) => id !== exceptId && run.project.id === projectId) || !!this.checks?.projectActive(projectId) || !!this.changeSets?.projectActive(projectId) || !!this.workspaces?.projectActive(projectId) });
|
||||
}
|
||||
start(id, content, resume = false, { instructionSource = null } = {}) {
|
||||
const session = this.store.session(id);
|
||||
if (pendingDeliveryReview(this.store, session)) throw Object.assign(new Error('当前任务已有待确认的Git交付预览。请在任务记录中审查并确认提交,或撤回预览后继续。'), { status: 409 });
|
||||
assertChangeSetsResolved(this.store, session.projectId, { includePrepared: true });
|
||||
assertWorkspacesResolved(this.store, session.projectId, { includePrepared: true });
|
||||
if (this.isActive(id) || this.projectHasActivity(session.projectId)) throw Object.assign(new Error('这个项目已有任务、检查或Git交付在执行。'), { status: 409 });
|
||||
if ([...this.store.core.delivery_job.values()].some(job => job.projectId === session.projectId && job.requiresVerification)) throw Object.assign(new Error('项目有结果未知的Git交付,请先在所属任务中核对提交结果。'), { status: 409 });
|
||||
if (!resume && (typeof content !== 'string' || !content.trim() || content.length > 20000)) throw new Error('任务内容不能为空,也不能超过 20,000 字符。');
|
||||
const project = this.store.project(session.projectId);
|
||||
safePath(project);
|
||||
const controller = new AbortController();
|
||||
const config = structuredClone(this.store.config);
|
||||
if (config.mode !== 'demo') this.provider.validate(config);
|
||||
@@ -120,6 +130,7 @@ export class Runtime {
|
||||
const signal = run.controller.signal;
|
||||
let projectionLogged = false;
|
||||
try {
|
||||
await verifyWorkspaceProject(this.store, run.project);
|
||||
for (let step = 0; step < config.maxSteps; step++) {
|
||||
signal.throwIfAborted();
|
||||
checkBudget(run.record, this.store.core.task.get(run.taskId));
|
||||
@@ -130,7 +141,7 @@ export class Runtime {
|
||||
const unknown = [...this.store.core.tool.values()].filter(tool => tool.taskId === task.id && tool.requiresVerification)
|
||||
.map(tool => ({ invocation_id: tool.id, call_id: tool.callId, tool: tool.tool, status: tool.state, requires_verification: true }));
|
||||
const context = this.provider.redact(projectContext(run.project) + '\n当前项目/会话/任务身份:' + JSON.stringify({
|
||||
project_id: run.project.id, session_id: session.id, task_id: task.id }) + '\n当前Task文件提案状态:' + JSON.stringify(state)
|
||||
project_id: run.project.id, session_id: session.id, task_id: task.id, workspace: projectWorkspaceIdentity(run.project) }) + '\n当前Task文件提案状态:' + JSON.stringify(state)
|
||||
+ '\n当前任务目标与全部追加要求(用户任务数据,完整保留):\n' + JSON.stringify({
|
||||
goal: task.goal, instructions: task.instructions, constraints: task.constraints ?? [], acceptance: task.acceptance ?? [],
|
||||
}) + '\n结果未知的调用,不得假定成功或重放:' + JSON.stringify(unknown)
|
||||
@@ -420,11 +431,11 @@ export class Runtime {
|
||||
}
|
||||
async stop(sessionId) {
|
||||
const run = this.active.get(sessionId);
|
||||
if (!run) { await this.checks?.stop(sessionId); await this.deliveries?.stop(sessionId); await this.changeSets?.stop(sessionId); return; }
|
||||
if (!run) { await this.checks?.stop(sessionId); await this.deliveries?.stop(sessionId); await this.changeSets?.stop(sessionId); await this.workspaces?.stop(sessionId); return; }
|
||||
const session = this.store.session(sessionId);
|
||||
session.status = 'stopping'; this.store.save(session);
|
||||
run.controller.abort(new Error('用户停止任务'));
|
||||
await run.promise;
|
||||
}
|
||||
async stopAll() { await Promise.all([...this.active.keys()].map(id => this.stop(id))); await this.checks?.stopAll(); await this.deliveries?.stopAll(); await this.changeSets?.stopAll(); }
|
||||
async stopAll() { await Promise.all([...this.active.keys()].map(id => this.stop(id))); await this.checks?.stopAll(); await this.deliveries?.stopAll(); await this.changeSets?.stopAll(); await this.workspaces?.stopAll(); }
|
||||
}
|
||||
|
||||
+42
-6
@@ -7,6 +7,7 @@ import { StateDatabase, runtimeOwnerAlive } from '../core/storage/state-database
|
||||
import { ArtifactStore } from '../core/storage/artifact-store.mjs';
|
||||
import { collectLegacy, cleanConfig } from '../core/storage/legacy-import.mjs';
|
||||
import { ACTIVE_STATES, CORE_KINDS, createTask, createRun, ownedRecord, emptyUsage, accumulateUsage, accountedTokens, isId } from '../shared/contracts/execution.mjs';
|
||||
import { WORKSPACE_ACTIVE, projectWorkspaceIdentity, assertWorkspacePath } from '../shared/contracts/workspaces.mjs';
|
||||
|
||||
export const now = () => new Date().toISOString();
|
||||
|
||||
@@ -210,6 +211,11 @@ export class Store extends EventEmitter {
|
||||
set.summary = '文件批次在执行中断;请核对实际原文/建议字节,不会自动续写或回退。';
|
||||
session.status = 'paused'; session.recoveryNotice = set.summary; changed = true;
|
||||
}
|
||||
for (const workspace of this.core.workspace.values()) if (workspace.sessionId === session.id && WORKSPACE_ACTIVE.has(workspace.status)) {
|
||||
workspace.status = 'unknown'; workspace.requiresVerification = true; workspace.finishedAt = now();
|
||||
workspace.summary = '隔离工作区创建中断,请核对实际目录、分支和Git登记。不会重放创建、删除或重置。';
|
||||
session.status = 'paused'; session.recoveryNotice = workspace.summary; changed = true;
|
||||
}
|
||||
for (const event of session.events ?? []) {
|
||||
if (['running', 'waiting', 'retrying'].includes(event.phase)) {
|
||||
const invocation = [...this.core.tool.values()].find(item => item.sessionId === session.id && item.callId === event.toolCallId);
|
||||
@@ -291,13 +297,27 @@ export class Store extends EventEmitter {
|
||||
return this.config;
|
||||
}
|
||||
|
||||
addProject(root) {
|
||||
addProject(root, { id = null, name = null, workspace = null } = {}) {
|
||||
if (id !== null && !isId(id) || name !== null && (typeof name !== 'string' || !name.trim() || name.length > 200 || /[\x00-\x1f]/.test(name))) throw new Error('内部项目身份或名称无效。');
|
||||
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() };
|
||||
if (existing) {
|
||||
if (id && existing.id !== id || workspace && JSON.stringify(existing.workspace) !== JSON.stringify(workspace)) throw Object.assign(new Error('目标目录已经属于另一个项目身份,不能替换。'), { status: 409 });
|
||||
return existing;
|
||||
}
|
||||
if (id && this.projects.some(project => project.id === id)) throw Object.assign(new Error('项目身份已经用于另一个目录。'), { status: 409 });
|
||||
if (workspace) {
|
||||
const record = this.core.workspace.get(workspace.id), source = record && this.project(record.projectId);
|
||||
const expected = record && { id: record.id, sourceProjectId: record.projectId, sourceSessionId: record.sessionId, sourceRoot: record.source.root,
|
||||
sourceWorkspaceId: source.workspace?.id ?? null, baseCommit: record.source.head, branch: record.branch,
|
||||
commonGitDir: record.source.commonDir, gitDir: record.observation?.gitDir, fingerprint: record.fingerprint };
|
||||
if (!record || record.status !== 'registering' || record.childProjectId !== id || record.root !== resolved
|
||||
|| JSON.stringify(workspace) !== JSON.stringify(expected)) throw Object.assign(new Error('工作区项目必须来自已验证的持久创建记录。'), { status: 409 });
|
||||
assertWorkspacePath({ root: resolved, workspace });
|
||||
}
|
||||
const project = { id: id ?? randomUUID(), root: resolved, name: name ?? path.basename(resolved), addedAt: now(), ...(workspace ? { workspace: structuredClone(workspace) } : {}) };
|
||||
const next = [project, ...this.projects];
|
||||
this.storage.transaction(() => this.storage.writeProjects(next));
|
||||
this.projects = next;
|
||||
@@ -310,10 +330,16 @@ export class Store extends EventEmitter {
|
||||
return project;
|
||||
}
|
||||
|
||||
createSession(projectId, title = '新任务') {
|
||||
createSession(projectId, title = '新任务', { id = null } = {}) {
|
||||
this.project(projectId);
|
||||
if (id !== null && !isId(id)) throw new Error('内部会话身份无效。');
|
||||
if (id && this.sessions.has(id)) {
|
||||
const existing = this.sessions.get(id);
|
||||
if (existing.projectId !== projectId) throw Object.assign(new Error('会话身份已经属于另一个项目。'), { status: 409 });
|
||||
return existing;
|
||||
}
|
||||
const session = {
|
||||
id: randomUUID(), projectId, title, status: 'idle', createdAt: now(), updatedAt: now(),
|
||||
id: 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,
|
||||
@@ -340,7 +366,11 @@ export class Store extends EventEmitter {
|
||||
if (task.readProgress) {
|
||||
task.readProgress.repeated = 0; task.readProgress.changingIndexes = []; task.readProgress.warning = null; task.readProgress.pause = false;
|
||||
}
|
||||
const workspaceIdentity = projectWorkspaceIdentity(this.project(session.projectId));
|
||||
task.workspaceIdentity ??= structuredClone(workspaceIdentity);
|
||||
if (JSON.stringify(task.workspaceIdentity) !== JSON.stringify(workspaceIdentity)) throw Object.assign(new Error('任务的工作区身份已变化,不能将原任务移动到另一个工作区。'), { status: 409 });
|
||||
const run = createRun(session, task, config, resume ? previousRunId : null);
|
||||
run.workspaceIdentity = structuredClone(workspaceIdentity);
|
||||
this.core.run.set(run.id, run); task.activeRunId = run.id;
|
||||
session.taskId = task.id; session.runId = run.id; session.status = 'running';
|
||||
this.save(session, { type: 'run.started', detail: { resumeOf: run.resumeOf } });
|
||||
@@ -467,11 +497,17 @@ export class Store extends EventEmitter {
|
||||
const tools = [...this.core.tool.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id);
|
||||
const artifacts = [...this.core.artifact.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-30);
|
||||
const jobs = [...this.core.check_job.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-10);
|
||||
const projectWorkspaces = [...this.core.workspace.values()].filter(value => value.projectId === session.projectId);
|
||||
const recentWorkspaceIds = new Set(projectWorkspaces.slice(-12).map(value => value.id));
|
||||
return {
|
||||
schemaVersion: 1, task: task ?? null, run: run ?? null,
|
||||
workspaceIdentity: projectWorkspaceIdentity(this.project(session.projectId)),
|
||||
workspaces: projectWorkspaces.filter(value => recentWorkspaceIds.has(value.id) || value.requiresVerification
|
||||
|| ['prepared', 'creating', 'verifying', 'registering'].includes(value.status)),
|
||||
runs: [...this.core.run.values()].filter(value => value.sessionId === session.id).slice(-20).map(value => ({ id: value.id, taskId: value.taskId,
|
||||
status: value.status, startedAt: value.startedAt, finishedAt: value.finishedAt, steps: value.steps, toolCalls: value.toolCalls,
|
||||
usage: value.usage, stopReason: value.stopReason, model: value.model, budget: value.budget, resumeOf: value.resumeOf })),
|
||||
usage: value.usage, stopReason: value.stopReason, model: value.model, budget: value.budget, resumeOf: value.resumeOf,
|
||||
...(value.workspaceIdentity ? { workspaceIdentity: value.workspaceIdentity } : {}), ...(value.review ? { review: value.review } : {}) })),
|
||||
progress: { totalTools: tools.length, completedTools: tools.filter(value => value.state === 'completed').length,
|
||||
requiresVerification: tools.filter(value => value.requiresVerification).map(value => ({ id: value.id, tool: value.tool, callId: value.callId, state: value.state })) },
|
||||
artifacts, checks: jobs,
|
||||
|
||||
Reference in New Issue
Block a user