service.ts 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. /**
  2. * SystemReminderService — framework-aware system-reminder injection.
  3. *
  4. * Called by SessionBridge.sendMessage() before dispatching to any adapter.
  5. * Uses a SystemReminderRegistry (chain-of-responsibility) to run registered
  6. * providers and assemble their outputs into a <system-reminder> block.
  7. *
  8. * Different AgentFrameworkType can have different provider chains — the
  9. * registry resolves which providers to run based on the session's framework.
  10. */
  11. import { performance } from 'node:perf_hooks';
  12. import type { SystemReminderRegistry } from './registry.js';
  13. import type { MemoryDirSnapshot, SessionInfo, MessageRequest } from './types.js';
  14. import type {
  15. DataCollector,
  16. ModelSelector,
  17. Logger,
  18. LogContext,
  19. ReminderConfig,
  20. SystemReminderDiagnostic,
  21. ProviderDiagnostic,
  22. } from './dependencies.js';
  23. import { getEvolutionReminder, boundMap } from './evolution.js';
  24. import type { EvolutionState } from './evolution.js';
  25. import { touchTodoStateTurn } from './todo-state.js';
  26. import { stripProviderSuffix } from './providers.js';
  27. export class SystemReminderService implements EvolutionState {
  28. // ── Turn tracking ──
  29. private readonly turnCounts = new Map<string, number>();
  30. // ── Evolution state (used exclusively by getEvolutionReminder) ──
  31. readonly memorySnapshots = new Map<string, MemoryDirSnapshot>();
  32. readonly lastSkillReminderAt = new Map<string, number>();
  33. readonly nextMemoryReminderAt = new Map<string, number>();
  34. readonly memoryReminderGap = new Map<string, number>();
  35. readonly nextSkillReminderAt = new Map<string, number>();
  36. readonly skillReminderGap = new Map<string, number>();
  37. constructor(
  38. private readonly collector: DataCollector,
  39. private readonly registry: SystemReminderRegistry,
  40. private readonly dataDir: string,
  41. /**
  42. * Host logging surface, injected so this package never imports a runtime
  43. * logger.
  44. */
  45. private readonly logger: Logger,
  46. /**
  47. * Factory for the per-call log context (trace id etc.). Invoked for each
  48. * log line so each emission carries a fresh context.
  49. */
  50. private readonly logCtx: () => LogContext,
  51. /**
  52. * Config slice read by the service — currently only the model-prefix
  53. * disable list that gates the skill-evolve model preview.
  54. */
  55. private readonly config: ReminderConfig,
  56. /**
  57. * Models for which the per-message `<system-reminder>` block is fully
  58. * suppressed. When the resolved model matches one of these
  59. * `"providerID/modelID"` keys, `buildReminder` returns undefined without
  60. * collecting data or running providers.
  61. *
  62. * Configured via `contextManagement.disableSystemReminderModels` in
  63. * config.yaml. Empty by default.
  64. */
  65. private readonly disableSrModels: ReadonlySet<string> = new Set(),
  66. /**
  67. * Optional reference to the model selector for previewing the resolved
  68. * model (dryRun) before SR injection. Required when `disableSrModels` is
  69. * non-empty so we can dispatch on the SAME model that the bridge will
  70. * eventually commit, regardless of whether the caller passed `msg.model`
  71. * explicitly.
  72. */
  73. private readonly modelSelectionService?: ModelSelector,
  74. ) {}
  75. /**
  76. * Build the full <system-reminder> block for a message being sent to a session.
  77. * Returns undefined if no reminders are needed.
  78. *
  79. * When diagnostics are explicitly requested via `options.withDiagnostic`,
  80. * also returns a SystemReminderDiagnostic via the second element of the
  81. * returned tuple.
  82. */
  83. async buildReminder(
  84. session: SessionInfo,
  85. msg: MessageRequest,
  86. options?: { withDiagnostic?: boolean },
  87. ): Promise<{ text: string | undefined; diagnostic?: SystemReminderDiagnostic }> {
  88. const diagEnabled = options?.withDiagnostic === true;
  89. const totalStart = diagEnabled ? performance.now() : 0;
  90. let criticalOnly = false;
  91. let disabledModelKey: string | undefined;
  92. let resolvedModelID: string | undefined;
  93. // Resolve model once — used for both SR disable check and skill-evolve model gating.
  94. const disableModelPrefixes = this.config.disableModelPrefixes;
  95. const needsModelPreview =
  96. (this.disableSrModels.size > 0 || disableModelPrefixes.length > 0) &&
  97. this.modelSelectionService;
  98. if (needsModelPreview) {
  99. try {
  100. const final = await this.modelSelectionService!.resolveForSend({
  101. sessionId: session.sessionId,
  102. agentName: session.agentName,
  103. requestModel: msg.model,
  104. dryRun: true,
  105. });
  106. resolvedModelID = final.modelID;
  107. const modelKey = `${final.providerID}/${final.modelID}`;
  108. if (this.disableSrModels.has(modelKey)) {
  109. criticalOnly = true;
  110. disabledModelKey = modelKey;
  111. }
  112. } catch (err) {
  113. this.logger.warn(
  114. this.logCtx(),
  115. `Failed to preview model for SR disable check — running normal pipeline sessionId=${session.sessionId} err=${err instanceof Error ? err.message : String(err)}`,
  116. );
  117. }
  118. }
  119. try {
  120. // 1. Increment turn counter
  121. const turnCount = this.incrementTurn(session.sessionId);
  122. // 2. Collect all dynamic data from stores/filesystem
  123. const collectStart = diagEnabled ? performance.now() : 0;
  124. const data = await this.collector.collect(session, msg, turnCount);
  125. const collectDurationMs = diagEnabled ? performance.now() - collectStart : 0;
  126. // 2b. Per-model skill-evolve gating
  127. if (data.skillEvolveEnabled && resolvedModelID && disableModelPrefixes.length > 0) {
  128. if (disableModelPrefixes.some((p) => resolvedModelID!.startsWith(p))) {
  129. data.skillEvolveEnabled = false;
  130. // Proposal trigger requires skill-evolve as parent gate; cascade.
  131. data.skillProposalEnabled = false;
  132. }
  133. }
  134. if (data.activeTodoState) {
  135. touchTodoStateTurn(session.sessionId, turnCount);
  136. data.activeTodoState.lastUpdatedTurn = turnCount;
  137. }
  138. // 3. Compute evolution reminder
  139. data.evolutionReminder = getEvolutionReminder(
  140. data.agentMemorySnapshot,
  141. session.sessionId,
  142. session.agentName,
  143. turnCount,
  144. this,
  145. );
  146. // 4. Run providers — with optional diagnostic capture.
  147. //
  148. // Per-turn allowlist gate (cloud-runtime path):
  149. // `data.systemReminders` is sourced from `AgentConfig.system_reminders`
  150. // (IDL field 19). When undefined (daemon / legacy callers), every
  151. // registered provider runs — preserves existing behaviour. When an
  152. // empty array or non-empty array is supplied (cloud-runtime always
  153. // supplies one), we filter the registry chain so only providers whose
  154. // stripped name matches an entry are executed. `critical` providers
  155. // are NOT bypassed; they go through the same gate per the design
  156. // `system-reminders-from-agent-config.md` Q2.
  157. const baseProviders = criticalOnly
  158. ? this.registry.resolveCritical(session.frameworkType)
  159. : this.registry.resolve(session.frameworkType);
  160. const allowlist = data.systemReminders;
  161. const allowedNames = allowlist ? new Set(allowlist.map((e) => e.name)) : null;
  162. const namedProviders = allowedNames
  163. ? baseProviders.filter((np) => allowedNames.has(stripProviderSuffix(np.name)))
  164. : baseProviders;
  165. const blocks: string[] = [];
  166. const providerDiagnostics: ProviderDiagnostic[] = [];
  167. for (const np of namedProviders) {
  168. const pStart = diagEnabled ? performance.now() : 0;
  169. const result = await np.fn(data);
  170. const pDuration = diagEnabled ? performance.now() - pStart : 0;
  171. const trimmed = result?.trim() || undefined;
  172. if (trimmed) {
  173. blocks.push(trimmed);
  174. }
  175. if (diagEnabled) {
  176. providerDiagnostics.push({
  177. name: np.name,
  178. fired: !!trimmed,
  179. output: trimmed,
  180. durationMs: Math.round(pDuration * 100) / 100,
  181. critical: np.critical,
  182. });
  183. }
  184. }
  185. if (criticalOnly) {
  186. this.logger.info(
  187. this.logCtx(),
  188. `SR injection limited to critical providers sessionId=${session.sessionId} modelKey=${disabledModelKey ?? 'unknown'} providers=${namedProviders.length} blocks=${blocks.length}`,
  189. );
  190. }
  191. const fullText =
  192. blocks.length === 0
  193. ? null
  194. : `<system-reminder>\n${blocks.join('\n\n')}\n</system-reminder>`;
  195. const diagnostic: SystemReminderDiagnostic | undefined = diagEnabled
  196. ? {
  197. fullText,
  198. criticalOnly,
  199. providers: providerDiagnostics,
  200. collectDurationMs: Math.round(collectDurationMs * 100) / 100,
  201. totalDurationMs: Math.round((performance.now() - totalStart) * 100) / 100,
  202. }
  203. : undefined;
  204. return { text: fullText ?? undefined, diagnostic };
  205. } catch (err) {
  206. this.logger.error(
  207. this.logCtx(),
  208. `Failed to build system reminder sessionId=${session.sessionId} err=${err instanceof Error ? err.message : String(err)}`,
  209. );
  210. return { text: undefined };
  211. }
  212. }
  213. /** Get the current turn count for a session (used by debug store). */
  214. getTurnCount(sessionId: string): number {
  215. return this.turnCounts.get(sessionId) ?? 0;
  216. }
  217. /** Clean up state when a session is removed. */
  218. onSessionRemoved(sessionId: string): void {
  219. this.turnCounts.delete(sessionId);
  220. this.memorySnapshots.delete(sessionId);
  221. this.lastSkillReminderAt.delete(sessionId);
  222. this.nextMemoryReminderAt.delete(sessionId);
  223. this.memoryReminderGap.delete(sessionId);
  224. this.nextSkillReminderAt.delete(sessionId);
  225. this.skillReminderGap.delete(sessionId);
  226. this.collector.onSessionRemoved(sessionId);
  227. }
  228. // ── Private helpers ──
  229. private incrementTurn(sessionId: string): number {
  230. const count = (this.turnCounts.get(sessionId) ?? 0) + 1;
  231. this.turnCounts.set(sessionId, count);
  232. boundMap(this.turnCounts);
  233. return count;
  234. }
  235. }