feat: preserve bounded model requests and complete task history
This commit is contained in:
+33
-19
@@ -3,7 +3,7 @@ import path from 'node:path';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { StringDecoder } from 'node:string_decoder';
|
||||
import { safePath, listFiles, readLines, searchFiles, proposeFile, proposePatch } from './files.mjs';
|
||||
import { projectContext, projectMessages } from './provider.mjs';
|
||||
import { projectContext, toolDefinitions } from './provider.mjs';
|
||||
import { now, repairToolPairs } from './store.mjs';
|
||||
import { executionEnvironment, sessionContext, sessionSnapshot } from './diagnostics.mjs';
|
||||
import { BudgetExceeded, checkBudget } from '../shared/contracts/execution.mjs';
|
||||
@@ -11,6 +11,7 @@ import { CheckRunner } from '../core/check-runner.mjs';
|
||||
import { inspectProject } from '../core/project-inspector.mjs';
|
||||
import { GitDelivery } from '../core/git-delivery.mjs';
|
||||
import { ProjectIndex } from '../core/context/project-index.mjs';
|
||||
import { RequestPlanner } from '../core/context/request-plan.mjs';
|
||||
import { ChangeSetManager } from '../core/workspaces/change-sets.mjs';
|
||||
import { assertChangeSetsResolved } from '../shared/contracts/change-sets.mjs';
|
||||
|
||||
@@ -47,6 +48,7 @@ export class Runtime {
|
||||
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; }
|
||||
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);
|
||||
}
|
||||
@@ -118,25 +120,32 @@ export class Runtime {
|
||||
signal.throwIfAborted();
|
||||
checkBudget(run.record, this.store.core.task.get(run.taskId));
|
||||
const stepRecord = this.store.beginStep(session, run.record);
|
||||
const projected = projectMessages(session.providerMessages, config.contextLimit);
|
||||
session.estimatedTokens = projected.estimatedTokens;
|
||||
if (projected.projected && !projectionLogged) {
|
||||
const task = this.store.core.task.get(run.taskId);
|
||||
const state = session.changes.filter(change => change.taskId === task.id || ['pending', 'conflict'].includes(change.status))
|
||||
.map(change => ({ path: change.path, status: change.status, id: change.id, changeSetId: change.changeSetId ?? null }));
|
||||
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)
|
||||
+ '\n当前任务目标与全部追加要求(用户任务数据,完整保留):\n' + JSON.stringify({
|
||||
goal: task.goal, instructions: task.instructions, constraints: task.constraints ?? [], acceptance: task.acceptance ?? [],
|
||||
}) + '\n结果未知的调用,不得假定成功或重放:' + JSON.stringify(unknown)
|
||||
+ '\n' + sessionContext(session, run.project, config, value => this.provider.redact(value)));
|
||||
const planned = this.requestPlanner().prepare(session, run.record, config, { system: context, tools: toolDefinitions, stepId: stepRecord.id });
|
||||
if (planned.record.archivedGroups && !projectionLogged) {
|
||||
projectionLogged = true; session.compactions++;
|
||||
this.store.event(session, { kind: 'context', label: '整理请求上下文', phase: 'completed',
|
||||
output: '本地提取式投影:估算 ' + projected.beforeTokens + ' → ' + projected.estimatedTokens + ' tokens;完整历史仍保留在会话文件中。' });
|
||||
this.store.event(session, { kind: 'context', label: '整理请求上下文', phase: 'completed', contextPlanId: planned.record.id,
|
||||
output: '完整请求输入估算 ' + planned.record.beforeInputTokens + ' → ' + planned.record.estimatedInputTokens +
|
||||
' tokens;省略 ' + planned.record.archivedGroups + ' 个完整消息组,原历史和参数已保存为SHA256工件。估算与服务实际用量分别记录。' });
|
||||
}
|
||||
const state = session.changes.map(change => ({ path: change.path, status: change.status, id: change.id }));
|
||||
const context = projectContext(run.project) + '\n当前文件提案状态:' + JSON.stringify(state).slice(0, 8000)
|
||||
+ '\n当前任务目标与追加要求(来自用户,完整原文保存在任务记录):\n' + JSON.stringify({
|
||||
goal: this.store.core.task.get(run.taskId).goal,
|
||||
instructions: this.store.core.task.get(run.taskId).instructions.slice(-8),
|
||||
acceptance: this.store.core.task.get(run.taskId).acceptance,
|
||||
}).slice(0, 16000)
|
||||
+ '\n' + sessionContext(session, run.project, config, value => this.provider.redact(value));
|
||||
if (projected.estimatedTokens > config.contextLimit * 2) throw new Error('这次任务上下文仍超出预算,请缩小读取范围或新建会话。');
|
||||
let requestEvent;
|
||||
const response = await this.provider.complete(config, [{ role: 'system', content: context }, ...projected.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() });
|
||||
let response;
|
||||
try {
|
||||
signal.throwIfAborted(); checkBudget(run.record, task);
|
||||
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 });
|
||||
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;
|
||||
requestEvent.label = progress.phase === 'retrying' ? '正在重试模型连接' : progress.phase === 'completed' ? '模型响应已收到' : progress.phase === 'failed' ? '模型连接失败' : '请求模型服务';
|
||||
@@ -147,14 +156,19 @@ export class Runtime {
|
||||
if (progress.durationMs !== undefined) requestEvent.durationMs = progress.durationMs;
|
||||
if (['completed', 'failed'].includes(progress.phase)) requestEvent.finishedAt = now();
|
||||
this.store.save(session);
|
||||
});
|
||||
}, planned.record);
|
||||
this.requestPlanner().finish(session, planned.record, { response, attempts: planned.record.requestAttempts });
|
||||
} catch (error) {
|
||||
this.requestPlanner().finish(session, planned.record, { error: Object.assign(new Error(this.provider.redact(error.message ?? String(error))), { name: signal.aborted ? 'AbortError' : error.name }), attempts: planned.record.requestAttempts });
|
||||
throw error;
|
||||
}
|
||||
signal.throwIfAborted();
|
||||
const message = response.message;
|
||||
const calls = message.tool_calls ?? [];
|
||||
const previousIds = new Set(session.providerMessages.flatMap(item => (item.tool_calls ?? []).map(call => call.id)));
|
||||
if (new Set(calls.map(call => call.id)).size !== calls.length || calls.some(call => previousIds.has(call.id))) throw new Error('模型返回了重复的工具调用 ID,请重新发送任务。');
|
||||
session.providerMessages.push(message);
|
||||
this.store.recordResponse(session, run.record, response.usage, projected.estimatedTokens + Math.ceil(JSON.stringify(message).length / 4));
|
||||
this.store.recordResponse(session, run.record, response.usage, planned.record.estimatedInputTokens + Math.ceil(Buffer.byteLength(JSON.stringify(message), 'utf8') / 3) + 8);
|
||||
for (const call of calls) {
|
||||
const event = { id: randomUUID(), createdAt: now(), startedAt: now(), kind: 'tool', phase: 'queued',
|
||||
toolCallId: call.id, tool: call.function.name, label: labels[call.function.name] ?? call.function.name, taskId: run.taskId, runId: run.id };
|
||||
|
||||
Reference in New Issue
Block a user