providers.ts 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  1. /**
  2. * System-reminder providers — individual reminder block providers.
  3. *
  4. * Each provider is a ReminderProviderFn: it receives SystemReminderInput and
  5. * returns a string block for injection into <system-reminder>, or undefined
  6. * to skip. Providers are registered on a SystemReminderRegistry and executed
  7. * in registration order.
  8. *
  9. * The createDefaultRegistry() factory returns a registry pre-loaded with all
  10. * built-in providers. Framework-specific providers can be appended via
  11. * registry.appendFor() after creation.
  12. */
  13. import type { ReminderPolicyEntry, ReminderProviderFn, SystemReminderInput } from './types.js';
  14. import { boundMap } from './evolution.js';
  15. import {
  16. buildAgentContextBlock,
  17. buildSlimAgentContextBlock,
  18. buildPeersUpdateBlock,
  19. buildCliSunsetMemoryNoticeBlock,
  20. buildMemorySkillReminder,
  21. buildProactiveMemoryBlock,
  22. buildMemoryTopicsBlock,
  23. buildPersonaMissingBlock,
  24. buildBootstrapBlock,
  25. buildTeamMemoryBlock,
  26. buildEvolutionReminderBlock,
  27. buildRelevantMemoryBlock,
  28. buildUserMemoryUpdateBlock,
  29. buildAgentMemoryUpdateBlock,
  30. buildMemorySummaryUpdateBlock,
  31. buildDailyMemoryUpdateBlock,
  32. buildIdentityUpdateBlock,
  33. buildConfigUpdateBlock,
  34. buildInboundMetaBlock,
  35. buildActivePlanReminderBlock,
  36. buildSkillEvolutionChannelsBlock,
  37. buildAsyncAuditBlock,
  38. buildMediaOutputReminderBlock,
  39. buildTaskCompletionReminderBlock,
  40. buildBoardNudgeBlock,
  41. buildWorktreeReminderBlock,
  42. buildSecretEnvBlock,
  43. } from './blocks.js';
  44. import { SystemReminderRegistry } from './registry.js';
  45. import type { NudgeRegistry, DateFormatter } from './dependencies.js';
  46. import { shouldInjectTodoCompletionReminder } from './todo-state.js';
  47. // ─── Threshold Constants ─────────────────────────────────────────────────────
  48. /** Cool-down between repeated cold-start reminder injections (per session+kind). */
  49. export const COLD_START_COOLDOWN_MS = 6 * 60 * 60 * 1000; // 6h
  50. // ─── ReminderPolicyEntry allowlist / policy helpers ──────────────────────────
  51. //
  52. // Cloud-runtime path: `AgentConfig.system_reminders` (IDL field 19) flows
  53. // through `CloudDataCollector.collect()` into `SystemReminderInput.systemReminders`
  54. // as a strict allowlist + per-entry policy override.
  55. //
  56. // Provider naming convention: registry registers providers as `xxxProvider`
  57. // (e.g. `memorySkillReminderProvider`); Apollo `reminder_name` writes them
  58. // without the `Provider` suffix (`memorySkillReminder`). `stripProviderSuffix`
  59. // is the single normalisation point — service.ts uses it for allowlist
  60. // filtering, each backoff provider uses it via `findReminderPolicy` to look
  61. // up its own policy entry.
  62. /** Drop the canonical `Provider` suffix when comparing registry name to Apollo `reminder_name`. */
  63. export function stripProviderSuffix(name: string): string {
  64. return name.endsWith('Provider') ? name.slice(0, -'Provider'.length) : name;
  65. }
  66. /**
  67. * Look up the ReminderPolicyEntry that targets `providerName` in the per-turn
  68. * allowlist. Returns undefined when:
  69. * - `input.systemReminders` is undefined (daemon path / legacy caller — no
  70. * override, provider falls back to its hard-coded default schedule)
  71. * - `input.systemReminders` is an empty array (cloud strict-off — provider
  72. * won't fire because service.ts allowlist filter drops it; defensive
  73. * lookup still returns undefined here)
  74. * - no entry matches the stripped name
  75. *
  76. * The provider should read `.frequency` / `.thresholds` off the returned entry
  77. * and treat undefined fields as "use default".
  78. */
  79. export function findReminderPolicy(
  80. input: SystemReminderInput,
  81. providerName: string,
  82. ): ReminderPolicyEntry | undefined {
  83. if (!input.systemReminders) return undefined;
  84. const key = stripProviderSuffix(providerName);
  85. return input.systemReminders.find((e) => e.name === key);
  86. }
  87. /**
  88. * Resolve the next backoff interval given a level (0-based emit count) and an
  89. * optional Apollo override sequence. Falls back to `defaultIntervals` when the
  90. * override is missing or empty. Both arrays clamp to the last value once
  91. * `level` exceeds their length — matches the daemon "cap at last interval"
  92. * behaviour used by every backoff provider.
  93. *
  94. * `override` may be `(number | string)[]` because thrift-gen emits i64-capable
  95. * fields as `number | string`; SystemReminderFrequency.intervals is i32 so this
  96. * shows up as `number[]`. We accept both for forward-compat with any future
  97. * widening.
  98. */
  99. export function effectiveInterval(
  100. level: number,
  101. override: ReadonlyArray<number | string> | undefined,
  102. defaultIntervals: readonly number[],
  103. ): number {
  104. const src = override && override.length > 0 ? override : defaultIntervals;
  105. // src.length > 0 guaranteed: override branch checked; defaultIntervals branch
  106. // is statically non-empty at every call site (ASYNC_AUDIT_DEFAULTS / etc).
  107. // tsconfig has noUncheckedIndexedAccess so widen via nullish-coalesce + last-elem fallback.
  108. const idx = Math.min(level, src.length - 1);
  109. const raw = src[idx] ?? src[src.length - 1] ?? 0;
  110. return typeof raw === 'string' ? Number(raw) : raw;
  111. }
  112. /** Resolve a single i32 ms override (number|string) with a fallback. */
  113. export function effectiveMs(override: number | string | undefined, fallback: number): number {
  114. if (override === undefined || override === null) return fallback;
  115. return typeof override === 'string' ? Number(override) : override;
  116. }
  117. /**
  118. * Normalise an optional i32 ms override (thrift-gen emits `number | string`)
  119. * into `number | undefined`. Used by cold-start cooldown providers that pass
  120. * the result straight into `tryEnterColdStart`'s `cooldownOverrideMs` slot
  121. * (undefined → fall back to per-kind default).
  122. */
  123. export function effectiveMsOr(override: number | string | undefined): number | undefined {
  124. if (override === undefined || override === null) return undefined;
  125. return typeof override === 'string' ? Number(override) : override;
  126. }
  127. // ─── Cold-start cool-down state ──────────────────────────────────────────────
  128. //
  129. // Cold-start reminders (persona_missing, bootstrap_check) are
  130. // noisy if injected on every turn. We track per-session+per-kind last-injected timestamps
  131. // in process memory. State is intentionally non-persistent — daemon restart resets it,
  132. // which is acceptable: a single re-injection right after restart is harmless.
  133. //
  134. // Tests can call `_resetColdStartCooldownForTests()` to clear state between cases.
  135. type ColdStartKind = 'persona_missing' | 'bootstrap_check' | 'worktree_check';
  136. const coldStartLastInjectedAt = new Map<string, number>();
  137. /** Cool-down key — sessionId+kind, falls back to agentName when env is unavailable. */
  138. function coldStartKey(input: SystemReminderInput, kind: ColdStartKind): string {
  139. const id = input.env?.sessionId ?? input.env?.agentName ?? 'unknown';
  140. return `${id}::${kind}`;
  141. }
  142. /**
  143. * Check whether a cold-start reminder is allowed to fire now.
  144. * Records the timestamp on success; subsequent calls within the cool-down window return false.
  145. *
  146. * `cooldownOverrideMs` (typically `thresholds.cooldown_ms` from the package-local
  147. * ReminderPolicyEntry) takes precedence over `COLD_START_COOLDOWN_MS`.
  148. *
  149. * `now` is overridable for deterministic tests.
  150. */
  151. function tryEnterColdStart(
  152. input: SystemReminderInput,
  153. kind: ColdStartKind,
  154. cooldownOverrideMs: number | undefined,
  155. now: number = Date.now(),
  156. ): boolean {
  157. const key = coldStartKey(input, kind);
  158. const last = coldStartLastInjectedAt.get(key);
  159. const cooldown = cooldownOverrideMs ?? COLD_START_COOLDOWN_MS;
  160. if (last !== undefined && now - last < cooldown) return false;
  161. coldStartLastInjectedAt.set(key, now);
  162. return true;
  163. }
  164. /** Test helper — clear cool-down state. Not exported from the package public API. */
  165. export function _resetColdStartCooldownForTests(): void {
  166. coldStartLastInjectedAt.clear();
  167. }
  168. /** Cold-start reminders only fire for orchestrators or manually-created agents. */
  169. function isColdStartAudience(input: SystemReminderInput): boolean {
  170. if (input.env?.agentRole === 'orchestrator') return true;
  171. if (input.creationSource === 'manual') return true;
  172. return false;
  173. }
  174. // ─── Individual Providers ────────────────────────────────────────────────────
  175. /** Inject <agent-context> block with session/agent metadata. */
  176. export const agentContextProvider: ReminderProviderFn = (input) => {
  177. if (!input.env) return undefined;
  178. if (input.turnCount !== undefined && input.turnCount > 1) {
  179. return buildSlimAgentContextBlock(input.env);
  180. }
  181. return buildAgentContextBlock(input.env, { teamModeOff: input.teamModeOff });
  182. };
  183. /** Inject <peers_update> when peer list changes mid-session. */
  184. export const peersUpdateProvider: ReminderProviderFn = (input) => {
  185. if (input.teamModeOff) return undefined;
  186. if (!input.peersChanged || !input.env?.peers?.length) return undefined;
  187. return buildPeersUpdateBlock(input.env.peers);
  188. };
  189. /**
  190. * Inject <active-plan-reminder> for orchestrators who own one or more active
  191. * team plans. Worker sessions and sessions with no active plans are skipped.
  192. * Reminds the orchestrator to keep new requirement changes inside the
  193. * existing plan via `mavis team plan pause` + `decision` rather than
  194. * spawning standalone sessions.
  195. */
  196. export const activePlanReminderProvider: ReminderProviderFn = (input) => {
  197. if (input.teamModeOff) return undefined;
  198. if (input.env?.agentRole !== 'orchestrator') return undefined;
  199. if (!input.activePlans?.length) return undefined;
  200. return buildActivePlanReminderBlock(input.activePlans);
  201. };
  202. /** Inject <memory-skill-reminder> with file size, skill-evolution routing trigger,
  203. * and the three-question memory-layer attribution.
  204. *
  205. * Schedule: turn 1, then 10 → 20 → 40 → 40... turns apart (cap at 40).
  206. * Resets on compaction (turnCount drops below lastInjectedAt).
  207. *
  208. * Renamed from `memoryStatusProvider` — the block now teaches a precondition
  209. * before the memory-layer test: "is this a SKILL signal/proposal instead?"
  210. * The skill section gates independently per channel via
  211. * `input.skillEvolveEnabled` (signal) and `input.skillProposalEnabled`
  212. * (proposal); when both are off, only the three-question memory-layer test
  213. * is rendered. The full skill-evolution channel rules live in the
  214. * `skill-evolution` skill; this block carries only the trigger checklist
  215. * + skill names so agents in long sessions stop silently defaulting to
  216. * `mavis memory append`.
  217. */
  218. export const memorySkillReminderProvider: ReminderProviderFn = (input) => {
  219. if (!input.env) return undefined;
  220. const skillOpts = {
  221. skillEvolveEnabled: input.skillEvolveEnabled === true,
  222. skillProposalEnabled: input.skillProposalEnabled === true,
  223. };
  224. const turn = input.turnCount ?? 0;
  225. if (turn < 1) {
  226. // Fallback for callers that do not pass turnCount — preserve original
  227. // "always inject" behavior so SR rendering paths without turn info
  228. // still get the block.
  229. const block = buildMemorySkillReminder(input.memorySkillReminder, {
  230. ...skillOpts,
  231. scene: input.env.scene,
  232. dataDir: input.env.dataDir,
  233. });
  234. return block || undefined;
  235. }
  236. const sessionId = input.env.sessionId ?? 'unknown';
  237. const state = memorySkillReminderState.get(sessionId);
  238. const policy = findReminderPolicy(input, 'memorySkillReminderProvider');
  239. const overrideIntervals = policy?.frequency?.intervals;
  240. // First turn or no state → inject and initialize
  241. if (turn <= 1 || !state) {
  242. memorySkillReminderState.set(sessionId, { lastInjectedAt: turn, backoffLevel: 0 });
  243. boundMap(memorySkillReminderState);
  244. const block = buildMemorySkillReminder(input.memorySkillReminder, {
  245. ...skillOpts,
  246. scene: input.env.scene,
  247. dataDir: input.env.dataDir,
  248. });
  249. return block || undefined;
  250. }
  251. // Compaction detected: turnCount dropped below last injection point → reset
  252. if (turn < state.lastInjectedAt) {
  253. memorySkillReminderState.set(sessionId, { lastInjectedAt: turn, backoffLevel: 0 });
  254. boundMap(memorySkillReminderState);
  255. const block = buildMemorySkillReminder(input.memorySkillReminder, {
  256. ...skillOpts,
  257. scene: input.env.scene,
  258. dataDir: input.env.dataDir,
  259. });
  260. return block || undefined;
  261. }
  262. const interval = effectiveInterval(
  263. state.backoffLevel,
  264. overrideIntervals,
  265. MEMORY_SKILL_REMINDER_DEFAULTS,
  266. );
  267. if (turn - state.lastInjectedAt >= interval) {
  268. memorySkillReminderState.set(sessionId, {
  269. lastInjectedAt: turn,
  270. backoffLevel: state.backoffLevel + 1,
  271. });
  272. boundMap(memorySkillReminderState);
  273. const block = buildMemorySkillReminder(input.memorySkillReminder, {
  274. ...skillOpts,
  275. scene: input.env.scene,
  276. dataDir: input.env.dataDir,
  277. });
  278. return block || undefined;
  279. }
  280. return undefined;
  281. };
  282. /** Inject the opt-in proactive-memory rubric on every eligible turn. */
  283. export const proactiveMemoryProvider: ReminderProviderFn = (input) => {
  284. if (input.proactiveMemoryEnabled !== true) return undefined;
  285. return buildProactiveMemoryBlock();
  286. };
  287. interface MemorySkillReminderState {
  288. lastInjectedAt: number;
  289. backoffLevel: number;
  290. }
  291. const memorySkillReminderState = new Map<string, MemorySkillReminderState>();
  292. /** Default backoff schedule: 10, 20, 40 (cap). Apollo `intervals` overrides this. */
  293. const MEMORY_SKILL_REMINDER_DEFAULTS = [10, 20, 40] as const;
  294. /**
  295. * @deprecated Use `effectiveInterval(level, override, MEMORY_SKILL_REMINDER_DEFAULTS)`.
  296. * Kept temporarily for any external import; the inline impl matches the old
  297. * 10 / 20 / 40 (cap) ladder.
  298. */
  299. function memorySkillReminderInterval(level: number): number {
  300. return effectiveInterval(level, undefined, MEMORY_SKILL_REMINDER_DEFAULTS);
  301. }
  302. // Suppress lint warning — kept on purpose for back-compat (see deprecation note above).
  303. void memorySkillReminderInterval;
  304. /** Test helper — clear memory-skill-reminder backoff state. */
  305. export function _resetMemorySkillReminderStateForTests(): void {
  306. memorySkillReminderState.clear();
  307. }
  308. /** Inject <available_memory_topics> listing topic files with descriptions. */
  309. export const memoryTopicsProvider: ReminderProviderFn = (input) => {
  310. if (!input.env) return undefined;
  311. // Only inject on first message (topics don't change mid-session)
  312. if (input.turnCount !== undefined && input.turnCount !== 1) return undefined;
  313. const block = buildMemoryTopicsBlock(input.memoryTopics);
  314. return block || undefined;
  315. };
  316. /**
  317. * Inject <cli-sunset-memory-notice> when the host flagged stored memory files
  318. * as predating the mavis CLI removal. First turn only — the host re-evaluates
  319. * per session (and after compaction resets turnCount), so eligibility stays
  320. * fresh without provider-side state.
  321. */
  322. export const cliSunsetMemoryNoticeProvider: ReminderProviderFn = (input) => {
  323. if (input.turnCount !== undefined && input.turnCount !== 1) return undefined;
  324. const block = buildCliSunsetMemoryNoticeBlock(input.cliSunsetMemoryNotice);
  325. return block || undefined;
  326. };
  327. /**
  328. * Inject <persona_missing> for cold-start audiences when the agent has no real persona yet.
  329. * Cool-down: 6h default per (session, kind); Apollo `thresholds.cooldown_ms` overrides.
  330. */
  331. export const personaMissingProvider: ReminderProviderFn = (input) => {
  332. if (!input.personaMissing) return undefined;
  333. if (!isColdStartAudience(input)) return undefined;
  334. const policy = findReminderPolicy(input, 'personaMissingProvider');
  335. const cooldownMs = policy?.thresholds?.cooldown_ms;
  336. if (!tryEnterColdStart(input, 'persona_missing', effectiveMsOr(cooldownMs))) return undefined;
  337. const personaPath = input.personaPath ?? '<unknown>';
  338. const agentName = input.env?.agentName ?? '<agent>';
  339. return buildPersonaMissingBlock(personaPath, agentName, { scene: input.env?.scene });
  340. };
  341. /**
  342. * Create a <branch-finish-alert> provider that renders finish timestamps using
  343. * the host-injected local-date formatter (the host owns the timezone).
  344. */
  345. export function createBranchNotificationProvider(
  346. formatLocalDateTime: DateFormatter,
  347. ): ReminderProviderFn {
  348. return (input) => {
  349. if (!input.branchNotifications?.length) return undefined;
  350. const lines = input.branchNotifications.map(
  351. (n) =>
  352. `- "${n.title ?? '(untitled)'}" (${n.branchSessionId}) finished at ${formatLocalDateTime(n.finishedAt)} without sending a report.` +
  353. ` Use \`mavis session messages ${n.branchSessionId}\` to check its results.`,
  354. );
  355. return (
  356. `<branch-finish-alert>\n` +
  357. `The following branch sessions finished without reporting back to you:\n` +
  358. `${lines.join('\n')}\n` +
  359. `Review their results and take action if needed.\n` +
  360. `</branch-finish-alert>`
  361. );
  362. };
  363. }
  364. /**
  365. * Inject session-scoped one-shot reminder bodies (e.g. session-rotate
  366. * handoff bootstrap, async handoff-ready notice). Each entry is already a
  367. * complete block — the outer `<system-reminder>` wrapper is added by
  368. * SystemReminderService. Multiple entries are joined with a blank line.
  369. *
  370. * Consumed by SystemReminderDataCollector — entries are cleared on
  371. * collect, so each reminder is delivered exactly once.
  372. */
  373. export const pendingSessionRemindersProvider: ReminderProviderFn = (input) => {
  374. if (!input.pendingSessionReminders?.length) return undefined;
  375. return input.pendingSessionReminders
  376. .map((c) => c.trim())
  377. .filter(Boolean)
  378. .join('\n\n');
  379. };
  380. /** Remind agents to reconcile active TodoWrite items before final delivery. */
  381. export const taskCompletionReminderProvider: ReminderProviderFn = (input) => {
  382. const sessionId = input.env?.sessionId;
  383. const turn = input.turnCount ?? 0;
  384. if (!input.activeTodoState) return undefined;
  385. if (!sessionId || turn < 1) return undefined;
  386. const policy = findReminderPolicy(input, 'taskCompletionReminderProvider');
  387. const intervalTurns = effectiveMs(policy?.thresholds?.todo_reminder_interval_turns, 5);
  388. const summary = shouldInjectTodoCompletionReminder(sessionId, turn, intervalTurns);
  389. if (!summary) return undefined;
  390. return buildTaskCompletionReminderBlock(summary);
  391. };
  392. /** Inject evolution reminder (memory-write reminder only). */
  393. export const evolutionReminderProvider: ReminderProviderFn = (input) => {
  394. if (!input.evolutionReminder?.trim()) return undefined;
  395. return buildEvolutionReminderBlock(input.evolutionReminder.trim());
  396. };
  397. /**
  398. * Inject <bootstrap_check> for cold-start audiences in uninitialized workspaces.
  399. * Cool-down: 6h default per (session, kind); Apollo `thresholds.cooldown_ms` overrides.
  400. */
  401. export const bootstrapProvider: ReminderProviderFn = (input) => {
  402. if (!input.needsBootstrap) return undefined;
  403. if (!input.isGitWorkspace) return undefined; // non-git workspaces don't need AGENTS.md bootstrap
  404. if (!isColdStartAudience(input)) return undefined;
  405. const policy = findReminderPolicy(input, 'bootstrapProvider');
  406. const cooldownMs = policy?.thresholds?.cooldown_ms;
  407. if (!tryEnterColdStart(input, 'bootstrap_check', effectiveMsOr(cooldownMs))) return undefined;
  408. return buildBootstrapBlock(input.workspaceDir, { scene: input.env?.scene });
  409. };
  410. /**
  411. * Inject <worktree-reminder> for cloud and legacy callers in a git checkout.
  412. *
  413. * Audience: ALL agents (orchestrator, worker, branch — any role can edit code).
  414. * Local-runtime resolves explicit UI worktree selection before the turn. This
  415. * reminder prevents cloud and legacy callers from creating duplicate worktrees
  416. * while leaving the final branch policy to the repository instructions.
  417. * Suppression: skipped when the agent is already inside a worktree
  418. * (`.git` is a gitlink file rather than a directory) — at that point the
  419. * worktree workflow is presumed in effect.
  420. *
  421. * Cool-down: 6h default per (session, kind); Apollo `thresholds.cooldown_ms` overrides.
  422. * Rationale: the rule is short and stable; once-per-session is enough.
  423. * 6h handles long-lived sessions and post-rotation re-injection without
  424. * spamming context on every turn.
  425. */
  426. export const worktreeReminderProvider: ReminderProviderFn = (input) => {
  427. if (input.env?.scene === 'local') return undefined;
  428. if (!input.isGitWorkspace) return undefined;
  429. if (input.isInsideWorktree) return undefined;
  430. const policy = findReminderPolicy(input, 'worktreeReminderProvider');
  431. const cooldownMs = policy?.thresholds?.cooldown_ms;
  432. if (!tryEnterColdStart(input, 'worktree_check', effectiveMsOr(cooldownMs))) return undefined;
  433. return buildWorktreeReminderBlock();
  434. };
  435. /** Inject <team_memory> with sibling agent memory headings. */
  436. export const teamMemoryProvider: ReminderProviderFn = (input) => {
  437. if (!input.teamMemoryIndex?.trim()) return undefined;
  438. return buildTeamMemoryBlock(input.teamMemoryIndex.trim());
  439. };
  440. /** Inject <relevant-memory> with query-matched memory sections. */
  441. export const relevantMemoryProvider: ReminderProviderFn = (input) => {
  442. if (!input.relevantMemory?.trim()) return undefined;
  443. return buildRelevantMemoryBlock(input.relevantMemory.trim());
  444. };
  445. /** Inject <user_memory_update> when user memory changes mid-session. */
  446. export const userMemoryUpdateProvider: ReminderProviderFn = (input) => {
  447. if (!input.userMemoryUpdate?.trim()) return undefined;
  448. return buildUserMemoryUpdateBlock(input.userMemoryUpdate.trim());
  449. };
  450. /** Inject <agent_memory_update> when agent MEMORY.md changes mid-session. */
  451. export const agentMemoryUpdateProvider: ReminderProviderFn = (input) => {
  452. if (!input.agentMemoryUpdate?.trim()) return undefined;
  453. return buildAgentMemoryUpdateBlock(input.agentMemoryUpdate.trim());
  454. };
  455. /** Inject <memory_summary_update> when .summary.md is regenerated mid-session. */
  456. export const memorySummaryUpdateProvider: ReminderProviderFn = (input) => {
  457. if (!input.memorySummaryUpdate?.trim()) return undefined;
  458. return buildMemorySummaryUpdateBlock(input.memorySummaryUpdate.trim());
  459. };
  460. /** Inject <daily_memory_update> when daily digest changes mid-session. */
  461. export const dailyMemoryUpdateProvider: ReminderProviderFn = (input) => {
  462. if (!input.dailyMemoryUpdate?.trim()) return undefined;
  463. return buildDailyMemoryUpdateBlock(input.dailyMemoryUpdate.trim());
  464. };
  465. /** Inject <identity_update> when identity changes mid-session. */
  466. export const identityUpdateProvider: ReminderProviderFn = (input) => {
  467. if (!input.identityUpdate?.display_name) return undefined;
  468. return buildIdentityUpdateBlock(input.identityUpdate);
  469. };
  470. /** Inject <config_update> when agent config files change mid-session. */
  471. export const configUpdateProvider: ReminderProviderFn = (input) => {
  472. if (!input.configUpdate) return undefined;
  473. return buildConfigUpdateBlock();
  474. };
  475. /** Inject inbound message metadata block. */
  476. export const inboundMetaProvider: ReminderProviderFn = (input) => {
  477. if (!input.inboundMeta || Object.keys(input.inboundMeta).length === 0) return undefined;
  478. return buildInboundMetaBlock(input.inboundMeta);
  479. };
  480. /** Inject <skill-evolution-channels> teaching block when skill-evolve is enabled.
  481. * Only on the first message — agents don't need re-teaching every turn.
  482. * Excluded agents (e.g. skill-editor) never see this block.
  483. *
  484. * The proposal section inside the block is independently gated by
  485. * `input.skillProposalEnabled` — when proposal is off, only the Signal
  486. * section is rendered (parent gate `skillEvolveEnabled` still on).
  487. */
  488. export const skillEvolutionChannelsProvider: ReminderProviderFn = (input) => {
  489. if (input.turnCount !== undefined && input.turnCount !== 1) return undefined; // first message only
  490. if (!input.skillEvolveEnabled) return undefined;
  491. return buildSkillEvolutionChannelsBlock({
  492. skillProposalEnabled: input.skillProposalEnabled === true,
  493. });
  494. };
  495. /**
  496. * @deprecated Renamed to `skillEvolutionChannelsProvider` in v3. The export
  497. * is retained as an alias so external imports keep compiling during the
  498. * rename window — remove in a follow-up cleanup.
  499. */
  500. export const skillSignalReportingProvider = skillEvolutionChannelsProvider;
  501. // teamModeProvider — removed: team-mode hint is now injected directly into system_prompt
  502. // via transformSystemPrompt() in the legacy local-runtime plugin for better reliability.
  503. // ─── Async Audit Provider ────────────────────────────────────────────────────
  504. //
  505. // Periodically reminds agents to check for unmonitored async operations.
  506. //
  507. // Schedule: inject on turn 1, then every N turns with exponential backoff:
  508. // 5 → 10 → 20 → 20 → 20... (cap at 20)
  509. //
  510. // Reset triggers:
  511. // - Compaction: turnCount drops below lastInjectedAt → reset + inject
  512. // - New session (no state yet) → inject on first turn
  513. //
  514. // State is in-process memory, keyed by sessionId. Non-persistent intentionally.
  515. interface AsyncAuditState {
  516. lastInjectedAt: number;
  517. backoffLevel: number;
  518. }
  519. const asyncAuditState = new Map<string, AsyncAuditState>();
  520. /** Default backoff schedule: 5, 10, 20 (cap). Apollo `intervals` overrides this. */
  521. const ASYNC_AUDIT_DEFAULTS = [5, 10, 20] as const;
  522. /** Test helper — clear async audit state. */
  523. export function _resetAsyncAuditStateForTests(): void {
  524. asyncAuditState.clear();
  525. }
  526. /**
  527. * Inject <async-audit> reminder on a turn-based schedule with exponential backoff.
  528. *
  529. * - Always fires on turn 1 (session start)
  530. * - Then every 5 → 10 → 20 → 20... turns (default; Apollo `intervals` overrides)
  531. * - Resets when turnCount drops (compaction detected)
  532. * - Silent when the host has no Cron capability (`cronEnabled === false`)
  533. */
  534. export const asyncAuditProvider: ReminderProviderFn = (input) => {
  535. if (input.mavisEnabled === false) return undefined;
  536. // The block's external follow-up path depends on Cron. Hosts without Cron
  537. // (embedded CLI) would otherwise be told every session to call a command
  538. // that fails closed with CRON_UNSUPPORTED_HOST.
  539. if (input.cronEnabled === false) return undefined;
  540. const turn = input.turnCount ?? 0;
  541. if (turn < 1) return undefined;
  542. const sessionId = input.env?.sessionId ?? 'unknown';
  543. const state = asyncAuditState.get(sessionId);
  544. const policy = findReminderPolicy(input, 'asyncAuditProvider');
  545. const overrideIntervals = policy?.frequency?.intervals;
  546. const sceneOpts = { scene: input.env?.scene };
  547. // First turn or no state → inject and initialize
  548. if (turn <= 1 || !state) {
  549. asyncAuditState.set(sessionId, { lastInjectedAt: turn, backoffLevel: 0 });
  550. return buildAsyncAuditBlock(sceneOpts);
  551. }
  552. // Compaction detected: turnCount dropped below last injection point → reset
  553. if (turn < state.lastInjectedAt) {
  554. asyncAuditState.set(sessionId, { lastInjectedAt: turn, backoffLevel: 0 });
  555. return buildAsyncAuditBlock(sceneOpts);
  556. }
  557. // Check if enough turns have elapsed for the next injection
  558. const interval = effectiveInterval(state.backoffLevel, overrideIntervals, ASYNC_AUDIT_DEFAULTS);
  559. if (turn - state.lastInjectedAt >= interval) {
  560. asyncAuditState.set(sessionId, {
  561. lastInjectedAt: turn,
  562. backoffLevel: state.backoffLevel + 1,
  563. });
  564. return buildAsyncAuditBlock(sceneOpts);
  565. }
  566. return undefined;
  567. };
  568. // ─── Media Output Reminder Provider ──────────────────────────────────────────
  569. //
  570. // Periodically reminds agents to deliver files using the current surface's
  571. // system-prompt protocol and verify their current state.
  572. //
  573. // Schedule: inject on turn 1, then every N turns with exponential backoff:
  574. // 10 → 20 → 40 → 40 → 40... (cap at 40)
  575. //
  576. // Audience: orchestrator or manually-created agents only — workers don't
  577. // send deliverables directly to the user.
  578. interface MediaOutputState {
  579. lastInjectedAt: number;
  580. backoffLevel: number;
  581. }
  582. const mediaOutputState = new Map<string, MediaOutputState>();
  583. /** Default backoff schedule: 10, 20, 40 (cap). Apollo `intervals` overrides this. */
  584. const MEDIA_OUTPUT_DEFAULTS = [10, 20, 40] as const;
  585. /** Test helper — clear media output state. */
  586. export function _resetMediaOutputStateForTests(): void {
  587. mediaOutputState.clear();
  588. }
  589. /**
  590. * Inject <media-output-reminder> on a turn-based schedule with exponential backoff.
  591. *
  592. * - Always fires on turn 1 (session start)
  593. * - Then every 10 → 20 → 40 → 40... turns (default; Apollo `intervals` overrides)
  594. * - Resets when turnCount drops (compaction detected)
  595. * - Only for orchestrators or manually-created agents
  596. */
  597. export const mediaOutputReminderProvider: ReminderProviderFn = (input) => {
  598. const turn = input.turnCount ?? 0;
  599. if (turn < 1) return undefined;
  600. // Only for orchestrator or manual agents — workers don't send deliverables to users
  601. if (input.env?.agentRole !== 'orchestrator' && input.creationSource !== 'manual') {
  602. return undefined;
  603. }
  604. const sessionId = input.env?.sessionId ?? 'unknown';
  605. const state = mediaOutputState.get(sessionId);
  606. const policy = findReminderPolicy(input, 'mediaOutputReminderProvider');
  607. const overrideIntervals = policy?.frequency?.intervals;
  608. // First turn or no state → inject and initialize
  609. if (turn <= 1 || !state) {
  610. mediaOutputState.set(sessionId, { lastInjectedAt: turn, backoffLevel: 0 });
  611. return buildMediaOutputReminderBlock({ scene: input.env?.scene });
  612. }
  613. // Compaction detected: turnCount dropped below last injection point → reset
  614. if (turn < state.lastInjectedAt) {
  615. mediaOutputState.set(sessionId, { lastInjectedAt: turn, backoffLevel: 0 });
  616. return buildMediaOutputReminderBlock({ scene: input.env?.scene });
  617. }
  618. // Check if enough turns have elapsed for the next injection
  619. const interval = effectiveInterval(state.backoffLevel, overrideIntervals, MEDIA_OUTPUT_DEFAULTS);
  620. if (turn - state.lastInjectedAt >= interval) {
  621. mediaOutputState.set(sessionId, {
  622. lastInjectedAt: turn,
  623. backoffLevel: state.backoffLevel + 1,
  624. });
  625. return buildMediaOutputReminderBlock({ scene: input.env?.scene });
  626. }
  627. return undefined;
  628. };
  629. // ─── Secret Env Reminder Provider ────────────────────────────────────────────
  630. //
  631. // Tells the agent which encrypted secret env var names are available this
  632. // turn (e.g. `OPENAI_API_KEY`). The values themselves are never surfaced —
  633. // they're resolved at shell-command time by the cloud-runtime export prefix
  634. // and masked on outbound text by SecretMasker.
  635. //
  636. // Schedule: emit on turn 1 (cold start) and whenever the sorted name set
  637. // has changed since the last emission for this session. Steady-state turns
  638. // stay silent so we don't reprint the same list every turn.
  639. //
  640. // State: per-session djb2 hash of the sorted name list, kept in process
  641. // memory. Non-persistent — mirrors the rest of this module. Resets when a
  642. // session is removed (collector takes care of that for memoryDeltaTracker
  643. // etc.; this state map relies on the cooldown/hash table never growing
  644. // without bound because it's keyed by the same finite session set).
  645. //
  646. // Empty store → return undefined (no point reminding the agent about
  647. // nothing). Source data must be a NAME LIST ONLY — the caller MUST NOT pass
  648. // secret values into `SystemReminderInput.secretNames`.
  649. interface SecretEnvReminderState {
  650. /** djb2 hash of the sorted name list at last injection. */
  651. hash: number;
  652. }
  653. const secretEnvReminderState = new Map<string, SecretEnvReminderState>();
  654. /** djb2 hash — same primitive the cloud-runtime peer-change detector uses. */
  655. function djb2Hash(str: string): number {
  656. let hash = 5381;
  657. for (let i = 0; i < str.length; i++) {
  658. hash = ((hash << 5) + hash + str.charCodeAt(i)) | 0;
  659. }
  660. return hash >>> 0;
  661. }
  662. /** Test helper — clear secret-env-reminder state across all sessions. */
  663. export function _resetSecretEnvReminderStateForTests(): void {
  664. secretEnvReminderState.clear();
  665. }
  666. /**
  667. * Inject <secret-env> on turn 1 and whenever the secret name set changes
  668. * mid-session. Stays silent when:
  669. * - `secretNames` is undefined (daemon / legacy path with no SecretStore wiring)
  670. * - `secretNames` is empty (cloud store wired but no secrets configured)
  671. * - The sorted name set is identical to the last emission for this session
  672. * AND we're not on turn 1
  673. *
  674. * Names are sorted before hashing AND before rendering — same sort order
  675. * keeps the block visually stable across turns and the hash deterministic
  676. * regardless of the input order the host happens to supply.
  677. */
  678. export const secretEnvReminderProvider: ReminderProviderFn = (input) => {
  679. if (input.secretNames === undefined) return undefined;
  680. if (input.secretNames.length === 0) return undefined;
  681. const sessionId = input.env?.sessionId ?? 'unknown';
  682. const sorted = [...input.secretNames].sort();
  683. const hash = djb2Hash(sorted.join('|'));
  684. const state = secretEnvReminderState.get(sessionId);
  685. const turn = input.turnCount ?? 0;
  686. const firstTurn = turn <= 1 || !state;
  687. const namesChanged = !!state && state.hash !== hash;
  688. if (!firstTurn && !namesChanged) return undefined;
  689. secretEnvReminderState.set(sessionId, { hash });
  690. boundMap(secretEnvReminderState);
  691. return buildSecretEnvBlock(sorted);
  692. };
  693. // ─── Board Nudge Provider (closure-based) ────────────────────────────────────
  694. //
  695. // Created by the container and appended to the registry after construction.
  696. // Captures a NudgeRegistry reference so it can read pending nudge flags set
  697. // by BoardWatcher without adding a new field to SystemReminderInput.
  698. //
  699. // Flow:
  700. // 1. BoardWatcher sets a nudge flag in the registry
  701. // 2. On the worker's next tool-result turn, this provider reads and clears it
  702. // 3. The <engine-nudge> block appears inside <system-reminder>
  703. // 4. The agent sees it and (hopefully) updates the board
  704. /**
  705. * Create a board-nudge provider that reads from the given NudgeRegistry.
  706. * The provider injects an <engine-nudge> block when a session has a pending nudge,
  707. * then clears the flag so the agent sees it exactly once per nudge cycle.
  708. */
  709. export function createBoardNudgeProvider(nudgeRegistry: NudgeRegistry): ReminderProviderFn {
  710. return (input: SystemReminderInput) => {
  711. if (!input.env?.sessionId) return undefined;
  712. const nudge = nudgeRegistry.get(input.env.sessionId);
  713. if (!nudge) return undefined;
  714. // Clear after injection — one-shot delivery per nudge cycle.
  715. // If the agent still doesn't update the board, BoardWatcher will set
  716. // another nudge on the next poll.
  717. nudgeRegistry.clear(input.env.sessionId);
  718. return buildBoardNudgeBlock(nudge.boardPath);
  719. };
  720. }
  721. // ─── Default Registry Factory ────────────────────────────────────────────────
  722. /**
  723. * Create a SystemReminderRegistry pre-loaded with all default providers.
  724. *
  725. * The default set is framework-agnostic — every provider runs for all framework
  726. * types. Use `registry.appendFor(frameworkType, fn)` after creation to add
  727. * framework-specific providers.
  728. *
  729. * Provider execution order matches the block order in <system-reminder>.
  730. *
  731. * @param formatLocalDateTime host-injected local-date formatter (the host owns
  732. * the timezone) used by the branch-finish-alert provider.
  733. */
  734. export function createDefaultRegistry(formatLocalDateTime: DateFormatter): SystemReminderRegistry {
  735. return (
  736. new SystemReminderRegistry()
  737. .append('agentContextProvider', agentContextProvider)
  738. .append('peersUpdateProvider', peersUpdateProvider)
  739. .append('activePlanReminderProvider', activePlanReminderProvider)
  740. .append('memorySkillReminderProvider', memorySkillReminderProvider)
  741. .append('proactiveMemoryProvider', proactiveMemoryProvider)
  742. .append('memoryTopicsProvider', memoryTopicsProvider)
  743. .append('cliSunsetMemoryNoticeProvider', cliSunsetMemoryNoticeProvider)
  744. .append('personaMissingProvider', personaMissingProvider)
  745. .append('branchNotificationProvider', createBranchNotificationProvider(formatLocalDateTime))
  746. .appendCritical('pendingSessionRemindersProvider', pendingSessionRemindersProvider)
  747. .appendCritical('taskCompletionReminderProvider', taskCompletionReminderProvider)
  748. .append('evolutionReminderProvider', evolutionReminderProvider)
  749. .append('bootstrapProvider', bootstrapProvider)
  750. .append('worktreeReminderProvider', worktreeReminderProvider)
  751. .append('teamMemoryProvider', teamMemoryProvider)
  752. // relevantMemoryProvider removed — low relevance precision wastes ~500-1000 tokens/turn
  753. .append('userMemoryUpdateProvider', userMemoryUpdateProvider)
  754. .append('agentMemoryUpdateProvider', agentMemoryUpdateProvider)
  755. .append('memorySummaryUpdateProvider', memorySummaryUpdateProvider)
  756. .append('dailyMemoryUpdateProvider', dailyMemoryUpdateProvider)
  757. .append('identityUpdateProvider', identityUpdateProvider)
  758. .append('configUpdateProvider', configUpdateProvider)
  759. .append('inboundMetaProvider', inboundMetaProvider)
  760. .append('skillEvolutionChannelsProvider', skillEvolutionChannelsProvider)
  761. .appendCritical('mediaOutputReminderProvider', mediaOutputReminderProvider)
  762. .appendCritical('asyncAuditProvider', asyncAuditProvider)
  763. .append('secretEnvReminderProvider', secretEnvReminderProvider)
  764. );
  765. }