feat: wire optional progress reminders to actual requests and verified readback
This commit is contained in:
@@ -30,6 +30,7 @@ import { BRAND, OrvenMark } from './brand';
|
||||
import { WorkbenchTools } from './WorkbenchTools';
|
||||
import type { WorkbenchAction } from './WorkbenchTools';
|
||||
import { AppearancePanel } from './AppearancePanel';
|
||||
import { ProgressReminderSettings } from './ProgressReminders';
|
||||
import { Palette as PaletteIcon } from 'lucide-react';
|
||||
|
||||
const activeStates = ['running', 'awaiting_approval', 'stopping'];
|
||||
@@ -81,6 +82,7 @@ export default function App() {
|
||||
const [inspectorOpen, setInspectorOpen] = useState(false);
|
||||
const [toolsOpen, setToolsOpen] = useState(false);
|
||||
const [appearanceOpen, setAppearanceOpen] = useState(false);
|
||||
const [reminderSettingsOpen, setReminderSettingsOpen] = useState(false);
|
||||
const [narrow, setNarrow] = useState(() => window.innerWidth <= 940);
|
||||
const [viewportWidth,setViewportWidth]=useState(()=>window.innerWidth);
|
||||
const [mobile, setMobile] = useState(() => window.innerWidth <= 620);
|
||||
@@ -574,6 +576,7 @@ export default function App() {
|
||||
{ id: 'research', label: '机制研究与设计', description: '阅读已有研究报告与机制说明', group: '能力与研究', icon: BookOpenText, run: () => void openResearch() },
|
||||
{ id: 'models', label: '模型中心', description: '选择模型、管理连接和模型池', group: '设置与连接', icon: ModelServer, run: () => setModelCenterOpen(true) },
|
||||
{ id: 'appearance', label: '外观', description: '选择深青绿、雾蓝或鸢尾紫,自动记住你的偏好', group: '设置与连接', icon: PaletteIcon, run: () => setAppearanceOpen(true) },
|
||||
{ id: 'progress-reminders', label: '进展提醒', description: '可选的重复读取与参数错误建议,查看实际送达和回读', group: '设置与连接', icon: Activity, run: () => setReminderSettingsOpen(true) },
|
||||
{ id: 'diagnostics', label: '运行诊断', description: '检查连接、终端与最近错误', group: '设置与连接', icon: Activity, run: () => void openDiagnostics() },
|
||||
{ id: 'companion', label: '手机连接', description: '在手机上查看和接续电脑任务', group: '设置与连接', icon: Link2, run: () => setCompanionOpen(true) },
|
||||
...(desktop ? [{ id: 'desktop', label: '桌面宿主', description: '查看窗口、后台任务与本地宿主', group: '设置与连接', icon: SquareTerminal, run: () => setDesktopOpen(true) }] : []),
|
||||
@@ -661,6 +664,7 @@ export default function App() {
|
||||
</aside>
|
||||
{toolsOpen && <Modal title="工具箱" description="项目的上下文、能力和连接,都在这里。" onClose={() => setToolsOpen(false)}><WorkbenchTools actions={actions} onClose={() => setToolsOpen(false)} /></Modal>}
|
||||
{appearanceOpen && <Modal title="外观" description="选择适合你的工作台配色,切换后立即生效。" onClose={() => setAppearanceOpen(false)}><AppearancePanel /></Modal>}
|
||||
{reminderSettingsOpen && <Modal title="进展提醒" description="根据原工具结果提供可选建议,并核对后续进展。" onClose={() => setReminderSettingsOpen(false)}><ProgressReminderSettings /></Modal>}
|
||||
{installationOpen && <Modal title="版本与更新" description="核对本机版本、真实更新阶段与原始结果。" onClose={() => setInstallationOpen(false)}><InstallationStatus /></Modal>}
|
||||
{projectOpen && <Modal title="打开项目" description="选择这台电脑上的项目文件夹,或输入完整路径。" onClose={() => { if (!projectBusy) { setProjectOpen(false); setDirectoryPickerOpen(false); setProjectError(''); } }}><form onSubmit={event => { event.preventDefault(); if (!directoryPickerOpen) void openProject(); }}><label className="form-field">项目文件夹<input autoFocus value={projectInput} disabled={projectBusy} onChange={event => { setProjectInput(event.target.value); setProjectError(''); }} placeholder="C:\Projects\my-app" aria-label="项目文件夹路径" /></label>{projectError && <p className="local-files-error" role="alert">{projectError}</p>}{directoryPickerOpen && <ProjectDirectoryPicker initialPath={projectInput.trim()} onChoose={value => { setProjectInput(value); setProjectError(''); setDirectoryPickerOpen(false); }} onCancel={() => setDirectoryPickerOpen(false)} />}<div className="modal-actions"><button type="button" className="button secondary" disabled={pickingProject || projectBusy} onClick={() => desktop ? void pickDesktopProject() : setDirectoryPickerOpen(value => !value)}><FolderOpen size={15} />选择文件夹</button>{exampleId && <button type="button" className="button secondary" disabled={projectBusy} onClick={() => { chooseProject(exampleId); setProjectOpen(false); setDirectoryPickerOpen(false); }}>打开示例项目</button>}<button type="submit" className="button primary" disabled={!projectInput.trim() || projectBusy || directoryPickerOpen}>{projectBusy ? <LoaderCircle className="spin" size={15} /> : <FolderOpen size={15} />}{projectBusy ? '正在打开…' : '打开项目'}</button></div></form></Modal>}
|
||||
{companionOpen && <Modal title="手机连接" description="指定项目和权限,连接到同一个Windows执行宿主。" onClose={() => setCompanionOpen(false)} wide><CompanionPanel projects={projects} selectedProjectId={selectedProject?.id ?? ''} /></Modal>}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
.reminder-settings { padding: 4px 2px 12px; font-size: 14px; line-height: 1.7; }
|
||||
.reminder-settings p { margin: 14px 0; }
|
||||
.reminder-toggle { display: flex; align-items: center; justify-content: space-between; gap: 20px; padding: 12px 0 18px; border-bottom: 1px solid var(--orven-line); cursor: pointer; }
|
||||
.reminder-toggle span { display: grid; gap: 4px; }
|
||||
.reminder-toggle strong { font-size: 15px; }
|
||||
.reminder-toggle small { font-size: 12px; color: var(--orven-muted); }
|
||||
.reminder-toggle input { width: 21px; height: 21px; flex: 0 0 auto; accent-color: var(--orven-accent); cursor: pointer; }
|
||||
.reminder-readback { margin-top: 16px; padding-top: 12px; border-top: 1px solid var(--orven-line); }
|
||||
.reminder-readback h4 { margin: 0 0 8px; font-size: 13px; }
|
||||
.reminder-evidence { display: flex; flex-wrap: wrap; gap: 4px 12px; }
|
||||
@media (max-width: 620px) { .reminder-readback button, .reminder-settings button { min-height: 44px; } .reminder-toggle { min-height: 60px; } }
|
||||
@@ -0,0 +1,73 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { LoaderCircle } from 'lucide-react';
|
||||
import { api } from './api';
|
||||
import type { ReminderInspection, Run } from './types';
|
||||
import './ProgressReminders.css';
|
||||
|
||||
export function ProgressReminderSettings() {
|
||||
const [enabled, setEnabled] = useState<boolean | null>(null), [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState(''), [notice, setNotice] = useState(''), [reload, setReload] = useState(0);
|
||||
useEffect(() => {
|
||||
let alive = true; setError(''); setEnabled(null);
|
||||
api<{ enabled: boolean }>('/progress-reminders/settings').then(value => { if (alive) setEnabled(value.enabled); })
|
||||
.catch(() => { if (alive) setError('暂时无法读取提醒设置,请重试。'); });
|
||||
return () => { alive = false; };
|
||||
}, [reload]);
|
||||
async function toggle(next: boolean) {
|
||||
setSaving(true); setError(''); setNotice('');
|
||||
try {
|
||||
const saved = await api<{ enabled: boolean }>('/progress-reminders/settings', { enabled: next });
|
||||
setEnabled(saved.enabled); setNotice(saved.enabled ? '已开启,并保存为后续运行的偏好。' : '已关闭,后续请求不再附加建议。');
|
||||
} catch { setError('设置未保存,请重试。原选择仍然保留。'); }
|
||||
finally { setSaving(false); }
|
||||
}
|
||||
return <div className="reminder-settings">
|
||||
<label className="reminder-toggle"><span><strong>开启进展提醒</strong><small>默认关闭。你的选择会自动保存。</small></span>
|
||||
{enabled === null ? <LoaderCircle size={18} className="spin" aria-label="正在读取设置" />
|
||||
: <input type="checkbox" role="switch" aria-label="开启进展提醒" checked={enabled} disabled={saving} onChange={event => void toggle(event.target.checked)} />}</label>
|
||||
<p>仅在文件任务连续重复读取相同内容,或连续出现相同参数错误时,附加可选建议。正常分页、研究和等待检查继续按原任务进行。</p>
|
||||
<p>在任务记录中查看建议随哪次请求发出、后续是否出现对应工具结果。回复“明白”不会被记为解决。</p>
|
||||
<p className="record-footnote">本设置不改变操作权限、模型额度或历史传递。当前执行中的请求保留原记录;外部引擎与压缩历史不附加建议。</p>
|
||||
{notice && <p role="status">{notice}</p>}
|
||||
{saving && <p role="status">正在保存…</p>}
|
||||
{error && <div role="alert"><p>{error}</p>{enabled === null && <button type="button" className="text-button" onClick={() => setReload(value => value + 1)}>重新读取</button>}</div>}
|
||||
</div>;
|
||||
}
|
||||
|
||||
const labels: Record<string, string> = { pending: '待发送', delivered: '已随请求发出', resolved: '已观察到进展', expired: '已过期' };
|
||||
const reasons: Record<string, string> = { disabled: '已关闭提醒', cancelled: '运行已取消', run_finished: '运行已结束', ttl: '建议已过期',
|
||||
research: '保留只读研究', waiting: '等待所属操作', user_boundary: '用户要求已变化', new_failure: '出现新的失败证据',
|
||||
ineffective: '重复建议未见效果,已停止附加', tool_unavailable_or_advice_too_large: '本轮不再适用' };
|
||||
|
||||
export function ReminderReadback({ sessionId, run, openArtifact }: { sessionId: string; run: Run; openArtifact: (id: string) => void }) {
|
||||
const [view, setView] = useState<ReminderInspection | null>(null), [error, setError] = useState(''), [reload, setReload] = useState(0);
|
||||
const recorded = !!run.progressReminders || !!run.progressReminderError;
|
||||
useEffect(() => {
|
||||
let alive = true; setView(null); setError('');
|
||||
if (recorded) api<ReminderInspection>('/sessions/' + sessionId + '/progress-reminders?run=' + run.id)
|
||||
.then(value => { if (alive) setView(value); }).catch(() => { if (alive) setError('暂时无法核对提醒记录。'); });
|
||||
return () => { alive = false; };
|
||||
}, [sessionId, run.id, run.progressReminderReceiptId, run.progressReminderError?.phase, recorded, reload]);
|
||||
if (!recorded) return null;
|
||||
return <section className="reminder-readback" aria-label="提醒与回读">
|
||||
<h4>提醒与回读</h4>
|
||||
{!view && !error && <p role="status">正在核对原始记录…</p>}
|
||||
{error && <p role="alert">{error}<button type="button" className="text-button" onClick={() => setReload(value => value + 1)}>重新核对</button></p>}
|
||||
{view && !view.evidenceVerified && <p role="alert">提醒依据暂时无法核对。原任务和执行结果保留。</p>}
|
||||
{view?.evidenceVerified && <>
|
||||
{view.error && <p className="record-footnote">部分提醒未能记录,原任务继续执行。</p>}
|
||||
{!view.items.length && <p className="record-footnote">本次运行没有生成建议。</p>}
|
||||
<ol>{view.items.map(item => <li key={item.key}>
|
||||
<strong>{item.category === 'repeated_read' ? '重复读取建议' : '参数错误建议'} · {labels[item.status] ?? item.status}</strong>
|
||||
<p>{item.deliveries.length ? `已随 ${item.deliveries.length} 次请求发出` : '尚未随请求发出'}{item.exitReason ? ` · ${reasons[item.exitReason] ?? item.exitReason}` : ''}</p>
|
||||
{item.resolution && <p>{item.resolution.relation === 'naturally_resolved' ? '发送前已自然出现对应工具结果。' : '发送后已出现对应工具结果,因果关系未证实。'}{item.resolution.kind === 'new_read_range' ? '已取得新的读取区间。' : '原参数错误工具已返回成功结果。'}</p>}
|
||||
<div className="reminder-evidence">{item.source.map((ref, index) => <button type="button" className="text-button" key={ref.artifactId} onClick={() => openArtifact(ref.artifactId)}>原观察 {index + 1}</button>)}
|
||||
{item.deliveries.map((delivery, index) => <button type="button" className="text-button" key={delivery.requestId} onClick={() => openArtifact(delivery.requestArtifactId)}>实际请求 {index + 1}</button>)}
|
||||
{item.resolution && <button type="button" className="text-button" onClick={() => openArtifact(item.resolution!.source.artifactId)}>回读依据</button>}
|
||||
</div>
|
||||
</li>)}</ol>
|
||||
{view.receiptArtifactId && <button type="button" className="text-button" onClick={() => openArtifact(view.receiptArtifactId!)}>查看提醒原收据</button>}
|
||||
<p className="record-footnote">工具进展与业务完成分别核对;送达记录不代表模型收到、采纳或节省了 tokens。</p>
|
||||
</>}
|
||||
</section>;
|
||||
}
|
||||
@@ -120,7 +120,7 @@ export function TaskPanel({ project, session, onSession, onError, busy, onWorksp
|
||||
<dt>本次预算</dt><dd>{run.budget?.maxTokens === 0 ? 'tokens 不限' : number(run.budget?.maxTokens) + ' tokens'} · {run.budget?.maxDurationMs === 0 ? '时长不限' : Math.round((run.budget?.maxDurationMs ?? 0) / 60000) + ' 分钟'} · {run.budget?.maxSteps === 0 ? '轮次不限' : run.budget?.maxSteps + ' 轮'}</dd><dt>任务累计</dt><dd>{number(execution?.accountedTaskTokens)} / {task.budget.maxTokens === 0 ? '不限' : number(task.budget.maxTokens)} tokens</dd>
|
||||
</dl>{run.stopReason && <p className="run-stop">{stopReasons[run.stopReason] || run.stopReason}</p>}
|
||||
<p className="record-footnote">用量按请求尝试累计,包含失败响应已报告的 tokens;未报告的请求单独估算。历史缺失不补造,tokens 不等于费用。</p>
|
||||
<TurnProgress run={run} openArtifact={openArtifact} />
|
||||
<TurnProgress sessionId={session.id} run={run} openArtifact={openArtifact} />
|
||||
</> : <p className="record-empty"><LoaderCircle size={14} className="spin" />正在读取运行记录</p>}
|
||||
</section>}
|
||||
{run && <RequestContextPanel session={session} runId={run.id} onError={onError} openArtifact={openArtifact} />}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import type { Run } from './types';
|
||||
import { ReminderReadback } from './ProgressReminders';
|
||||
const labels: Record<string, string> = { baseline: '本次运行基线', waiting: '等待所属操作', evidence_growth: '新增外显证据', new_failure_evidence: '新增失败证据',
|
||||
user_boundary: '用户边界变化', repeated_failure_candidate: '重复失败候选', repeated_read_candidate: '重复读取候选', no_observed_change: '未见新外显事实', unknown_bounded: '观察容量已满,保留未知' };
|
||||
const failureLabels: Record<string, string> = { invalid_input: '参数无效', permission: '权限或审批拒绝', requires_verification: '结果待核对', network: '网络连接', service: '上游服务',
|
||||
authentication: '身份验证', rate_limit: '请求限流', quota: '服务额度', tool_or_environment: '工具或环境', unknown: '尚未分类' };
|
||||
export function TurnProgress({ run, openArtifact }: { run: Run; openArtifact: (id: string) => void }) {
|
||||
if (!run.progressShadow && !run.progressShadowError) return null;
|
||||
export function TurnProgress({ sessionId, run, openArtifact }: { sessionId: string; run: Run; openArtifact: (id: string) => void }) {
|
||||
if (!run.progressShadow && !run.progressShadowError && !run.progressReminders && !run.progressReminderError) return null;
|
||||
const shadow = run.progressShadow;
|
||||
return <details className="turn-progress" aria-label="单轮观察">
|
||||
<summary>单轮观察 · 仅记录{shadow ? ` · 已保留 ${shadow.turns.filter(row => row.phase === 'settled').length} 轮` : ''}</summary>
|
||||
@@ -21,5 +22,6 @@ export function TurnProgress({ run, openArtifact }: { run: Run; openArtifact: (i
|
||||
{!!turn.waiting.length && <p>等待 {turn.waiting.map(row => ({ approval: '审批', check_job: '检查作业', review: '审查' }[row.kind] ?? row.kind)).join('、')}</p>}
|
||||
{run.progressShadowArtifactIds?.[index] && <button className="text-button" onClick={() => openArtifact(run.progressShadowArtifactIds![index])}>查看原观察收据</button>}
|
||||
</li>)}</ol>
|
||||
<ReminderReadback key={sessionId + '/' + run.id} sessionId={sessionId} run={run} openArtifact={openArtifact} />
|
||||
</details>;
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ export interface Config {
|
||||
executionMode?: 'unrestricted' | 'restricted';
|
||||
capacityMode?: 'passthrough' | 'model' | 'manual';
|
||||
historyPolicy?: 'preserve' | 'compact';
|
||||
progressRemindersEnabled?: boolean;
|
||||
maxRunDurationMs: number; maxRunTokens: number; maxTaskTokens: number;
|
||||
modelResponseTimeoutMs?: number; modelStreamIdleTimeoutMs?: number;
|
||||
}
|
||||
@@ -152,6 +153,14 @@ export interface TurnObservation {
|
||||
waiting: { kind: string; id: string }[];
|
||||
}
|
||||
export interface Run { progressShadow?: { mode: 'shadow'; observations: number; truncated: boolean; turns: TurnObservation[] }; progressShadowArtifactIds?: string[]; progressShadowError?: { kind: string; phase: string } }
|
||||
export interface ReminderSource { artifactId: string; sha256: string; ordinal: number }
|
||||
export interface ProgressReminder { key: string; category: string; status: string; createdAt: number; expiresAt: number; source: ReminderSource[];
|
||||
toolNames: string[]; expected: { kind: string }; exitReason?: string;
|
||||
deliveries: { requestId: string; requestArtifactId: string; requestSha256: string; dispatchedAt: number }[];
|
||||
resolution?: { source: ReminderSource; kind: string; relation: string; causality: string } }
|
||||
export interface ReminderInspection { enabled: boolean; recorded: boolean; evidenceVerified: boolean; receiptArtifactId: string | null;
|
||||
items: ProgressReminder[]; error: { kind: string; phase: string } | null }
|
||||
export interface Run { progressReminders?: { enabled: boolean; items: ProgressReminder[] }; progressReminderReceiptId?: string; progressReminderError?: { kind: string; phase: string } }
|
||||
export interface RunBrief { purpose?: 'execution' | 'diagnostic'; source?: string; taskStatusBefore?: string; consumption?: ModelConsumption[] }
|
||||
export interface Run { question?: string; diagnosticContext?: { artifactId: string; sha256: string; originalRunId: string | null } }
|
||||
export interface DiagnosticContext {
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
import { planHash } from '../../shared/contracts/task-plans.mjs';
|
||||
import { requestHistory, requestVariants } from '../../shared/contracts/model-request.mjs';
|
||||
import { verifyTurnProgressReceipt } from './turn-progress-recorder.mjs';
|
||||
import { observeReminders, selectReminder, recordReminderDispatch } from './reminder-queue.mjs';
|
||||
|
||||
const scopeOf = run => ({ projectId: run.projectId, sessionId: run.sessionId, taskId: run.taskId, runId: run.id });
|
||||
const owned = (row, scope) => row && row.projectId === scope.projectId && row.sessionId === scope.sessionId && row.taskId === scope.taskId && row.runId === scope.runId;
|
||||
const current = (session, run) => session.id === run.sessionId && session.projectId === run.projectId && session.taskId === run.taskId && session.runId === run.id;
|
||||
|
||||
export function verifyReminderMessage(store, session, plan, body) {
|
||||
const ref = plan.progressReminder;
|
||||
if (!ref) return null;
|
||||
const scope = { projectId: plan.projectId, sessionId: plan.sessionId, taskId: plan.taskId, runId: plan.runId };
|
||||
const artifact = store.owned('artifact', ref.artifactId, session.id);
|
||||
if (!owned(artifact, scope) || artifact.kind !== 'progress-reminder-message' || artifact.sha256 !== ref.sha256) throw new Error('提醒原文来源不一致。');
|
||||
const message = JSON.parse(store.artifactStore.read(artifact));
|
||||
if (planHash(message.scope) !== planHash(scope) || message.key !== ref.key || planHash(message.content) !== message.sha256) throw new Error('提醒原文归属不一致。');
|
||||
for (const variant of requestVariants(body)) {
|
||||
const matches = requestHistory(variant).filter(row => ['user', 'system'].includes(row.role) && typeof row.content === 'string' && row.content.includes(message.content));
|
||||
const tools = (variant.tools ?? []).map(tool => tool.function?.name ?? tool.name);
|
||||
if (matches.length !== 1 || message.tools.some(name => !tools.includes(name))) throw new Error('提醒与实际请求正文或工具不一致。');
|
||||
}
|
||||
return message;
|
||||
}
|
||||
|
||||
// No permissions, retries or stops are delegated to this observer. All entry
|
||||
// points isolate their own failures and leave the original execution intact.
|
||||
export class ReminderManager {
|
||||
constructor(store) { this.store = store; }
|
||||
error(session, run, phase) {
|
||||
if (!current(session, run)) return;
|
||||
run.progressReminderError = { kind: 'reminder_unavailable', phase };
|
||||
try { this.store.save(session, { type: 'run.reminder_unavailable', detail: { runId: run.id, phase } }); } catch { /* Original execution owns persistence failures. */ }
|
||||
}
|
||||
verifiedState(session, run) {
|
||||
if (!run.progressReminders) return null;
|
||||
const artifact = this.store.owned('artifact', run.progressReminderReceiptId, session.id);
|
||||
if (!owned(artifact, scopeOf(run)) || artifact.kind !== 'progress-reminder-queue') throw new Error('提醒队列收据归属不一致。');
|
||||
const receipt = JSON.parse(this.store.artifactStore.read(artifact));
|
||||
if (planHash(receipt.state) !== planHash(run.progressReminders) || planHash(receipt.state.scope) !== planHash(scopeOf(run))) throw new Error('提醒队列与原收据不一致。');
|
||||
return run.progressReminders;
|
||||
}
|
||||
save(session, run, state, phase) {
|
||||
if (planHash(state) === planHash(run.progressReminders ?? null)) return;
|
||||
const artifact = this.store.artifactStore.write(session, run, { schemaVersion: 1, phase, state }, { kind: 'progress-reminder-queue' });
|
||||
this.store.core.artifact.set(artifact.id, artifact);
|
||||
run.progressReminders = state; run.progressReminderReceiptId = artifact.id;
|
||||
this.store.save(session, { type: 'run.progress_reminder', detail: { runId: run.id, phase, artifactId: artifact.id } });
|
||||
}
|
||||
observe(session, run, { endReason = null } = {}) {
|
||||
if (!current(session, run) || (!this.store.config.progressRemindersEnabled && !run.progressReminders)) return;
|
||||
try {
|
||||
const state = this.verifiedState(session, run), id = run.progressShadowArtifactIds?.at(-1);
|
||||
let receipt = null;
|
||||
if (id && !endReason && state?.lastArtifactId !== id) {
|
||||
const verified = verifyTurnProgressReceipt(this.store, session, run, id);
|
||||
if (planHash(verified.observation) !== planHash(run.progressShadow?.turns.at(-1))) throw new Error('提醒观察与原收据不一致。');
|
||||
receipt = { ...verified, ref: { artifactId: id, sha256: verified.artifact.sha256, ordinal: run.progressShadow.observations } };
|
||||
}
|
||||
const task = this.store.core.task.get(run.taskId);
|
||||
// Only explicit file work is eligible for read nudges. General analysis,
|
||||
// research and diagnostics remain valid read-only work without prompting.
|
||||
const research = run.purpose === 'diagnostic' || !!run.workerId || task?.contract?.kind !== 'file';
|
||||
const next = observeReminders(state, { scope: scopeOf(run), enabled: this.store.config.progressRemindersEnabled,
|
||||
at: Date.now(), receipt, research, endReason });
|
||||
this.save(session, run, next, endReason ?? 'observation');
|
||||
} catch { this.error(session, run, 'observation'); }
|
||||
}
|
||||
prepare(session, run, toolSurface) {
|
||||
if (!current(session, run) || run.purpose === 'diagnostic' || run.workerId || (!this.store.config.progressRemindersEnabled && !run.progressReminders)) return null;
|
||||
try {
|
||||
const state = this.verifiedState(session, run);
|
||||
// Check source integrity again at use, including receipts retained before
|
||||
// B's display window. Never trust the mutable in-memory projection alone.
|
||||
for (const item of state?.items.filter(row => ['pending', 'delivered'].includes(row.status)) ?? [])
|
||||
for (const ref of item.source) this.verifySource(session, run, ref);
|
||||
const selected = selectReminder(state, { scope: scopeOf(run), enabled: this.store.config.progressRemindersEnabled,
|
||||
at: Date.now(), visibleTools: toolSurface.entries.filter(row => row.visible).map(row => row.name) });
|
||||
this.save(session, run, selected.state, 'selection');
|
||||
if (!selected.message) return null;
|
||||
const artifact = this.store.artifactStore.write(session, run, selected.message, { kind: 'progress-reminder-message' });
|
||||
this.store.core.artifact.set(artifact.id, artifact);
|
||||
return { message: selected.message, ref: { key: selected.message.key, artifactId: artifact.id, sha256: artifact.sha256 } };
|
||||
} catch { this.error(session, run, 'selection'); return null; }
|
||||
}
|
||||
verifySource(session, run, ref) {
|
||||
const verified = verifyTurnProgressReceipt(this.store, session, run, ref.artifactId);
|
||||
if (verified.artifact.sha256 !== ref.sha256) throw new Error('提醒依据SHA变化。');
|
||||
return verified;
|
||||
}
|
||||
requestEvidence(session, run, plan) {
|
||||
const scope = scopeOf(run), frozenArtifact = this.store.owned('artifact', plan.artifactId, session.id);
|
||||
if (!owned(plan, scope) || !owned(frozenArtifact, scope) || frozenArtifact.kind !== 'context-plan') throw new Error('提醒请求计划归属不一致。');
|
||||
const frozen = JSON.parse(this.store.artifactStore.read(frozenArtifact));
|
||||
for (const key of ['id', 'projectId', 'sessionId', 'taskId', 'runId', 'requestArtifactId', 'requestSha256', 'progressReminder'])
|
||||
if (planHash(frozen[key] ?? null) !== planHash(plan[key] ?? null)) throw new Error('提醒请求与发送前封存不一致。');
|
||||
const artifact = this.store.owned('artifact', plan.requestArtifactId, session.id);
|
||||
if (!owned(artifact, scope) || artifact.kind !== 'model-request' || artifact.sha256 !== plan.requestSha256) throw new Error('提醒请求原文变化。');
|
||||
return JSON.parse(this.store.artifactStore.read(artifact));
|
||||
}
|
||||
dispatch(session, run, plan, submission) {
|
||||
if (!plan.progressReminder || !current(session, run) || session.status === 'stopping') return;
|
||||
try {
|
||||
const state = this.verifiedState(session, run);
|
||||
const body = this.requestEvidence(session, run, plan);
|
||||
const message = verifyReminderMessage(this.store, session, plan, body);
|
||||
if (!requestVariants(body).some(variant => planHash(variant) === submission.wireRequestSha256)) throw new Error('提醒实际线路请求与原计划不一致。');
|
||||
const next = recordReminderDispatch(state, { scope: scopeOf(run), at: Date.now(), message, requestId: plan.id, requestSha256: plan.requestSha256,
|
||||
attemptId: submission.attemptId, wireRequestSha256: submission.wireRequestSha256 });
|
||||
// Provider calls this only after submitting fetch, before awaiting the
|
||||
// response. A later disable/cancel cannot erase that dispatch fact.
|
||||
if (next.items.find(row => row.key === message.key)?.deliveries.some(row => row.requestId === plan.id)) {
|
||||
plan.progressReminderDispatches ??= [];
|
||||
if (!plan.progressReminderDispatches.some(row => row.attemptId === submission.attemptId))
|
||||
plan.progressReminderDispatches.push({ ...submission, recordedAt: new Date().toISOString() });
|
||||
}
|
||||
this.save(session, run, next, 'dispatch');
|
||||
} catch { this.error(session, run, 'dispatch'); }
|
||||
}
|
||||
inspect(session, run) {
|
||||
const view = { schemaVersion: 1, enabled: this.store.config.progressRemindersEnabled === true, recorded: !!run.progressReminders,
|
||||
evidenceVerified: false, receiptArtifactId: run.progressReminderReceiptId ?? null, items: [], error: run.progressReminderError ?? null };
|
||||
if (!view.recorded) { view.evidenceVerified = true; return view; }
|
||||
try {
|
||||
const state = this.verifiedState(session, run);
|
||||
for (const item of state.items) {
|
||||
for (const ref of [...item.source, ...(item.resolution ? [item.resolution.source] : [])]) this.verifySource(session, run, ref);
|
||||
for (const delivered of item.deliveries) {
|
||||
const plan = this.store.owned('context_plan', delivered.requestId, session.id);
|
||||
if (!owned(plan, scopeOf(run)) || plan.requestSha256 !== delivered.requestSha256 || !plan.progressReminderDispatches?.length) throw new Error('提醒送达请求未核对。');
|
||||
const body = this.requestEvidence(session, run, plan);
|
||||
const message = verifyReminderMessage(this.store, session, plan, body);
|
||||
if (message.key !== item.key || message.sha256 !== delivered.messageSha256) throw new Error('提醒送达原文变化。');
|
||||
const variants = requestVariants(body).map(planHash);
|
||||
if (!delivered.attempts?.length || delivered.attempts.some(attempt => !variants.includes(attempt.wireRequestSha256)
|
||||
|| !plan.progressReminderDispatches.some(row => row.attemptId === attempt.attemptId && row.wireRequestSha256 === attempt.wireRequestSha256))) throw new Error('提醒实际线路送达未核对。');
|
||||
}
|
||||
}
|
||||
view.items = structuredClone(state.items).map(item => ({ ...item, deliveries: item.deliveries.map(row => ({ ...row,
|
||||
requestArtifactId: this.store.core.context_plan.get(row.requestId).requestArtifactId })) }));
|
||||
view.evidenceVerified = true;
|
||||
} catch { view.error = { kind: 'reminder_evidence_unverified', phase: 'readback' }; }
|
||||
return view;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
const hash = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
||||
const hash = value => createHash('sha256').update(typeof value === 'string' ? value : JSON.stringify(value)).digest('hex');
|
||||
const sha = value => /^[a-f0-9]{64}$/.test(value ?? '');
|
||||
const active = item => ['pending', 'delivered'].includes(item.status);
|
||||
const same = (a, b) => hash(a) === hash(b);
|
||||
@@ -114,14 +114,21 @@ export function selectReminder(previous, { scope, enabled = false, at, visibleTo
|
||||
|
||||
// Dispatch means included in a real submitted request. It does not assert that
|
||||
// an upstream received it, the model adopted it, or the advice caused progress.
|
||||
export function recordReminderDispatch(previous, { scope, at, message, requestId, requestSha256 }) {
|
||||
export function recordReminderDispatch(previous, { scope, at, message, requestId, requestSha256, attemptId = null, wireRequestSha256 = null }) {
|
||||
const state = queue(previous, scope, previous?.enabled, at), item = state.items.find(row => row.key === message?.key);
|
||||
if (!same(message?.scope, state.scope) || !sha(requestSha256) || typeof requestId !== 'string' || !requestId) throw new Error('Reminder request ownership is invalid.');
|
||||
if (!state.enabled || !item || !active(item)) return state;
|
||||
const expected = messageFor(state, item, message.tools ?? []);
|
||||
if (!expected || !same(expected, message)) throw new Error('Reminder dispatch differs from selected advice.');
|
||||
if (item.deliveries.some(row => row.requestId === requestId)) return state;
|
||||
item.deliveries.push({ requestId, requestSha256, messageSha256: message.sha256, ordinal: state.lastOrdinal, dispatchedAt: at });
|
||||
if (attemptId !== null && (typeof attemptId !== 'string' || !attemptId || !sha(wireRequestSha256))) throw new Error('Reminder wire attempt is invalid.');
|
||||
let delivery = item.deliveries.find(row => row.requestId === requestId);
|
||||
if (!delivery) {
|
||||
delivery = { requestId, requestSha256, messageSha256: message.sha256, ordinal: state.lastOrdinal, dispatchedAt: at };
|
||||
item.deliveries.push(delivery);
|
||||
}
|
||||
if (attemptId && !delivery.attempts?.some(row => row.attemptId === attemptId)) {
|
||||
delivery.attempts ??= []; delivery.attempts.push({ attemptId, wireRequestSha256, dispatchedAt: at });
|
||||
}
|
||||
item.status = 'delivered';
|
||||
return state;
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import { prefixAudit } from './prefix-audit.mjs';
|
||||
import { observeRequest, providerHistory, requestPath } from './request-observation.mjs';
|
||||
import { verifyToolSurface } from './tool-surface.mjs';
|
||||
import { isPassthrough } from '../../shared/contracts/model-capacity.mjs';
|
||||
import { verifyReminderMessage } from './reminder-manager.mjs';
|
||||
|
||||
const hash = value => createHash('sha256').update(typeof value === 'string' ? value : JSON.stringify(value), 'utf8').digest('hex');
|
||||
const PLACEHOLDER_ID = '00000000-0000-0000-0000-000000000000';
|
||||
@@ -189,7 +190,7 @@ export class RequestPlanner {
|
||||
return { artifact_id: artifact.id, sha256: artifact.sha256, group_sha256: group.sha256, bytes: Buffer.byteLength(text, 'utf8'), chunks: chunks.length };
|
||||
}
|
||||
|
||||
prepare(session, run, config, { system, contextTail = null, tools, toolSurface = null, stepId, projectMemory = null, skillCatalog = null, mcpCatalog = null, transportReservationTokens = 0,engineStepOnly=false }) {
|
||||
prepare(session, run, config, { system, contextTail = null, tools, toolSurface = null, stepId, projectMemory = null, skillCatalog = null, mcpCatalog = null, progressReminder = null, transportReservationTokens = 0,engineStepOnly=false }) {
|
||||
const task = this.store.owned('task', run.taskId, session.id);
|
||||
this.store.owned('run', run.id, session.id);
|
||||
const history = providerHistory(session, run);
|
||||
@@ -406,6 +407,7 @@ export class RequestPlanner {
|
||||
requestArtifactId: requestArtifact.id,
|
||||
prefixAudit: prefix,
|
||||
requestObservation: observation,
|
||||
...(progressReminder ? { progressReminder } : {}),
|
||||
...(preserve ? { contextLayout: 'stable-prefix-1', historyPolicy: 'preserve', contextTailArtifactId: tailArtifact?.id ?? null, contextTailSha256: tailArtifact?.sha256 ?? null } : {}),
|
||||
...(tokenReservation?{tokenReservation,maxBudgetAttempts:Math.min(8,Math.floor(credit/tokenReservation.reservedTokens))}:{engineStepOnly:true}),
|
||||
estimateMethod: metrics.estimateMethod, beforeInputTokens: before.estimatedInputTokens, beforeBytes: before.bytes, budget,
|
||||
@@ -474,9 +476,10 @@ export function verifyPlanEvidence(store, session, plan, cache = new Map()) {
|
||||
historyGroups(requestHistory(body));
|
||||
for (const variant of requestVariants(body)) historyGroups(requestHistory(variant));
|
||||
const frozen = JSON.parse(store.artifactStore.read(get(plan.artifactId, 'context-plan')));
|
||||
for (const key of ['contextLayout', 'historyPolicy', 'contextTailArtifactId', 'contextTailSha256', 'prefixAudit', 'requestObservation']) {
|
||||
for (const key of ['contextLayout', 'historyPolicy', 'contextTailArtifactId', 'contextTailSha256', 'prefixAudit', 'requestObservation', 'progressReminder']) {
|
||||
if (JSON.stringify(frozen[key] ?? null) !== JSON.stringify(plan[key] ?? null)) throw new Error('前缀或历史策略与发送前封存不匹配。');
|
||||
}
|
||||
verifyReminderMessage(store, session, plan, body);
|
||||
if (plan.requestObservation) {
|
||||
const run = store.owned('run', plan.runId, session.id);
|
||||
const expected = observeRequest(store, session, run, providerHistory(session, run).slice(0, plan.originalMessages), plan.requestObservation.toolSurface);
|
||||
|
||||
@@ -11,6 +11,7 @@ import { currentBrowserVerification, verifyBrowserJob } from './browser/browser-
|
||||
import { TaskPlanManager } from './tasks/task-plan-manager.mjs';
|
||||
import { RequirementReview } from './tasks/requirement-review.mjs';
|
||||
import { inspectTurnProgress } from './context/turn-progress-recorder.mjs';
|
||||
import { ReminderManager } from './context/reminder-manager.mjs';
|
||||
import { FileResults } from './tasks/file-results.mjs';
|
||||
import { taskContract } from '../shared/contracts/task-control.mjs';
|
||||
import { modelIdentityLabel } from '../shared/contracts/model-identity.mjs';
|
||||
@@ -150,6 +151,8 @@ export class DeliveryReporter {
|
||||
: researchScope && !check ? contract.checks === 'skip' ? 'scope_verified' : 'research_verified'
|
||||
: hasFileScope && !fileDelivery.newChanges ? 'existing_verified' : hasFileScope && contract.checks === 'skip' ? 'files_delivered'
|
||||
: hasCommit ? 'verified_committed' : 'verified_uncommitted';
|
||||
const reminders = [...this.store.core.run.values()].filter(value => value.sessionId === session.id && value.taskId === taskId && (value.progressReminders || value.progressReminderError))
|
||||
.map(value => ({ runId: value.id, ...new ReminderManager(this.store).inspect(session, value) }));
|
||||
const report = {
|
||||
schemaVersion: 1, kind: 'engineering-delivery', generatedAt: new Date().toISOString(), status, statusLabel: labels[status],
|
||||
lifecycle: { phase: run.finishedAt ? 'final' : 'snapshot', runStatus: run.status, finishedAt: run.finishedAt ?? null },
|
||||
@@ -164,6 +167,7 @@ export class DeliveryReporter {
|
||||
context: inspectDiagnosticContext(this.store, session, value) })),
|
||||
turnObservations: [...this.store.core.run.values()].filter(value => value.sessionId === session.id && value.taskId === taskId)
|
||||
.map(value => ({ runId: value.id, ...inspectTurnProgress(this.store, session, value) })),
|
||||
...(reminders.length ? { reminderObservations: reminders } : {}),
|
||||
fileResults, fileDelivery,
|
||||
checkPolicy: contract.checks === 'skip' ? 'not_requested' : contract.checks,
|
||||
gitOutcome: { status: hasCommit ? 'committed' : terminalGit.length ? 'observed_unverified' : !fileDelivery.newChanges && hasFileScope ? 'no_new_changes' : 'uncommitted',
|
||||
@@ -269,6 +273,16 @@ export function renderDeliveryMarkdown(report) {
|
||||
turn.classification, turn.delta.read_characters, turn.delta.repeated_reads, turn.delta.new_failures + ' / ' + turn.delta.repeated_failures,
|
||||
run.evidence_verified ? '原字节已核对' : run.error].map(escapeCell).join(' | ') + ' |');
|
||||
}
|
||||
if (report.reminderObservations?.length) {
|
||||
lines.push('', '## 提醒与实际回读', '', '随请求发出与后续工具进展分别记录;模型收到、采纳和收益因果未证实,不作为业务交付通过依据。', '',
|
||||
'| Run / 建议 | 状态 | 实际发送请求 | 回读依据 | 原收据核对 |', '| --- | --- | --- | --- | --- |');
|
||||
for (const run of report.reminderObservations) {
|
||||
if (run.error) lines.push('', '提醒观察部分不可用;原任务结果保留。');
|
||||
for (const item of run.items) lines.push('| ' + [run.runId + ' / ' + item.category, item.status,
|
||||
item.deliveries.map(row => row.requestId).join(', ') || '未发送', item.resolution?.source.artifactId ?? '尚未观察到对应结果',
|
||||
run.evidenceVerified ? '原字节已核对' : '待核对'].map(escapeCell).join(' | ') + ' |');
|
||||
}
|
||||
}
|
||||
if (report.taskPlan?.configured) {
|
||||
lines.push('', '## 执行计划与实际核验', '', '计划:' + (report.taskPlan.plan_id ?? '无法核对'),
|
||||
'核验:' + (report.taskPlan.verified_steps ?? 0) + '/' + (report.taskPlan.total_steps ?? 0), '',
|
||||
|
||||
@@ -8,11 +8,13 @@ export const DEFAULT_CONFIG = {
|
||||
mode: 'demo', baseUrl: 'http://127.0.0.1:11434/v1', model: '', ...DEFAULT_MODEL_CAPACITY, approvalMode: 'ask', capacityMode: 'passthrough', historyPolicy: 'preserve', executionMode: 'unrestricted', maxSteps: 0,
|
||||
maxRunDurationMs: 0, maxRunTokens: 0, maxTaskTokens: 0, configRevision: 1,
|
||||
modelResponseTimeoutMs: 0, modelStreamIdleTimeoutMs: 0,
|
||||
progressRemindersEnabled: false,
|
||||
};
|
||||
|
||||
export function cleanConfig(value = {}) {
|
||||
const result = { ...DEFAULT_CONFIG };
|
||||
for (const key of Object.keys(result)) if (Object.hasOwn(value, key)) result[key] = value[key];
|
||||
result.progressRemindersEnabled = result.progressRemindersEnabled === true;
|
||||
if (!Object.hasOwn(value, 'executionMode') && ['contextLimit', 'maxOutputTokens', 'maxSteps', 'maxRunTokens'].some(key => Object.hasOwn(value, key))) result.executionMode = 'restricted';
|
||||
// Old settings stay manual. Every saved Run keeps its original snapshot.
|
||||
if (!Object.hasOwn(value, 'capacityMode') && (Object.hasOwn(value, 'contextLimit') || Object.hasOwn(value, 'maxOutputTokens'))) result.capacityMode = 'manual';
|
||||
|
||||
@@ -241,6 +241,21 @@ return async (request, response) => {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (route === '/api/progress-reminders/settings') {
|
||||
if (method === 'GET') return json(response, { enabled: store.config.progressRemindersEnabled === true });
|
||||
if (method === 'POST') {
|
||||
const input = await body(request);
|
||||
if (!input || Object.keys(input).length !== 1 || typeof input.enabled !== 'boolean') throw new Error('进展提醒设置只接受开启或关闭。');
|
||||
store.saveConfig({ progressRemindersEnabled: input.enabled }); runtime.progressRemindersChanged();
|
||||
return json(response, { enabled: store.config.progressRemindersEnabled === true });
|
||||
}
|
||||
}
|
||||
const reminderRoute = route.match(/^\/api\/sessions\/([a-f0-9-]{36})\/progress-reminders$/i);
|
||||
if (method === 'GET' && reminderRoute) {
|
||||
const session = store.session(reminderRoute[1]), id = url.searchParams.get('run') || session.runId;
|
||||
const run = store.owned('run', id, session.id);
|
||||
return json(response, runtime.reminderManager().inspect(session, run));
|
||||
}
|
||||
if (method === 'GET' && route === '/api/operations') {
|
||||
return json(response, inspectOperations({ store, provider, runtime, server, appDirectory, version: APP_VERSION, parameters: url.searchParams }));
|
||||
}
|
||||
|
||||
+10
-3
@@ -1,4 +1,4 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { randomUUID, createHash } from 'node:crypto';
|
||||
import { unrestricted, approvalLabels } from '../shared/contracts/execution-policy.mjs';
|
||||
import { listFiles } from './files.mjs';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
@@ -234,8 +234,15 @@ export class Provider {
|
||||
dispatched = true;
|
||||
const transport=this.fetcher?null:(this.transport??=new ModelTransport());
|
||||
if(transport)onProgress?.({phase:'running',transport:transport.profile,attempt,maxAttempts:policy.attempts,wireAttemptId:receipt.attemptId});
|
||||
const response = await (this.fetcher??transport.fetch.bind(transport))(requestUrl, { method: body ? 'POST' : 'GET', headers,
|
||||
body: body ? JSON.stringify(body) : undefined, signal: requestSignal, redirect: 'manual' });
|
||||
const wireBody = body ? JSON.stringify(body) : undefined;
|
||||
const submitted = (this.fetcher??transport.fetch.bind(transport))(requestUrl, { method: body ? 'POST' : 'GET', headers,
|
||||
body: wireBody, signal: requestSignal, redirect: 'manual' });
|
||||
if (wireBody && options.onSubmitted) {
|
||||
// Optional local observers cannot interrupt an already submitted HTTP
|
||||
// request or leave its promise unobserved.
|
||||
try { options.onSubmitted({ attemptId: receipt.attemptId, wireRequestSha256: createHash('sha256').update(wireBody).digest('hex') }); } catch { /* Observer only. */ }
|
||||
}
|
||||
const response = await submitted;
|
||||
// Never forward either credential header to a redirect target. The
|
||||
// observed response URL is diagnostic data; queries/credentials are removed.
|
||||
let responseUrl = null;
|
||||
|
||||
+35
-8
@@ -51,6 +51,7 @@ import { browserPlanInput } from '../shared/contracts/browser.mjs';
|
||||
import { TaskPlanManager } from '../core/tasks/task-plan-manager.mjs';
|
||||
import { RequirementReview } from '../core/tasks/requirement-review.mjs';
|
||||
import { recordTurnProgress } from '../core/context/turn-progress-recorder.mjs';
|
||||
import { ReminderManager } from '../core/context/reminder-manager.mjs';
|
||||
import { FileResults } from '../core/tasks/file-results.mjs';
|
||||
import { fileResultInput, fileResultToolDefinitions } from '../shared/contracts/file-results.mjs';
|
||||
import { verifiedCheck } from '../core/delivery-report.mjs';
|
||||
@@ -220,6 +221,15 @@ export class Runtime {
|
||||
redact: value => this.provider.redact(value), projectBusy: projectId => this.projectHasActivity(projectId) });
|
||||
}
|
||||
requestPlanner() { return this.contextPlans ??= new RequestPlanner(this.store); }
|
||||
reminderManager() { return this.progressReminders ??= new ReminderManager(this.store); }
|
||||
observeProgress(session, run, step, phase = 'settled', failure = null) {
|
||||
const observation = recordTurnProgress(this.store, session, run, step, phase, failure);
|
||||
if (observation) this.reminderManager().observe(session, run);
|
||||
return observation;
|
||||
}
|
||||
progressRemindersChanged() {
|
||||
for (const [id, run] of this.active) this.reminderManager().observe(this.store.session(id), run.record);
|
||||
}
|
||||
inputAttachments() { return this.inputs ??= new InputAttachments(this.store,{busy:projectId=>this.projectHasActivity(projectId)}); }
|
||||
budgetResumes(){return this.resumes??=new BudgetResume(this.store,this.provider,this);}
|
||||
resumeBudget(id,input){const session=this.store.session(id),plan=this.budgetResumes().verify(session,input);return this.start(id,'',true,{resumePlan:plan});}
|
||||
@@ -325,6 +335,7 @@ export class Runtime {
|
||||
const status = session.status;
|
||||
if (record.purpose === 'diagnostic') session.status = record.taskStatusBefore;
|
||||
this.store.finishRun(session, record, run.stopReason ?? null, { status });
|
||||
this.reminderManager().observe(session, record, { endReason: run.stopReason === 'cancelled' ? 'cancelled' : 'run_finished' });
|
||||
await this.finalizeDeliveryReport(session, run);
|
||||
} finally { this.active.delete(id); }
|
||||
});
|
||||
@@ -390,7 +401,7 @@ export class Runtime {
|
||||
if (current.sourceFingerprint === originalTask.stagnation.sourceFingerprint) throw new BudgetExceeded('no_progress', '连续两次运行未增加源码改动、检查结果或新的读取依据。本次未请求模型;请根据原日志修改源码或发送具体调整,避免重复空续接。');
|
||||
originalTask.stagnation = null;
|
||||
}
|
||||
recordTurnProgress(this.store, session, run.record, null, 'baseline');
|
||||
this.observeProgress(session, run.record, null, 'baseline');
|
||||
for (let step = 0; config.maxSteps === 0 || step < config.maxSteps; step++) {
|
||||
signal.throwIfAborted();
|
||||
checkBudget(run.record, this.store.core.task.get(run.taskId));
|
||||
@@ -477,8 +488,22 @@ export class Runtime {
|
||||
: !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, toolSurface, stepId: stepRecord.id, projectMemory, skillCatalog, mcpCatalog,
|
||||
transportReservationTokens:run.worker?.engine?ENGINE_SEED_RESERVATION:0,engineStepOnly:!!run.worker?.engine });
|
||||
let reminder = config.mode === 'compatible' && !run.worker && (config.capacityMode === 'passthrough' || config.historyPolicy === 'preserve')
|
||||
? this.reminderManager().prepare(session, run.record, toolSurface) : null;
|
||||
const prepare = selected => this.requestPlanner().prepare(session, run.record, config, {
|
||||
system: stablePrefix ? this.provider.redact(fixedContext) : context + (selected ? '\n' + selected.message.content : ''),
|
||||
contextTail: stablePrefix ? context + (selected ? '\n' + selected.message.content : '') : null,
|
||||
progressReminder: selected?.ref ?? null, tools, toolSurface, stepId: stepRecord.id, projectMemory, skillCatalog, mcpCatalog,
|
||||
transportReservationTokens: run.worker?.engine ? ENGINE_SEED_RESERVATION : 0, engineStepOnly: !!run.worker?.engine });
|
||||
let planned;
|
||||
try { planned = prepare(reminder); }
|
||||
catch (error) {
|
||||
if (!reminder) throw error;
|
||||
// Optional advice may never be the reason a request is refused or
|
||||
// original history is removed. Retry planning once without advice;
|
||||
// no model request or tool has been dispatched at this point.
|
||||
reminder = null; this.reminderManager().error(session, run.record, 'request_plan'); planned = prepare(null);
|
||||
}
|
||||
if (planned.record.archivedGroups && !projectionLogged) {
|
||||
projectionLogged = true; session.compactions++;
|
||||
this.store.event(session, { kind: 'context', label: '整理请求上下文', phase: 'completed', contextPlanId: planned.record.id,
|
||||
@@ -541,7 +566,9 @@ 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: providerHistory(session, run.record) } : {}), 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) } : {}),
|
||||
...(reminder ? { onSubmitted: submission => this.reminderManager().dispatch(session, run.record, planned.record, submission) } : {}),
|
||||
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) {
|
||||
@@ -720,7 +747,7 @@ export class Runtime {
|
||||
return;
|
||||
}
|
||||
stepRecord.progressSettled = true;
|
||||
recordTurnProgress(this.store, session, run.record, stepRecord);
|
||||
this.observeProgress(session, run.record, stepRecord);
|
||||
if (!unrestricted(config) && this.store.core.task.get(run.taskId).readProgress?.pause) throw new BudgetExceeded('no_progress',
|
||||
'模型连续重复读取工件或核对相同的工程状态,未推进当前任务。实际结果和原任务已保存,请核对后继续。');
|
||||
}
|
||||
@@ -762,7 +789,7 @@ export class Runtime {
|
||||
} finally {
|
||||
if (currentStep && !currentStep.progressSettled) {
|
||||
currentStep.progressSettled = true;
|
||||
recordTurnProgress(this.store, session, run.record, currentStep, 'settled', session.lastFailure?.runId === run.id ? session.lastFailure : null);
|
||||
this.observeProgress(session, run.record, currentStep, 'settled', session.lastFailure?.runId === run.id ? session.lastFailure : null);
|
||||
}
|
||||
if (run.worker?.engine) await this.engineRunner().finish(session, run);
|
||||
}
|
||||
@@ -946,7 +973,7 @@ export class Runtime {
|
||||
...(check.python ? { python: { runtime: check.python.runtime, mode: check.python.mode } } : {}) })),
|
||||
reason: '执行工程检查计划 ' + plan.id.slice(0, 8) + ';保存测试数量、退出码和日志。' }, run, async () => {
|
||||
const { promise } = await this.checkRunner().start(session, plan.id, { signal: run.controller.signal, source: 'agent' });
|
||||
recordTurnProgress(this.store, session, run.record, [...this.store.core.step.values()].findLast(row => row.runId === run.id), 'waiting');
|
||||
this.observeProgress(session, run.record, [...this.store.core.step.values()].findLast(row => row.runId === run.id), 'waiting');
|
||||
const job = await promise;
|
||||
return { status: job.status === 'cancelled' ? 'interrupted' : job.status === 'passed' ? 'completed' : job.status,
|
||||
check_status: job.status, job_id: job.id, plan_id: job.planId, results: job.results, summary: job.summary,
|
||||
@@ -1016,7 +1043,7 @@ export class Runtime {
|
||||
session.approvals.push(approval);
|
||||
event.phase = 'waiting'; session.status = 'awaiting_approval';
|
||||
this.store.invocationState(session, event, 'waiting');
|
||||
recordTurnProgress(this.store, session, run.record, [...this.store.core.step.values()].findLast(row => row.runId === run.id), 'waiting');
|
||||
this.observeProgress(session, run.record, [...this.store.core.step.values()].findLast(row => row.runId === run.id), 'waiting');
|
||||
const policy = automaticApproval(this.store.config, args);
|
||||
approval.approvalMode = policy.mode; approval.policyRevision = this.store.config.configRevision;
|
||||
const decision = policy.approve ? (approval.status = 'approved', approval.decisionSource = policy.source, approval.decidedAt = now(), this.store.save(session), true) : await new Promise(resolve => {
|
||||
|
||||
Reference in New Issue
Block a user