Files
Agent-Workbench/src/core/context/reminder-queue.mjs
T

135 lines
9.2 KiB
JavaScript

import { createHash } from 'node:crypto';
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);
const scopeOf = value => Object.fromEntries(['projectId', 'sessionId', 'taskId', 'runId'].map(key => [key, value?.[key]]));
// These bounds apply only to optional advice. They never limit a user request,
// model output, history, tools, execution time or permissions.
export const REMINDER_POLICY = Object.freeze({ repeatedTurns: 2, ttlMs: 10 * 60_000, cooldownTurns: 3, maxDeliveries: 3, messageBytes: 1800 });
function queue(previous, scope, enabled, at) {
if (Object.values(scopeOf(scope)).some(value => typeof value !== 'string' || !value)) throw new Error('Reminder scope is incomplete.');
if (previous && (previous.schemaVersion !== 1 || !same(previous.scope, scopeOf(scope)))) throw new Error('Reminder belongs to another Task/Run.');
if (!Number.isFinite(at)) throw new Error('Reminder time is invalid.');
const state = previous ? structuredClone(previous) : { schemaVersion: 1, scope: scopeOf(scope), enabled: false, lastOrdinal: 0, streak: null, items: [] };
state.enabled = enabled === true;
for (const item of state.items) if (active(item) && (!state.enabled || at >= item.expiresAt)) {
item.status = 'expired'; item.closedAt = at; item.exitReason = state.enabled ? 'ttl' : 'disabled';
}
if (!state.enabled) state.streak = null;
return state;
}
const expire = (state, reason, at) => {
for (const item of state.items) if (active(item)) { item.status = 'expired'; item.closedAt = at; item.exitReason = reason; }
state.streak = null;
};
// The caller must verify the immutable observation and original tool receipts.
// Text written by the model is deliberately not accepted as readback evidence.
export function observeReminders(previous, { scope, enabled = false, at, receipt = null, research = false, endReason = null }) {
const state = queue(previous, scope, enabled, at);
if (endReason) { expire(state, endReason, at); return state; }
if (!state.enabled || !receipt) return state;
const { observation: turn, ref, tools } = receipt;
if (!sha(ref?.sha256) || typeof ref.artifactId !== 'string' || !Number.isSafeInteger(ref.ordinal) || ref.ordinal < 1
|| turn?.taskId !== scope.taskId || turn.runId !== scope.runId || !Array.isArray(tools)) throw new Error('Reminder observation source is invalid.');
if (ref.ordinal <= state.lastOrdinal) {
if (ref.ordinal === state.lastOrdinal && state.lastArtifactId === ref.artifactId) return state;
throw new Error('Late reminder observation cannot update this queue.');
}
state.lastOrdinal = ref.ordinal; state.lastArtifactId = ref.artifactId;
if (research || turn.waiting?.length || turn.delta?.user_boundaries || turn.classification === 'new_failure_evidence') {
expire(state, research ? 'research' : turn.waiting?.length ? 'waiting' : turn.delta?.user_boundaries ? 'user_boundary' : 'new_failure', at);
return state;
}
if (turn.phase === 'baseline' || turn.phase === 'waiting') { state.streak = null; return state; }
for (const item of state.items.filter(active)) {
const later = ref.ordinal > item.source.at(-1).ordinal;
const newRange = item.expected.kind === 'new_read_range' && turn.delta?.read_characters > 0 && tools.some(tool => tool.read && !tool.failure);
const corrected = item.expected.kind === 'corrected_tool_result' && tools.some(tool => item.toolNames.includes(tool.name) && tool.success === true && !tool.failure);
if (later && (newRange || corrected)) {
item.status = 'resolved'; item.closedAt = at;
item.resolution = { source: structuredClone(ref), kind: newRange ? 'new_read_range' : 'corrected_tool_result',
relation: item.deliveries.length ? 'observed_after_dispatch' : 'naturally_resolved', causality: 'unproven' };
}
}
const noGrowth = turn.delta && !['read_characters', 'new_sources', 'changed_files', 'check_results', 'requirement_evidence', 'user_boundaries', 'new_failures', 'other_observations'].some(key => turn.delta[key]);
let category, relevant;
if (noGrowth && !turn.truncated && turn.classification === 'repeated_read_candidate') {
category = 'repeated_read'; relevant = tools.filter(tool => tool.read && !tool.failure);
} else if (noGrowth && !turn.truncated && turn.classification === 'repeated_failure_candidate'
&& tools.length && tools.every(tool => tool.failure?.category === 'invalid_input')) {
category = 'repeated_invalid_input'; relevant = tools;
}
if (!category || !relevant?.length) { state.streak = null; return state; }
const signatures = relevant.map(tool => category === 'repeated_read' ? [tool.name, tool.read]
: [tool.name, tool.argsSha256, tool.failure]).map(hash).sort();
const key = hash([state.scope, category, [...new Set(signatures)]]);
if (state.streak?.key === key) { state.streak.count++; state.streak.sources.push(structuredClone(ref)); }
else state.streak = { key, count: 1, sources: [structuredClone(ref)] };
state.streak.sources = state.streak.sources.slice(-REMINDER_POLICY.repeatedTurns);
// A stable fact is suggested once per Run. Ineffective, disabled or expired
// advice cannot keep recreating itself under a different random ID.
if (state.streak.count >= REMINDER_POLICY.repeatedTurns && !state.items.some(item => item.key === key)) {
state.items.push({ key, category, status: 'pending', createdAt: at, expiresAt: at + REMINDER_POLICY.ttlMs,
source: structuredClone(state.streak.sources), toolNames: [...new Set(relevant.map(tool => tool.name))].sort(),
expected: { kind: category === 'repeated_read' ? 'new_read_range' : 'corrected_tool_result' }, deliveries: [] });
}
return state;
}
function messageFor(state, item, visible) {
const tools = item.toolNames.filter(name => visible.includes(name));
if (!tools.length) return null;
const summary = item.category === 'repeated_read'
? '已核对同一SHA和区间连续重复返回。可根据原目标使用已有结果;还需内容时,用当前提供的读取工具取得未读区间。'
: '已核对同一工具和参数连续返回相同的参数错误。可根据原始错误修正参数,再使用本轮提供的工具。';
const content = '工作台可选进展建议(不是用户追加目标,不授予权限):\n' + JSON.stringify({
key: item.key, category: item.category, summary, available_tools: tools,
source: item.source.map(({ artifactId, sha256 }) => ({ artifact_id: artifactId, sha256 })), expected_observation: item.expected.kind,
note: '按原任务约定决定下一步;回复已知悉不构成证据,后续实际工具结果单独核对。',
});
if (Buffer.byteLength(content, 'utf8') > REMINDER_POLICY.messageBytes) return null;
return { key: item.key, scope: state.scope, content, sha256: hash(content), tools };
}
export function selectReminder(previous, { scope, enabled = false, at, visibleTools = [] }) {
const state = queue(previous, scope, enabled, at);
if (!state.enabled) return { state, message: null };
for (const item of state.items.filter(active)) {
if (item.deliveries.length >= REMINDER_POLICY.maxDeliveries) { item.status = 'expired'; item.closedAt = at; item.exitReason = 'ineffective'; continue; }
const last = item.deliveries.at(-1);
const cooldown = REMINDER_POLICY.cooldownTurns * 2 ** Math.max(0, item.deliveries.length - 1);
if (last && state.lastOrdinal - last.ordinal < cooldown) continue;
const message = messageFor(state, item, visibleTools);
if (!message) { item.status = 'expired'; item.closedAt = at; item.exitReason = 'tool_unavailable_or_advice_too_large'; continue; }
return { state, message };
}
return { state, message: null };
}
// 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, 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 (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;
}