executor.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  1. import type { ChannelPlatform, InboundContext } from '@mavis/shared';
  2. import {
  3. formatCronRunTitle,
  4. MEMORY_CLEANUP_CRON_NAME,
  5. parseCronSessionPurpose,
  6. } from '@mavis/shared/cron-purpose';
  7. import {
  8. logger,
  9. backgroundCtx,
  10. AppError,
  11. getMetricsReporter,
  12. nowMs,
  13. getCronStore,
  14. getSessionLifecycle,
  15. getAgentSpawner,
  16. getChannelDelivery,
  17. getMessageQueue,
  18. type CronHostUtils,
  19. } from './host-utils.js';
  20. import {
  21. CRON_MESSAGE_LANE,
  22. CronSessionType,
  23. Role,
  24. type AgentSpawnerPort,
  25. type ChannelDeliveryPort,
  26. type CronEventBusPort,
  27. type CronSessionBridgePort,
  28. type CronSessionRecord,
  29. type CronStorePort,
  30. type MessageQueuePort,
  31. type SessionLifecyclePort,
  32. } from './host-ports.js';
  33. import type { CronTaskState } from './types.js';
  34. import type { CronDeliveryTarget, CronTriggerSource } from './registry.js';
  35. import { normalizeSessionConfig, resolveReportToRoot } from './types.js';
  36. import { isWithinActiveHours } from './active-hours.js';
  37. import { BusyQueue, type BusyQueueDrainResult } from './busy-queue.js';
  38. import {
  39. IM_AUTO_DELIVERY_PROMPT_NOTE,
  40. collectCronTurnText,
  41. deliverToAllBoundChannels,
  42. deliverToChannel,
  43. supportsImAutoDelivery,
  44. } from './report-delivery.js';
  45. /**
  46. * Default retention when `keepSessions` is omitted: `null` = keep all
  47. * sessions visible (no auto-archive). Users opt-in to auto-archive by
  48. * explicitly setting `keepSessions` to a positive integer.
  49. */
  50. const DEFAULT_KEEP_SESSIONS: number | null = null;
  51. export interface ExecuteResult {
  52. executed: boolean;
  53. reason?: string;
  54. sessionId?: string;
  55. queuedSend?: Promise<BusyQueueDrainResult>;
  56. }
  57. export class CronExecutor {
  58. private readonly busyQueue = new BusyQueue();
  59. /**
  60. * Per `(agentName, cronName)` lock to serialise read-modify-write of the
  61. * cron's session history JSON. All append + cleanup paths must go through
  62. * this lock; otherwise an `appendSessionRun` interleaved with a
  63. * `replaceSessionHistory` could lose new records or overwrite the latest
  64. * history.
  65. */
  66. private readonly historyLocks = new Map<string, Promise<void>>();
  67. constructor(
  68. private readonly sessionBridge: CronSessionBridgePort,
  69. private readonly eventBus?: CronEventBusPort,
  70. private readonly cronHost: CronHostUtils = {},
  71. ) {
  72. // Drain BusyQueue on ANY terminal event — not just session.finish.
  73. // When the in-flight turn ends via error or abort, the cron prompt
  74. // that got latest-wins-enqueued during the active window must still
  75. // get a chance to dispatch; otherwise it sits in the queue forever
  76. // (next finish never comes if the session is now idle).
  77. const drainOnTerminal = (event: { payload?: unknown }) => {
  78. const sid = (event.payload as { sessionId?: string } | undefined)?.sessionId;
  79. if (sid) {
  80. void this.busyQueue.drain(sid);
  81. }
  82. };
  83. this.eventBus?.on('session.finish', (event) => {
  84. drainOnTerminal(event);
  85. // Cleanup is intentionally not scoped to the finished sessionId — the
  86. // persisted JSON is the source of truth, not in-memory state. Walk
  87. // every cron and let the algorithm decide what to archive.
  88. void this.cleanupAllCronSessions();
  89. });
  90. // session.error and session.abort both use a source allow-list rather
  91. // than reacting to every emitter, because the same event names are
  92. // emitted by non-turn-terminal sources. The daemon `CronExecutor`
  93. // dropped BusyQueue entirely in favour of `SessionInboundQueue`;
  94. // cloud-runtime keeps BusyQueue here (no SessionInboundQueue
  95. // equivalent yet) but mirrors the same source filters so a
  96. // session-title-service `session.error` cannot drain the cron queue
  97. // mid-turn, and a session-service `session.abort` cannot race a
  98. // queued cron prompt ahead of the user's immediate-message follow-up.
  99. this.eventBus?.on('session.error', (event) => {
  100. if (event.source !== 'session-bridge') return;
  101. drainOnTerminal(event);
  102. });
  103. this.eventBus?.on('session.abort', (event) => {
  104. if (event.source === 'session-service') return;
  105. drainOnTerminal(event);
  106. });
  107. }
  108. cancelQueuedCron(agentName: string, cronName: string): number {
  109. return this.busyQueue.removeCron(agentName, cronName);
  110. }
  111. private resolveCronStore(): CronStorePort {
  112. return this.cronHost.cronStore ?? getCronStore();
  113. }
  114. private resolveSessionLifecycle(): SessionLifecyclePort {
  115. return this.cronHost.sessionLifecycle ?? getSessionLifecycle();
  116. }
  117. private resolveAgentSpawner(): AgentSpawnerPort {
  118. return this.cronHost.agentSpawner ?? getAgentSpawner();
  119. }
  120. private resolveChannelDelivery(): ChannelDeliveryPort | undefined {
  121. return this.cronHost.channelDelivery ?? getChannelDelivery();
  122. }
  123. private resolveMessageQueue(): MessageQueuePort | undefined {
  124. return this.cronHost.messageQueue ?? getMessageQueue();
  125. }
  126. async execute(
  127. state: CronTaskState,
  128. options?: {
  129. force?: boolean;
  130. /** @deprecated Trigger dimensions are recorded by CronRegistry. */
  131. triggerSource?: CronTriggerSource;
  132. /** @deprecated Trigger dimensions are recorded by CronRegistry. */
  133. deliveryTarget?: CronDeliveryTarget;
  134. },
  135. ): Promise<ExecuteResult> {
  136. const ctx = backgroundCtx();
  137. const cronStartMs = Date.now();
  138. const force = options?.force ?? false;
  139. // Pre-checks (skipped when force=true for manual triggers)
  140. if (!force && !state.enabled) {
  141. logger.debug(
  142. ctx,
  143. `[cron] Skipping disabled task: agent=${state.agentName} cron=${state.cronName}`,
  144. );
  145. return { executed: false, reason: 'disabled' };
  146. }
  147. if (!force) {
  148. try {
  149. if (!isWithinActiveHours(state.config.activeHours, state.config.timezone)) {
  150. logger.debug(
  151. ctx,
  152. `[cron] Skipping — outside active hours: agent=${state.agentName} cron=${state.cronName}`,
  153. );
  154. return { executed: false, reason: 'outside_active_hours' };
  155. }
  156. } catch (err) {
  157. logger.error(
  158. ctx,
  159. `[cron] Invalid timezone in activeHours config: agent=${state.agentName} cron=${state.cronName} err=${(err as Error).message}`,
  160. );
  161. return { executed: false, reason: 'invalid_timezone' };
  162. }
  163. }
  164. if (state.status === 'running') {
  165. logger.debug(
  166. ctx,
  167. `[cron] Skipping — already running: agent=${state.agentName} cron=${state.cronName}`,
  168. );
  169. return { executed: false, reason: 'already_running' };
  170. }
  171. state.status = 'running';
  172. let sessionId: string | undefined;
  173. const sessionService = this.resolveSessionLifecycle();
  174. const agentService = this.resolveAgentSpawner();
  175. const cronStore = this.resolveCronStore();
  176. const messageQueue = this.resolveMessageQueue();
  177. try {
  178. // Resolve session — normalize legacy 'main' → 'root'
  179. const sessionCfg = normalizeSessionConfig(state.config.session);
  180. if (sessionCfg.mode === 'root') {
  181. const rootSession = await sessionService.getRootSession(state.agentName);
  182. if (!rootSession) {
  183. throw new AppError(
  184. `No root session found for agent '${state.agentName}'`,
  185. 'SESSION_NOT_FOUND',
  186. 404,
  187. );
  188. }
  189. sessionId = rootSession.sessionId;
  190. } else if (sessionCfg.mode === 'sessionId') {
  191. const sid = sessionCfg.sessionId;
  192. const session = await sessionService.getSession(sid);
  193. if (!session) {
  194. throw new AppError(
  195. `Session '${sid}' not found for agent '${state.agentName}'`,
  196. 'SESSION_NOT_FOUND',
  197. 404,
  198. );
  199. }
  200. sessionId = sid;
  201. } else {
  202. // mode === 'new'
  203. const newResult = await agentService.newSession(
  204. backgroundCtx(),
  205. state.agentName,
  206. undefined, // workspaceDir
  207. undefined, // parentSessionId
  208. undefined, // title
  209. undefined, // taskTreeId
  210. undefined, // teamModeOff
  211. { purpose: `cron:${state.agentName}:${state.cronName}` },
  212. );
  213. sessionId = newResult.sessionId;
  214. try {
  215. await sessionService.seedGeneratedTitle?.(sessionId, formatCronRunTitle(state.cronName), {
  216. onlyIfEmpty: true,
  217. });
  218. } catch (err) {
  219. logger.warn(
  220. {
  221. sessionId,
  222. cronName: state.cronName,
  223. err: err instanceof Error ? err.message : String(err),
  224. },
  225. 'Failed to seed cron session title',
  226. );
  227. }
  228. }
  229. // Record history for all modes. Cleanup only for 'new' mode
  230. // (main/sessionId reuse existing sessions that should not be archived).
  231. await this.runUnderHistoryLock(state.agentName, state.cronName, async () => {
  232. await cronStore.appendSessionRun(state.agentName, state.cronName, {
  233. sessionId: sessionId!,
  234. createdAt: nowMs(),
  235. });
  236. if (sessionCfg.mode === 'new') {
  237. await this.cleanupCronSessionsLocked(state.agentName, state.cronName);
  238. }
  239. });
  240. // Build sendTask closure (needed for both enqueue and normal execution paths).
  241. // Delivery listeners are installed inside the closure so queued sends do
  242. // not start their response timeout before the prompt is dispatched.
  243. const sendTask = async () => {
  244. const autoDeliveryEnabled =
  245. resolveReportToRoot(state.config) ?? state.config.session.mode === 'new';
  246. const imAutoDelivery =
  247. autoDeliveryEnabled && !state.config.delivery && supportsImAutoDelivery(this.cronHost);
  248. // Set up response listener BEFORE sending so it's ready to capture the response
  249. if (state.config.delivery && this.resolveChannelDelivery()) {
  250. this.setupDeliveryListener(state, sessionId!);
  251. } else if (imAutoDelivery) {
  252. this.setupAutoDeliveryListener(state, sessionId!);
  253. }
  254. // When IM auto-delivery is active, instruct the agent not to send
  255. // to IM itself — deliverToAllBoundChannels handles it after the turn.
  256. const promptContent = imAutoDelivery
  257. ? `${state.config.prompt}\n\n${IM_AUTO_DELIVERY_PROMPT_NOTE}`
  258. : state.config.prompt;
  259. const inboundContext: InboundContext = {
  260. platform: 'system' as ChannelPlatform,
  261. chatType: 'p2p',
  262. isGroupChat: false,
  263. accountName: 'cron-executor',
  264. senderId: 'system',
  265. messageId: `cron:${state.cronName}:${Date.now()}`,
  266. hasMention: false,
  267. timestamp: Date.now(),
  268. sourceType: 'cron',
  269. cronName: state.cronName,
  270. cronSchedule: state.config.schedule,
  271. };
  272. await this.sessionBridge.sendMessage(backgroundCtx(), state.agentName, sessionId!, {
  273. content: promptContent,
  274. fromRole: Role.User,
  275. source: 'cron',
  276. inboundContext,
  277. });
  278. };
  279. // Busy check — enqueue instead of skipping.
  280. //
  281. // Three signals are combined so the OpenCode adapter's known
  282. // ~500ms inter-step idle window (where /session/status briefly
  283. // reports `not busy` between tool completion and the next LLM
  284. // inference) cannot bypass BusyQueue and inject the cron prompt
  285. // into the live turn. Mirrors `SessionInboundQueue`'s gate for
  286. // Web/IM messages (`shouldDeferDrainForBusySession`).
  287. const status = await sessionService.getSessionStatus(backgroundCtx(), sessionId);
  288. const hasActiveTurn = this.sessionBridge.hasActiveTurn?.(sessionId) === true;
  289. const hasActiveSource = this.sessionBridge.getActiveSource?.(sessionId) !== undefined;
  290. const sessionBusy = status.type === 'started' || hasActiveTurn || hasActiveSource;
  291. if (sessionBusy) {
  292. const queuedSend = this.busyQueue.enqueue(
  293. sessionId,
  294. state.agentName,
  295. state.cronName,
  296. sendTask,
  297. );
  298. logger.info(
  299. ctx,
  300. `[cron] Session busy — enqueued (latest-wins): agent=${state.agentName} cron=${state.cronName} sessionId=${sessionId} queueSize=${this.busyQueue.size()} stored=${status.type} hasActiveTurn=${hasActiveTurn} hasActiveSource=${hasActiveSource}`,
  301. );
  302. state.lastRun = nowMs();
  303. state.lastResult = 'skipped';
  304. return { executed: false, reason: 'enqueued', sessionId, queuedSend };
  305. }
  306. // Send message
  307. logger.info(
  308. ctx,
  309. `[cron] Executing task: agent=${state.agentName} cron=${state.cronName} sessionId=${sessionId}`,
  310. );
  311. this.eventBus?.emit('cron.triggered', 'cron-executor', {
  312. agentName: state.agentName,
  313. cronName: state.cronName,
  314. sessionId,
  315. });
  316. if (messageQueue) {
  317. const bucketKey = `cron:${state.agentName}:${state.cronName}`;
  318. await messageQueue.enqueue(CRON_MESSAGE_LANE, bucketKey, sendTask, {
  319. timeoutMs: 60_000,
  320. });
  321. } else {
  322. await sendTask();
  323. }
  324. state.lastRun = nowMs();
  325. state.lastResult = 'success';
  326. state.lastError = null;
  327. this.eventBus?.emit('cron.completed', 'cron-executor', {
  328. agentName: state.agentName,
  329. cronName: state.cronName,
  330. });
  331. return { executed: true, sessionId };
  332. } catch (err) {
  333. state.lastRun = nowMs();
  334. state.lastResult = 'error';
  335. state.lastError = (err as Error).message;
  336. this.eventBus?.emit('cron.failed', 'cron-executor', {
  337. agentName: state.agentName,
  338. cronName: state.cronName,
  339. error: (err as Error).message,
  340. });
  341. logger.error(
  342. ctx,
  343. `[cron] Execution failed: agent=${state.agentName} cron=${state.cronName} err=${(err as Error).message}`,
  344. );
  345. return { executed: false, reason: 'error', sessionId };
  346. } finally {
  347. state.status = 'idle';
  348. const cronResult =
  349. state.lastResult === 'skipped'
  350. ? 'skipped'
  351. : state.lastResult === 'success'
  352. ? 'success'
  353. : 'failure';
  354. // Keep the established family schema; orthogonal trigger context is
  355. // already reported by CronRegistry via cron_task_triggered_total.
  356. getMetricsReporter().incr('cron_task_executed_total', {
  357. result: cronResult,
  358. agent_name: state.agentName,
  359. });
  360. getMetricsReporter().latency('cron_task_execution_duration_ms', Date.now() - cronStartMs, {
  361. agent_name: state.agentName,
  362. });
  363. }
  364. }
  365. /**
  366. * Public retention entry point for a single cron task. Source of truth is the
  367. * persisted `<cronName>.sessions.json` — runtime in-memory state plays no part.
  368. *
  369. * Algorithm (operating on records ordered oldest-first):
  370. * - skip when cron config missing or `session.mode !== 'new'`
  371. * - drop record if session no longer exists (compacted out)
  372. * - drop record if session is already compressed (compacted out)
  373. * - keep record if session is currently `started` (not counted toward keepN, not archived)
  374. * - keep newest `keepN` visible (non-started, non-compressed) records
  375. * - archive + drop older visible records
  376. * - Root sessions encountered in the JSON are skipped with a warning and retained
  377. *
  378. * Concurrency / errors:
  379. * - Serialised against `appendSessionRun` and `cleanupAllCronSessions` via
  380. * `runUnderHistoryLock`.
  381. * - Cleanup errors (including replaceSessionHistory write failures) are
  382. * non-fatal and logged with agent/cron context — the next trigger retries.
  383. */
  384. async cleanupCronSessions(agentName: string, cronName: string): Promise<void> {
  385. await this.runUnderHistoryLock(agentName, cronName, async () => {
  386. try {
  387. await this.cleanupCronSessionsLocked(agentName, cronName);
  388. } catch (err) {
  389. logger.warn(
  390. backgroundCtx(),
  391. `[cron] Archive cleanup failed (non-fatal), agent=${agentName} cron=${cronName} err=${(err as Error).message}`,
  392. );
  393. }
  394. });
  395. }
  396. /**
  397. * Walk every cron loaded by the store and run cleanup for each one in
  398. * `session.mode === 'new'`. Triggered at daemon startup and on every
  399. * `session.finish` (we cannot cheaply tell which cron a finishing session
  400. * belongs to, and the persisted JSON is the only authoritative input).
  401. */
  402. async cleanupAllCronSessions(): Promise<void> {
  403. const ctx = backgroundCtx();
  404. const cronStore = this.resolveCronStore();
  405. let configs: Awaited<ReturnType<CronStorePort['listAll']>>;
  406. try {
  407. configs = await cronStore.listAll();
  408. } catch (err) {
  409. logger.warn(
  410. ctx,
  411. `[cron] cleanupAllCronSessions: listAll failed (non-fatal), err=${(err as Error).message}`,
  412. );
  413. return;
  414. }
  415. for (const { agentName, cronName, config } of configs) {
  416. if (config.session.mode !== 'new') continue;
  417. await this.cleanupCronSessions(agentName, cronName);
  418. }
  419. }
  420. /**
  421. * Internal cleanup body — must be invoked while already holding the
  422. * per-cron history lock. Public callers should go through
  423. * `cleanupCronSessions` (which acquires the lock + swallows errors).
  424. */
  425. private async cleanupCronSessionsLocked(agentName: string, cronName: string): Promise<void> {
  426. const ctx = backgroundCtx();
  427. const cronStore = this.resolveCronStore();
  428. const sessionService = this.resolveSessionLifecycle();
  429. const config = await cronStore.get(agentName, cronName);
  430. if (!config) return;
  431. if (config.session.mode !== 'new') return;
  432. const records = await cronStore.getSessionHistory(agentName, cronName);
  433. if (records.length === 0) return;
  434. const { keepSessions } = config.session; // undefined | null | number
  435. const effectiveKeep = keepSessions === undefined ? DEFAULT_KEEP_SESSIONS : keepSessions;
  436. // Inspect each record once.
  437. type Inspection = {
  438. record: CronSessionRecord;
  439. kind: 'missing' | 'compressed' | 'started' | 'root' | 'visible';
  440. };
  441. const inspections: Inspection[] = [];
  442. for (const record of records) {
  443. const session = await sessionService.getSession(record.sessionId).catch(() => undefined);
  444. if (!session) {
  445. inspections.push({ record, kind: 'missing' });
  446. continue;
  447. }
  448. // Defensive: a Root session never belongs in cron history (cron always
  449. // creates branch sessions). If we see one, retain + warn instead of
  450. // attempting an archive that would throw MAIN_SESSION_PROTECTED.
  451. if (session.sessionType === CronSessionType.Root) {
  452. logger.warn(
  453. ctx,
  454. `[cron] Root session in cron history — skipping archive, agent=${agentName} cron=${cronName} sessionId=${record.sessionId}`,
  455. );
  456. inspections.push({ record, kind: 'root' });
  457. continue;
  458. }
  459. if (session.compressed) {
  460. inspections.push({ record, kind: 'compressed' });
  461. continue;
  462. }
  463. if (session.status?.type === 'started') {
  464. inspections.push({ record, kind: 'started' });
  465. continue;
  466. }
  467. inspections.push({ record, kind: 'visible' });
  468. }
  469. // Archive eligibility: oldest visible records beyond keepN.
  470. // null keepSessions → keep all visible (compact missing/compressed only).
  471. const visibleIndexes: number[] = [];
  472. for (let i = 0; i < inspections.length; i++) {
  473. if (inspections[i]!.kind === 'visible') visibleIndexes.push(i);
  474. }
  475. const archiveSet = new Set<number>();
  476. if (effectiveKeep !== null) {
  477. const keepCount = effectiveKeep;
  478. if (visibleIndexes.length > keepCount) {
  479. const archiveCount = visibleIndexes.length - keepCount;
  480. for (let i = 0; i < archiveCount; i++) {
  481. archiveSet.add(visibleIndexes[i]!);
  482. }
  483. }
  484. }
  485. // Build the new persisted list and perform archives.
  486. const next: CronSessionRecord[] = [];
  487. let archived = 0;
  488. let compacted = 0;
  489. for (let i = 0; i < inspections.length; i++) {
  490. const { record, kind } = inspections[i]!;
  491. if (kind === 'started' || kind === 'root') {
  492. next.push(record);
  493. continue;
  494. }
  495. if (kind === 'missing' || kind === 'compressed') {
  496. compacted++;
  497. continue;
  498. }
  499. if (archiveSet.has(i)) {
  500. try {
  501. await sessionService.setSessionArchived(record.sessionId, true);
  502. archived++;
  503. } catch (err) {
  504. // Archive failed — keep the record so we retry next time, do not
  505. // silently lose history.
  506. logger.warn(
  507. ctx,
  508. `[cron] Failed to archive session, agent=${agentName} cron=${cronName} sessionId=${record.sessionId} err=${(err as Error).message}`,
  509. );
  510. next.push(record);
  511. }
  512. continue;
  513. }
  514. next.push(record);
  515. }
  516. // Skip the write entirely when nothing actually changed.
  517. const changed = archived > 0 || compacted > 0 || next.length !== records.length;
  518. if (!changed) return;
  519. await cronStore.replaceSessionHistory(agentName, cronName, next);
  520. logger.info(
  521. ctx,
  522. `[cron] Cleanup applied, agent=${agentName} cron=${cronName} archived=${archived} compacted=${compacted} retained=${next.length} keep=${effectiveKeep ?? 'all'}`,
  523. );
  524. }
  525. /**
  526. * Delete all cron-created sessions before a cron task is deleted.
  527. * Only deletes sessions that:
  528. * - exist
  529. * - are NOT root sessions
  530. * - have a `purpose` matching `cron:{agentName}:{cronName}`
  531. *
  532. * Best-effort: individual delete failures are logged and skipped so
  533. * deletion can proceed.
  534. */
  535. async cleanupSessionsOnDelete(agentName: string, cronName: string): Promise<void> {
  536. const ctx = backgroundCtx();
  537. const cronStore = this.resolveCronStore();
  538. const sessionService = this.resolveSessionLifecycle();
  539. const expectedPurpose = `cron:${agentName}:${cronName}`;
  540. const records = await cronStore.getSessionHistory(agentName, cronName);
  541. // Deduplicate sessionIds (root/sessionId mode may repeat the same ID)
  542. const seen = new Set<string>();
  543. let deleted = 0;
  544. let skipped = 0;
  545. // Phase 1: delete sessions tracked in the history file
  546. for (const record of records) {
  547. if (seen.has(record.sessionId)) continue;
  548. seen.add(record.sessionId);
  549. try {
  550. const session = await sessionService.getSession(record.sessionId);
  551. if (!session) {
  552. skipped++;
  553. continue;
  554. }
  555. if (session.sessionType === CronSessionType.Root) {
  556. skipped++;
  557. continue;
  558. }
  559. if (session.purpose !== expectedPurpose) {
  560. skipped++;
  561. continue;
  562. }
  563. await sessionService.deleteSession(record.sessionId);
  564. deleted++;
  565. } catch (err) {
  566. logger.warn(
  567. ctx,
  568. `[cron] Failed to delete session on cron delete, agent=${agentName} cron=${cronName} sessionId=${record.sessionId} err=${(err as Error).message}`,
  569. );
  570. }
  571. }
  572. // Phase 2: fallback — sweep session store by purpose prefix to catch
  573. // orphans not tracked in the history file (e.g. records truncated by
  574. // retention policy or created by earlier versions without history tracking).
  575. if (sessionService.listByPurposePrefix) {
  576. try {
  577. const orphans = await sessionService.listByPurposePrefix(expectedPurpose);
  578. for (const orphan of orphans) {
  579. if (seen.has(orphan.sessionId)) continue;
  580. if (orphan.sessionType === CronSessionType.Root) continue;
  581. // listByPurposePrefix matches by prefix, so `cron:agent:foo` would also
  582. // return `cron:agent:foobar`. Re-verify exact purpose before deletion
  583. // to avoid wiping sessions belonging to same-prefix cron tasks.
  584. if (orphan.purpose !== expectedPurpose) continue;
  585. try {
  586. await sessionService.deleteSession(orphan.sessionId);
  587. deleted++;
  588. } catch (err) {
  589. logger.warn(
  590. ctx,
  591. `[cron] Failed to delete orphan session on cron delete, agent=${agentName} cron=${cronName} sessionId=${orphan.sessionId} err=${(err as Error).message}`,
  592. );
  593. }
  594. }
  595. } catch (err) {
  596. logger.warn(
  597. ctx,
  598. `[cron] Purpose-based orphan sweep failed (non-fatal), agent=${agentName} cron=${cronName} err=${(err as Error).message}`,
  599. );
  600. }
  601. }
  602. if (deleted > 0) {
  603. logger.info(
  604. ctx,
  605. `[cron] Sessions deleted on task delete, agent=${agentName} cron=${cronName} deleted=${deleted} skipped=${skipped}`,
  606. );
  607. }
  608. }
  609. /**
  610. * Delete orphan cron sessions at startup — sessions whose purpose matches
  611. * `cron:<agentName>:<cronName>` but whose corresponding cron task no longer
  612. * exists.
  613. *
  614. * @param aliveTaskKeys Set of `agentName:cronName` keys for currently
  615. * registered cron tasks.
  616. */
  617. async cleanupOrphanCronSessions(aliveTaskKeys: Set<string>): Promise<void> {
  618. const ctx = backgroundCtx();
  619. const sessionService = getSessionLifecycle();
  620. if (!sessionService.listByPurposePrefix) return;
  621. let sessions: Awaited<ReturnType<NonNullable<typeof sessionService.listByPurposePrefix>>>;
  622. try {
  623. sessions = await sessionService.listByPurposePrefix('cron:');
  624. } catch (err) {
  625. logger.warn(
  626. ctx,
  627. `[cron] Orphan session cleanup: listByPurposePrefix failed (non-fatal), err=${(err as Error).message}`,
  628. );
  629. return;
  630. }
  631. let deleted = 0;
  632. for (const session of sessions) {
  633. if (session.sessionType === CronSessionType.Root) continue;
  634. if (!session.purpose) continue;
  635. const parsed = parseCronSessionPurpose(session.purpose);
  636. if (!parsed) continue;
  637. // Reserved daemon-managed cron purposes — these are NOT registered in
  638. // CronRegistry (they are spawned by dedicated daemon services such as
  639. // MemoryCleanupSpawner) but legitimately use the cron:<agent>:<name>
  640. // purpose namespace. Skip them so startup orphan cleanup does not wipe
  641. // their session history.
  642. if (parsed.cronName === MEMORY_CLEANUP_CRON_NAME) continue;
  643. const taskKey = `${parsed.agentName}:${parsed.cronName}`;
  644. if (aliveTaskKeys.has(taskKey)) continue;
  645. try {
  646. await sessionService.deleteSession(session.sessionId);
  647. deleted++;
  648. } catch (err) {
  649. logger.warn(
  650. ctx,
  651. `[cron] Orphan session cleanup: failed to delete session=${session.sessionId} purpose=${session.purpose} err=${(err as Error).message}`,
  652. );
  653. }
  654. }
  655. if (deleted > 0) {
  656. logger.info(ctx, `[cron] Orphan cron sessions cleaned up: deleted=${deleted}`);
  657. }
  658. }
  659. private async runUnderHistoryLock(
  660. agentName: string,
  661. cronName: string,
  662. fn: () => Promise<void>,
  663. ): Promise<void> {
  664. const key = `${agentName}\u0000${cronName}`;
  665. const previous = this.historyLocks.get(key) ?? Promise.resolve();
  666. // Chain `fn` after the previous lock holder regardless of whether it
  667. // resolved or rejected — but log the previous failure for observability.
  668. // Each caller still receives its own error via `await tracked` below;
  669. // there is no error swallowing because the previous caller has already
  670. // observed (and logged) its own failure through its own `await`.
  671. const next = previous
  672. .catch((err) => {
  673. logger.debug(
  674. backgroundCtx(),
  675. `[cron] Previous lock holder failed (chained call proceeds): agent=${agentName} cron=${cronName} err=${(err as Error).message}`,
  676. );
  677. })
  678. .then(() => fn());
  679. // Track the in-flight tail; remove from the map only when this exact tail
  680. // resolves so a follow-up call still observes a consistent chain.
  681. const tracked = next.finally(() => {
  682. if (this.historyLocks.get(key) === tracked) {
  683. this.historyLocks.delete(key);
  684. }
  685. });
  686. this.historyLocks.set(key, tracked);
  687. await tracked;
  688. }
  689. /** Listen for the cron response and fan it out to the agent's bound IM chats. */
  690. private setupAutoDeliveryListener(state: CronTaskState, cronSessionId: string): void {
  691. collectCronTurnText(
  692. this.sessionBridge,
  693. {
  694. agentName: state.agentName,
  695. cronName: state.cronName,
  696. sessionId: cronSessionId,
  697. listenerLabel: 'IM auto-delivery',
  698. },
  699. (text) => {
  700. void deliverToAllBoundChannels(state.agentName, text, cronSessionId, this.cronHost);
  701. },
  702. );
  703. }
  704. /**
  705. * Listen for the cron response and deliver it to the configured channel
  706. * when the turn ends.
  707. */
  708. private setupDeliveryListener(state: CronTaskState, sessionId: string): void {
  709. const delivery = state.config.delivery!;
  710. collectCronTurnText(
  711. this.sessionBridge,
  712. {
  713. agentName: state.agentName,
  714. cronName: state.cronName,
  715. sessionId,
  716. listenerLabel: 'Delivery',
  717. },
  718. (text) => {
  719. void deliverToChannel(state, delivery, text, sessionId, this.cronHost);
  720. },
  721. );
  722. }
  723. }