feat: connect controlled engines to owned Tasks, approvals and budget ledger
This commit is contained in:
@@ -7,6 +7,7 @@ import { assertProposalUnsealed } from '../shared/contracts/change-sets.mjs';
|
||||
import { assertWorkspacesResolved } from '../shared/contracts/workspaces.mjs';
|
||||
import { verifyWorkspaceProject } from '../core/workspaces/git-workspaces.mjs';
|
||||
import { publicEngineJob } from '../shared/contracts/engines.mjs';
|
||||
import { publicEngineRun, verifyEngineInput, originalEngineRun } from '../shared/contracts/engine-execution.mjs';
|
||||
import { verifyBrowserJob } from '../core/browser/browser-manager.mjs';
|
||||
import { ConfigImporter } from '../core/models/config-import.mjs';
|
||||
import { ProjectMemoryManager } from '../core/memory/project-memory.mjs';
|
||||
@@ -185,6 +186,7 @@ return async (request, response) => {
|
||||
}
|
||||
if (method === 'GET' && route === '/api/research/availability') return json(response, runtime.researchManager().availability());
|
||||
if (method === 'GET' && route === '/api/engines/deepseek/availability') return json(response, runtime.engineManager().availability(url.searchParams.has('root') ? url.searchParams.get('root') : undefined));
|
||||
if (method === 'GET' && route === '/api/engines/deepseek/controlled-availability') return json(response, runtime.engineRunner().availability(url.searchParams.has('root') ? url.searchParams.get('root') : undefined));
|
||||
if (method === 'GET' && route === '/api/events') {
|
||||
const cursor = Math.max(cursorNumber(url.searchParams.get('after')), cursorNumber(request.headers['last-event-id']));
|
||||
if (cursor > store.eventCursor) throw Object.assign(new Error('事件游标超出当前历史,请重新加载工作台。'), { status: 409 });
|
||||
@@ -277,6 +279,21 @@ return async (request, response) => {
|
||||
}
|
||||
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 === 'engine-runs') return json(response, [...store.core.engine_run.values()].filter(job => job.sessionId === id).slice(-30).map(publicEngineRun));
|
||||
const engineRun = action.match(/^engine-runs\/([a-f0-9-]+)\/(input|report|download)$/);
|
||||
if (method === 'GET' && engineRun) {
|
||||
const job = store.owned('engine_run', engineRun[1], id);
|
||||
const text = engineRun[2] === 'input' ? store.artifactStore.read(verifyEngineInput(store, session, job)) : originalEngineRun(store, session, job);
|
||||
if (engineRun[2] !== 'download') {
|
||||
const artifact = store.owned('artifact', engineRun[2] === 'input' ? job.inputArtifactId : job.reportArtifactId, id);
|
||||
const offset = cursorNumber(url.searchParams.get('offset')), limit = Math.min(16000, url.searchParams.has('limit') ? cursorNumber(url.searchParams.get('limit')) : 4000);
|
||||
if (!limit || offset > text.length) throw Object.assign(new Error('原引擎记录的读取位置或页长超出范围。'), { status: 400 });
|
||||
return json(response, { ...artifact, content: text.slice(offset, offset + limit), offset, totalCharacters: text.length, truncated: offset + limit < text.length });
|
||||
}
|
||||
response.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store',
|
||||
'X-Content-Type-Options': 'nosniff', ...(engineRun[2] === 'download' ? { 'Content-Disposition': 'attachment; filename="agent-workbench-engine-run-' + job.id + '.json"' } : {}) });
|
||||
response.end(text); return;
|
||||
}
|
||||
if (method === 'GET' && action === 'mcp/jobs') return json(response, runtime.mcpRegistry().jobs(session));
|
||||
if (method === 'POST' && action === 'mcp/probe') {
|
||||
const started = runtime.mcpRegistry().start(session, await body(request));
|
||||
|
||||
@@ -177,13 +177,13 @@ export class Provider {
|
||||
const response = await this.request(config, '/models', undefined, undefined, key);
|
||||
return (response.data ?? response.models ?? []).map(item => String(item.id ?? item.name)).filter(Boolean).slice(0, 100);
|
||||
}
|
||||
async complete(config, messages, project, signal, onProgress, requestPlan = null, tools = toolDefinitions) {
|
||||
async complete(config, messages, project, signal, onProgress, requestPlan = null, tools = toolDefinitions, requestPolicy = {}) {
|
||||
const body = completionBody(config, messages, tools);
|
||||
assertPlannedRequest(body, requestPlan);
|
||||
if (config.mode === 'demo') return this.demo(messages, project);
|
||||
this.validate(config);
|
||||
const execute = async (selected, key, input, progress) => {
|
||||
const value = await this.request(selected, '/chat/completions', input, signal, key, progress, config.modelRouting ? { attempts: 1 } : {});
|
||||
const value = await this.request(selected, '/chat/completions', input, signal, key, progress, { ...(config.modelRouting ? { attempts: 1 } : {}), ...requestPolicy });
|
||||
if (!value.choices?.[0]?.message || value.choices[0].finish_reason === 'length') throw new ModelRequestError({ kind: 'protocol', source: 'model_connection',
|
||||
stage: 'model_request', title: '模型响应不完整', message: '模型响应缺少完整message或达到输出上限,未执行工具。', retryable: false, occurredAt: new Date().toISOString() });
|
||||
return value;
|
||||
|
||||
+22
-6
@@ -22,6 +22,7 @@ import { WorkspaceManager, verifyWorkspaceProject } from '../core/workspaces/git
|
||||
import { assertWorkspacesResolved, projectWorkspaceIdentity } from '../shared/contracts/workspaces.mjs';
|
||||
import { ResearchManager } from '../core/research-manager.mjs';
|
||||
import { EngineManager } from '../core/engine-manager.mjs';
|
||||
import { EngineRunner } from '../core/engines/engine-runner.mjs';
|
||||
import { BrowserManager, publicBrowserPlan } from '../core/browser/browser-manager.mjs';
|
||||
import { browserPlanInput } from '../shared/contracts/browser.mjs';
|
||||
import { TaskPlanManager } from '../core/tasks/task-plan-manager.mjs';
|
||||
@@ -118,6 +119,7 @@ export class Runtime {
|
||||
redact: value => this.provider.redact(value), projectBusy: projectId => this.projectHasActivity(projectId) });
|
||||
}
|
||||
requestPlanner() { return this.contextPlans ??= new RequestPlanner(this.store); }
|
||||
engineRunner() { return this.controlledEngines ??= new EngineRunner(this.store, this.provider, { appDirectory: this.appDirectory }); }
|
||||
memoryManager() { return this.projectMemories ??= new ProjectMemoryManager(this.store); }
|
||||
checkpointManager() { return this.taskCheckpoints ??= new TaskCheckpointManager(this.store, {
|
||||
taskPlans: this.taskPlanner(), redact: value => this.provider.redact(value) }); }
|
||||
@@ -267,29 +269,38 @@ export class Runtime {
|
||||
' tokens;省略 ' + planned.record.archivedGroups + ' 个完整消息组,原历史和参数已保存为SHA256工件。估算与服务实际用量分别记录。' });
|
||||
}
|
||||
let requestEvent;
|
||||
let response, requestStarted = false, responseAccounted = false;
|
||||
const externalEngine = !!run.worker?.engine;
|
||||
if (externalEngine) { planned.record.engineStepOnly = true; planned.record.engine = 'deepseek-workbench'; }
|
||||
let response, requestStarted = false, responseAccounted = externalEngine;
|
||||
try {
|
||||
signal.throwIfAborted(); checkBudget(run.record, task);
|
||||
if (run.worker) { planned.record.workerDispatchedAt = now(); this.store.save(session, { type: 'worker.request_intent' }); }
|
||||
if (run.worker && !externalEngine) { planned.record.workerDispatchedAt = now(); this.store.save(session, { type: 'worker.request_intent' }); }
|
||||
requestStarted = true;
|
||||
response = await this.provider.complete(config, planned.messages, run.project, signal, progress => {
|
||||
if (!requestEvent) requestEvent = this.store.event(session, { kind: 'model', runId: run.id, source: 'model_connection', label: '请求模型服务', phase: 'running', startedAt: now(), contextPlanId: planned.record.id });
|
||||
const progressHandler = progress => {
|
||||
if (!requestEvent) requestEvent = this.store.event(session, { kind: externalEngine ? 'engine' : 'model', runId: run.id,
|
||||
source: externalEngine ? 'controlled_engine' : 'model_connection', label: externalEngine ? '受控引擎执行' : '请求模型服务', phase: 'running', startedAt: now(), contextPlanId: planned.record.id });
|
||||
if (progress.engineRunId) requestEvent.engineRunId = progress.engineRunId;
|
||||
planned.record.status = progress.phase === 'running' || progress.phase === 'retrying' ? 'requesting' : planned.record.status;
|
||||
planned.record.requestAttempts = Math.max(planned.record.requestAttempts, progress.attempt ?? 0);
|
||||
stepRecord.modelAttempts = Math.max(stepRecord.modelAttempts, progress.attempt ?? 0);
|
||||
requestEvent.phase = progress.phase; requestEvent.attempts = progress.attempt;
|
||||
if (progress.connectionId) { requestEvent.connectionId = progress.connectionId; requestEvent.modelAttemptId = progress.modelAttemptId; requestEvent.actualModel = progress.model; }
|
||||
requestEvent.label = progress.switching ? '正在切换模型池连接' : progress.phase === 'retrying' ? '正在重试模型连接' : progress.phase === 'completed' ? '模型响应已收到' : progress.phase === 'failed' ? '模型连接失败' : '请求模型服务';
|
||||
if (externalEngine) requestEvent.label = progress.phase === 'completed' ? '引擎原结果已收到' : '受控引擎执行';
|
||||
requestEvent.output = progress.phase === 'retrying' ? '第 ' + progress.attempt + ' 次请求失败,将自动重试(最多 ' + progress.maxAttempts + ' 次)。'
|
||||
: progress.phase === 'completed' ? '模型响应已收到;工具请求将在校验后执行。'
|
||||
: progress.diagnostic?.message ?? '正在等待模型响应。';
|
||||
if (externalEngine) requestEvent.output = progress.phase === 'completed' ? '原引擎工具请求或最终输出已返回,后续按所属任务核验。' : '等待所属引擎;实际模型尝试另有记录。';
|
||||
if (progress.diagnostic) requestEvent.diagnostic = progress.diagnostic;
|
||||
if (progress.durationMs !== undefined) requestEvent.durationMs = progress.durationMs;
|
||||
if (['completed', 'failed'].includes(progress.phase)) requestEvent.finishedAt = now();
|
||||
this.store.save(session);
|
||||
}, planned.record, tools);
|
||||
};
|
||||
response = externalEngine
|
||||
? await this.engineRunner().complete(session, run, planned.messages, progressHandler, planned.record, tools)
|
||||
: await this.provider.complete(config, planned.messages, run.project, signal, progressHandler, planned.record, tools);
|
||||
this.requestPlanner().finish(session, planned.record, { response, attempts: planned.record.requestAttempts });
|
||||
if (run.worker) {
|
||||
if (run.worker && !externalEngine) {
|
||||
this.store.recordResponse(session, run.record, response.usage, planned.record.estimatedInputTokens + Math.ceil(Buffer.byteLength(JSON.stringify(response.message), 'utf8') / 3) + 8);
|
||||
planned.record.workerUsageAccounted = true; this.store.save(session); responseAccounted = true;
|
||||
}
|
||||
@@ -323,6 +334,7 @@ export class Runtime {
|
||||
if (!calls.length) {
|
||||
this.store.finishStep(session, stepRecord);
|
||||
session.status = session.changes.some(change => ['pending', 'conflict'].includes(change.status)) ? 'needs_review' : 'completed';
|
||||
if (externalEngine) await this.engineRunner().finish(session, run);
|
||||
if (session.status === 'completed' && run.worker) {
|
||||
try { await this.workerManager().output(session, run.worker); signal.throwIfAborted(); }
|
||||
catch (error) {
|
||||
@@ -407,6 +419,8 @@ export class Runtime {
|
||||
output: diagnostic.message, diagnostic: session.lastFailure });
|
||||
}
|
||||
this.store.save(session);
|
||||
} finally {
|
||||
if (run.worker?.engine) await this.engineRunner().finish(session, run);
|
||||
}
|
||||
}
|
||||
async executeTool(session, call, run) {
|
||||
@@ -419,6 +433,7 @@ export class Runtime {
|
||||
const args = JSON.parse(call.function.arguments);
|
||||
validateToolArgs(tool, args);
|
||||
assertWorkerTool(this.store, session, tool, args);
|
||||
if (run.worker?.engine) this.engineRunner().assertCurrent(session, run);
|
||||
event.input = JSON.parse(this.provider.redact(JSON.stringify(args)));
|
||||
const proofHint = !!this.store.core.task.get(run.taskId)?.currentTaskPlanId && PLAN_READ_TOOLS.includes(tool);
|
||||
const readMetadata = { ...(proofHint ? { tool_invocation_id: event.invocationId } : {}),
|
||||
@@ -580,6 +595,7 @@ export class Runtime {
|
||||
const cwd = safePath(run.project);
|
||||
event.phase = 'running'; event.executedAt = now(); session.status = 'running';
|
||||
this.store.invocationState(session, event, 'running');
|
||||
if (run.worker?.engine) this.engineRunner().assertCurrent(session, run);
|
||||
if (execute) return execute();
|
||||
return this.executeCommand(command, cwd, run.controller.signal, output => {
|
||||
event.output = output; this.store.save(session);
|
||||
|
||||
+26
-2
@@ -10,6 +10,7 @@ import { ACTIVE_STATES, CORE_KINDS, createTask, createRun, ownedRecord, emptyUsa
|
||||
import { WORKSPACE_ACTIVE, projectWorkspaceIdentity, assertWorkspacePath } from '../shared/contracts/workspaces.mjs';
|
||||
import { RESEARCH_ACTIVE } from '../shared/contracts/research.mjs';
|
||||
import { ENGINE_ACTIVE, publicEngineJob } from '../shared/contracts/engines.mjs';
|
||||
import { ENGINE_RUN_ACTIVE, publicEngineRun, verifyEngineModelInput } from '../shared/contracts/engine-execution.mjs';
|
||||
import { BROWSER_ACTIVE } from '../shared/contracts/browser.mjs';
|
||||
import { publicBrowserPlan } from '../core/browser/browser-manager.mjs';
|
||||
import { MCP_ACTIVE } from '../core/tools/mcp-contract.mjs';
|
||||
@@ -192,7 +193,7 @@ export class Store extends EventEmitter {
|
||||
step.status = 'interrupted'; step.finishedAt = now(); changed = true;
|
||||
}
|
||||
for (const plan of this.core.context_plan.values()) if (plan.sessionId === session.id) {
|
||||
if (plan.workerDispatchedAt && !plan.workerUsageAccounted) {
|
||||
if (plan.workerDispatchedAt && !plan.workerUsageAccounted && !plan.engineStepOnly) {
|
||||
const run = this.core.run.get(plan.runId);
|
||||
if (run && this.core.task.get(run.taskId)?.workerId) {
|
||||
this.recordResponse(session, run, null, plan.estimatedInputTokens + (run.model.maxOutputTokens ?? 2048));
|
||||
@@ -252,6 +253,28 @@ export class Store extends EventEmitter {
|
||||
worker.summary = '子执行在宿主中断时没有完整收尾;原进程结束及实际修改待核对,不按历史PID停止进程或重放工具。';
|
||||
session.status = 'paused'; session.recoveryNotice = worker.summary; changed = true;
|
||||
}
|
||||
for (const job of this.core.engine_run.values()) if (job.sessionId === session.id && ENGINE_RUN_ACTIVE.has(job.status)) {
|
||||
for (const request of job.requests) if (request.dispatchedAt && !request.finishedAt) {
|
||||
const run = this.core.run.get(job.runId);
|
||||
try {
|
||||
verifyEngineModelInput(this, session, job, request);
|
||||
const count = request.actualAttemptsFinal ?? request.maxAttempts;
|
||||
if (run) while (request.accountedAttempts < count) {
|
||||
request.accountedAttempts++; this.recordResponse(session, run, null, request.reservedPerAttempt);
|
||||
request.recoveredUnknownAttempts = (request.recoveredUnknownAttempts ?? 0) + 1;
|
||||
}
|
||||
} catch (error) {
|
||||
request.verificationError = error.message;
|
||||
if (run) this.recordResponse(session, run, null, Math.max(0, this.core.task.get(job.taskId).budget.maxTokens - accountedTokens(this.core.task.get(job.taskId).usage)));
|
||||
request.recoveryConservativeCharge = true;
|
||||
}
|
||||
request.status = 'interrupted'; request.finishedAt = now();
|
||||
request.error = '宿主中断,原模型结果未完整封存;按原尝试预算核对,不自动请求。';
|
||||
}
|
||||
job.status = 'unknown'; job.requiresVerification = true; job.verified = false; job.finishedAt = now();
|
||||
job.error = '受控引擎宿主中断,原工具/模型结果及进程树待核对。原输入保留,不按历史PID终止或重放。';
|
||||
session.status = 'paused'; session.recoveryNotice = job.error; changed = true;
|
||||
}
|
||||
for (const job of this.core.engine_job.values()) if (job.sessionId === session.id && ENGINE_ACTIVE.has(job.status)) {
|
||||
job.status = 'unknown'; job.requiresVerification = true; job.verification = null; job.finishedAt = now();
|
||||
job.summary = '外部引擎连接检查中断,原进程关闭状态未知。不会根据历史PID停止进程或重放请求,请查看所属原记录。';
|
||||
@@ -307,7 +330,7 @@ export class Store extends EventEmitter {
|
||||
for (const group of this.core.collaboration.values()) {
|
||||
const unresolved = group.children.some(child => this.core.worker.get(child.id)?.requiresVerification
|
||||
|| this.core.workspace.get(child.workspaceId)?.requiresVerification
|
||||
|| ['tool', 'check_job', 'change_set'].some(kind => [...this.core[kind].values()].some(record => record.taskId === child.taskId && record.requiresVerification)))
|
||||
|| ['tool', 'check_job', 'change_set', 'engine_run'].some(kind => [...this.core[kind].values()].some(record => record.taskId === child.taskId && record.requiresVerification)))
|
||||
|| [...this.core.change_set.values()].some(set => set.taskId === group.taskId && set.requiresVerification);
|
||||
if (!COLLABORATION_CLOSED.has(group.status) && unresolved && (!group.requiresVerification || group.status !== 'unknown')) {
|
||||
group.status = 'unknown'; group.requiresVerification = true; group.finishedAt = now();
|
||||
@@ -584,6 +607,7 @@ export class Store extends EventEmitter {
|
||||
researchTargets: [...this.core.research_target.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-32),
|
||||
researchJobs: [...this.core.research_job.values()].filter(value => value.sessionId === session.id && (value.taskId === task?.id || value.requiresVerification)).slice(-20),
|
||||
engineJobs: [...this.core.engine_job.values()].filter(value => value.sessionId === session.id && (value.taskId === task?.id || value.requiresVerification)).slice(-20).map(publicEngineJob),
|
||||
engineRuns: [...this.core.engine_run.values()].filter(value => value.sessionId === session.id && (value.taskId === task?.id || value.requiresVerification)).slice(-20).map(publicEngineRun),
|
||||
browserPlans: [...this.core.browser_plan.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-5).map(publicBrowserPlan),
|
||||
browserJobs: [...this.core.browser_job.values()].filter(value => value.sessionId === session.id && (value.taskId === task?.id || value.requiresVerification)).slice(-12),
|
||||
contextPlans: [...this.core.context_plan.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-30),
|
||||
|
||||
Reference in New Issue
Block a user