import type { Message } from '../types.js'; import { isSystemEventMessage } from '../runtime/systemEvents.js'; import { expandAdvisorHistory } from './advisorHistory.js'; /** Reload hints, not a second copy of skill instructions. Only successful skill * loads in the latest human turn qualify; never revive skills from older tasks. */ export function compactSkillReferences(messages: readonly Message[]): string { // Reuse the existing cold evidence archive across repeated compactions. // Never parse model-written summaries to invent successful skill loads. const evidence = expandAdvisorHistory(messages); let start = evidence.length - 1; while (start >= 0 && (evidence[start].role !== 'user' || isSystemEventMessage(evidence[start]))) start--; if (start < 0) return ''; const calls = new Map(); const successful = new Map(); for (const message of evidence.slice(start)) { if (message.role === 'assistant') for (const call of message.tool_calls ?? []) { if (call.function.name !== 'Skill') continue; try { const args = JSON.parse(call.function.arguments); if (typeof args.name === 'string' && args.name.length <= 200) calls.set(call.id, { name: args.name, ...(typeof args.sourceId === 'string' && /^[a-f0-9]{64}$/.test(args.sourceId) ? { sourceId: args.sourceId } : {}) }); } catch { /* Invalid invocations carry no reload authority. */ } } if (message.role === 'tool' && message.display_ok === true) { const skill = calls.get(message.tool_call_id); if (skill) successful.set(JSON.stringify(skill), skill); } } const skills = [...successful.values()].slice(-8); return skills.length ? '\n\n\n' + 'These are successful Skill loads from the latest human turn, not their instructions. If still needed for pending work, reload Skill before acting; do not treat remembered fragments as complete instructions or expand permissions. Task/agent status must be re-read from its existing ledger, not inferred from this summary.\n' + JSON.stringify(skills).replace(//g, '\\u003e') + '\n' : ''; }