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; } }