feat(context): audit tool visibility and isolate diagnostic history
This commit is contained in:
+42
-14
@@ -30,6 +30,8 @@ import { projectEnvironment } from '../core/process-environment.mjs';
|
||||
import { GitDelivery } from '../core/git-delivery.mjs';
|
||||
import { ProjectIndex } from '../core/context/project-index.mjs';
|
||||
import { RequestPlanner, verifyPlanEvidence } from '../core/context/request-plan.mjs';
|
||||
import { observeToolSurface } from '../core/context/tool-surface.mjs';
|
||||
import { providerHistory } from '../core/context/request-observation.mjs';
|
||||
import { ENGINE_SEED_RESERVATION } from '../shared/contracts/engine-context.mjs';
|
||||
import { InputAttachments } from '../core/context/input-attachments.mjs';
|
||||
import { BudgetResume } from '../core/context/budget-resume.mjs';
|
||||
@@ -291,6 +293,7 @@ export class Runtime {
|
||||
if (attachments.length && config.mode==='demo') throw Object.assign(new Error('演示执行器不会读取图片,请先选择支持视觉的模型连接。'),{status:409});
|
||||
if (!unrestricted(config) && attachments.length && !config.modelRouting) throw Object.assign(new Error('请在模型中心添加并声明支持视觉的连接,再发送图片。'),{status:409});
|
||||
const record = this.store.beginRun(session, content, resume, config, { instructionSource, inputAttachments:attachments,resumePlan });
|
||||
if (record.purpose === 'diagnostic') record.diagnosticMessages = structuredClone(session.providerMessages);
|
||||
const run = { controller, id: record.id, taskId: record.taskId, project, record, config, ...(worker ? { worker } : {}) };
|
||||
this.active.set(id, run);
|
||||
session.status = 'running'; session.recoveryNotice = null; session.executionMode = config.mode;
|
||||
@@ -299,7 +302,9 @@ export class Runtime {
|
||||
if (!resume || content) {
|
||||
const userMessage=this.store.message(session, 'user', String(content));
|
||||
if(attachments.length)userMessage.attachmentIds=attachments.map(row=>row.boundAttachmentId);
|
||||
session.providerMessages.push({ role: 'user', content: String(content) });
|
||||
const history = providerHistory(session, record);
|
||||
record.inputMessage = { id: userMessage.id, providerIndex: history.length, origin: instructionSource ? 'system_action' : 'user' };
|
||||
history.push({ role: 'user', content: String(content) });
|
||||
}
|
||||
if (resume) this.store.message(session, 'system', '从已保存的执行记录继续,已完成的工具结果保留。');
|
||||
session.failure = null;
|
||||
@@ -412,15 +417,38 @@ export class Runtime {
|
||||
}) : ''));
|
||||
const skillCatalog = run.worker ? null : this.skillRegistry().catalog(session.projectId);
|
||||
const mcpCatalog = run.worker ? null : this.mcpRegistry().catalog(session.projectId);
|
||||
const availableTools = [...toolDefinitions, ...(unrestricted(config) ? automaticToolDefinitions : []), ...taskPlanToolDefinitions, ...fileResultToolDefinitions, ...(unrestricted(config) || [...this.store.core.browsing_tab.values()].some(tab=>tab.sessionId===session.id&&tab.taskId===run.taskId&&tab.status==='open')?browsingToolDefinitions:[]), ...(skillCatalog?.entries.some(value => value.status === 'current') ? skillToolDefinitions : []),
|
||||
...(mcpCatalog?.entries.length ? mcpToolDefinitions : []),
|
||||
...([...this.store.core.research_target.values()].some(target => target.sessionId === session.id && target.taskId === run.taskId) ? researchToolDefinitions : []),
|
||||
...([...this.store.core.engine_job.values()].some(job => job.sessionId === session.id && job.taskId === run.taskId) ? engineToolDefinitions : []),
|
||||
...(this.browserManager().builds(run.project).length || [...this.store.core.browser_plan.values()].some(plan => plan.sessionId === session.id && plan.taskId === run.taskId) ? browserToolDefinitions : [])];
|
||||
const owned = kind => [...this.store.core[kind].values()].filter(value => value.sessionId === session.id && value.taskId === run.taskId);
|
||||
const tabs = owned('browsing_tab').filter(tab => tab.status === 'open'), targets = owned('research_target'), engines = owned('engine_job');
|
||||
const browserResources = [...this.browserManager().builds(run.project).map(value => ({ kind: 'build', path: value })),
|
||||
...owned('browser_plan').map(value => ({ kind: 'plan', id: value.id }))];
|
||||
const registrations = registry => registry.state().registrations.filter(value => value.projectId === session.projectId)
|
||||
.map(({ id, enabled, revision, configurationRevision }) => ({ id, enabled, revision, configurationRevision }));
|
||||
const skills = run.worker ? [] : registrations(this.skillRegistry()), mcps = run.worker ? [] : registrations(this.mcpRegistry());
|
||||
const groups = [
|
||||
{ name: 'core', definitions: toolDefinitions, assembled: true },
|
||||
{ name: 'automatic', definitions: automaticToolDefinitions, assembled: unrestricted(config), reason: 'disabled_by_execution_mode' },
|
||||
{ name: 'task_plan', definitions: taskPlanToolDefinitions, assembled: true },
|
||||
{ name: 'file_results', definitions: fileResultToolDefinitions, assembled: true },
|
||||
{ name: 'browsing', definitions: browsingToolDefinitions, assembled: unrestricted(config) || !!tabs.length, reason: 'missing_current_resource', resources: tabs.map(({ id, revision }) => ({ id, revision })) },
|
||||
{ name: 'skills', definitions: skillToolDefinitions, assembled: !!skillCatalog?.entries.some(value => value.status === 'current'),
|
||||
reason: run.worker ? 'not_assembled_for_worker' : skills.length && !skills.some(value => value.enabled) ? 'disabled' : 'missing_current_resource',
|
||||
resources: [{ registrations: skills, entries: skillCatalog?.entries ?? [] }] },
|
||||
{ name: 'mcp', definitions: mcpToolDefinitions, assembled: !!mcpCatalog?.entries.length,
|
||||
reason: run.worker ? 'not_assembled_for_worker' : mcps.length && !mcps.some(value => value.enabled) ? 'disabled' : 'missing_current_resource',
|
||||
resources: [{ registrations: mcps, entries: mcpCatalog?.entries ?? [] }] },
|
||||
{ name: 'research', definitions: researchToolDefinitions, assembled: !!targets.length, reason: 'missing_current_resource', resources: targets.map(({ id }) => ({ id })) },
|
||||
{ name: 'engine', definitions: engineToolDefinitions, assembled: !!engines.length, reason: 'missing_current_resource', resources: engines.map(({ id }) => ({ id })) },
|
||||
{ name: 'browser_checks', definitions: browserToolDefinitions, assembled: !!browserResources.length, reason: 'missing_current_resource', resources: browserResources },
|
||||
];
|
||||
const availableTools = groups.filter(group => group.assembled).flatMap(group => group.definitions);
|
||||
const tools = openToolDefinitions(availableTools.filter(tool => unrestricted(config) || (!run.worker || WORKER_TOOLS.has(tool.function.name)) && taskToolAllowed(task, run.record, tool.function.name)), config);
|
||||
const toolSurface = observeToolSurface(groups, tools, { identity: { executionMode: config.executionMode ?? 'restricted', approvalMode: config.approvalMode ?? 'ask',
|
||||
purpose: run.record.purpose ?? 'execution', workerId: run.worker?.id ?? null },
|
||||
reason: name => run.worker && !WORKER_TOOLS.has(name) ? 'disabled_by_worker_contract'
|
||||
: !taskToolAllowed(task, run.record, name) ? 'disabled_by_task_contract' : 'disabled_by_execution_mode' });
|
||||
const projectMemory = await this.memoryManager().context(session, { redact: value => this.provider.redact(value) });
|
||||
signal.throwIfAborted();
|
||||
const planned = this.requestPlanner().prepare(session, run.record, config, { system: stablePrefix ? this.provider.redact(fixedContext) : context, contextTail: stablePrefix ? context : null, tools, stepId: stepRecord.id, projectMemory, skillCatalog, mcpCatalog,
|
||||
const planned = this.requestPlanner().prepare(session, run.record, config, { system: stablePrefix ? this.provider.redact(fixedContext) : context, contextTail: stablePrefix ? context : null, tools, toolSurface, stepId: stepRecord.id, projectMemory, skillCatalog, mcpCatalog,
|
||||
transportReservationTokens:run.worker?.engine?ENGINE_SEED_RESERVATION:0,engineStepOnly:!!run.worker?.engine });
|
||||
if (planned.record.archivedGroups && !projectionLogged) {
|
||||
projectionLogged = true; session.compactions++;
|
||||
@@ -484,7 +512,7 @@ export class Runtime {
|
||||
response = externalEngine
|
||||
? await this.engineRunner().complete(session, run, planned.messages, progressHandler, planned.record, tools)
|
||||
: await this.provider.complete(requestConfig, planned.messages, run.project, signal, progressHandler, planned.record, tools,
|
||||
{ ...(config.mode === 'demo' ? { demoHistory: session.providerMessages } : {}), maxBudgetAttempts:planned.record.maxBudgetAttempts,beforeDispatch:({previousFailure}={})=>checkModelDispatchBudget(this.store,session,run.record,requestConfig,planned.body,0,previousFailure)});
|
||||
{ ...(config.mode === 'demo' ? { demoHistory: providerHistory(session, run.record) } : {}), maxBudgetAttempts:planned.record.maxBudgetAttempts,beforeDispatch:({previousFailure}={})=>checkModelDispatchBudget(this.store,session,run.record,requestConfig,planned.body,0,previousFailure)});
|
||||
if (response.compatibility?.length && requestEvent) { requestEvent.compatibility = response.compatibility; this.store.save(session); }
|
||||
this.requestPlanner().finish(session, planned.record, { response, attempts: planned.record.requestAttempts });
|
||||
if (run.worker && !externalEngine && !responseAccounted) {
|
||||
@@ -518,7 +546,7 @@ export class Runtime {
|
||||
// The truncated assistant turn was never appended, so the conversation
|
||||
// stays valid. Feed the instruction to the model as a standalone turn
|
||||
// in the provider history, and mirror it to the visible chat log.
|
||||
session.providerMessages.push({ role: 'user', content: note });
|
||||
providerHistory(session, run.record).push({ role: 'user', content: note });
|
||||
this.store.event(session, { kind: 'context', runId: run.id, label: '模型输出被上限截断,已请求拆分后继续', phase: 'completed', contextPlanId: planned.record.id,
|
||||
output: '第 ' + run.record.outputTruncationRecoveries + '/' + OUTPUT_TRUNCATION_RECOVERY_LIMIT + ' 次恢复:上一响应 finish_reason=length,未执行任何工具,原响应与用量已保存。' });
|
||||
this.store.message(session, 'system', note);
|
||||
@@ -545,9 +573,9 @@ export class Runtime {
|
||||
: this.store.owned('artifact', args.artifact_id, session.id).bytes;
|
||||
return Math.max(0, Math.min(size - (args.offset ?? 0), args.limit ?? (call.function.name === 'read_artifact' ? 2000 : Infinity)));
|
||||
});
|
||||
const previousIds = new Set(session.providerMessages.flatMap(item => (item.tool_calls ?? []).map(call => call.id)));
|
||||
const previousIds = new Set(providerHistory(session, run.record).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);
|
||||
providerHistory(session, run.record).push(message);
|
||||
if (!responseAccounted) 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',
|
||||
@@ -621,7 +649,7 @@ export class Runtime {
|
||||
const invocation = [...this.store.core.tool.values()].findLast(row => row.runId === run.id && row.callId === call.id);
|
||||
if (invocation?.resultArtifactId) (stepRecord.progressToolIds ??= []).push(invocation.id);
|
||||
spendReadBudget(run.readBatchBudget, call, result);
|
||||
session.providerMessages.push({ role: 'tool', tool_call_id: call.id, content: JSON.stringify(result) });
|
||||
providerHistory(session, run.record).push({ role: 'tool', tool_call_id: call.id, content: JSON.stringify(result) });
|
||||
if (call.function.name === 'prepare_change_set' && result.status === 'awaiting_review') preparedSets.add(result.change_set_id);
|
||||
if (call.function.name === 'call_registered_mcp' && result.requires_verification) mcpReview = result.mcp_job_id;
|
||||
if (call.function.name === 'plan_delivery' && result.status === 'awaiting_review') {
|
||||
@@ -674,8 +702,8 @@ export class Runtime {
|
||||
this.store.save(session);
|
||||
} catch (error) {
|
||||
this.store.interruptPending(session, run.record);
|
||||
const repaired = repairToolPairs(session.providerMessages, callId => this.store.savedToolResult(session.id, callId));
|
||||
if (repaired.changed) session.providerMessages = repaired.messages;
|
||||
const history = providerHistory(session, run.record), repaired = repairToolPairs(history, callId => this.store.savedToolResult(session.id, callId));
|
||||
if (repaired.changed) history.splice(0, history.length, ...repaired.messages);
|
||||
const budget = error instanceof BudgetExceeded ? error : signal.reason instanceof BudgetExceeded ? signal.reason : null;
|
||||
if (signal.aborted || budget) {
|
||||
run.stopReason = budget?.reason ?? 'cancelled';
|
||||
|
||||
Reference in New Issue
Block a user