fix (heartbeat/cron): preserve cron prompts for tagged interval events

This commit is contained in:
Vignesh Natarajan
2026-02-14 19:46:07 -08:00
parent 1712a71a39
commit 4c4d2558e3
5 changed files with 41 additions and 14 deletions

View File

@@ -35,7 +35,7 @@ export type CronServiceDeps = {
resolveSessionStorePath?: (agentId?: string) => string;
/** Path to the session store (sessions.json) for reaper use. */
sessionStorePath?: string;
enqueueSystemEvent: (text: string, opts?: { agentId?: string }) => void;
enqueueSystemEvent: (text: string, opts?: { agentId?: string; contextKey?: string }) => void;
requestHeartbeatNow: (opts?: { reason?: string }) => void;
runHeartbeatOnce?: (opts?: { reason?: string; agentId?: string }) => Promise<HeartbeatRunResult>;
/**

View File

@@ -445,7 +445,10 @@ async function executeJobCore(
: 'main job requires payload.kind="systemEvent"',
};
}
state.deps.enqueueSystemEvent(text, { agentId: job.agentId });
state.deps.enqueueSystemEvent(text, {
agentId: job.agentId,
contextKey: `cron:${job.id}`,
});
if (job.wakeMode === "now" && state.deps.runHeartbeatOnce) {
const reason = `cron:${job.id}`;
const delay = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
@@ -503,7 +506,10 @@ async function executeJobCore(
const prefix = "Cron";
const label =
res.status === "error" ? `${prefix} (error): ${summaryText}` : `${prefix}: ${summaryText}`;
state.deps.enqueueSystemEvent(label, { agentId: job.agentId });
state.deps.enqueueSystemEvent(label, {
agentId: job.agentId,
contextKey: `cron:${job.id}`,
});
if (job.wakeMode === "now") {
state.deps.requestHeartbeatNow({ reason: `cron:${job.id}` });
}

View File

@@ -64,7 +64,7 @@ export function buildGatewayCronService(params: {
cfg: runtimeConfig,
agentId,
});
enqueueSystemEvent(text, { sessionKey });
enqueueSystemEvent(text, { sessionKey, contextKey: opts?.contextKey });
},
requestHeartbeatNow,
runHeartbeatOnce: async (opts) => {

View File

@@ -59,7 +59,7 @@ import {
resolveHeartbeatDeliveryTarget,
resolveHeartbeatSenderContext,
} from "./outbound/targets.js";
import { peekSystemEvents } from "./system-events.js";
import { peekSystemEventEntries } from "./system-events.js";
type HeartbeatDeps = OutboundSendDeps &
ChannelHeartbeatDeps & {
@@ -487,11 +487,23 @@ export async function runHeartbeatOnce(opts: {
// If so, use a specialized prompt that instructs the model to relay the result
// instead of the standard heartbeat prompt with "reply HEARTBEAT_OK".
const isExecEvent = opts.reason === "exec-event";
const isCronEvent = Boolean(opts.reason?.startsWith("cron:"));
const pendingEvents = isExecEvent || isCronEvent ? peekSystemEvents(sessionKey) : [];
const cronEvents = pendingEvents.filter((evt) => isCronSystemEvent(evt));
const pendingEventEntries = peekSystemEventEntries(sessionKey);
const hasTaggedCronEvents = pendingEventEntries.some((event) =>
event.contextKey?.startsWith("cron:"),
);
const shouldInspectPendingEvents = isExecEvent || isCronEventReason || hasTaggedCronEvents;
const pendingEvents = shouldInspectPendingEvents
? pendingEventEntries.map((event) => event.text)
: [];
const cronEvents = pendingEventEntries
.filter(
(event) =>
(isCronEventReason || event.contextKey?.startsWith("cron:")) &&
isCronSystemEvent(event.text),
)
.map((event) => event.text);
const hasExecCompletion = pendingEvents.some(isExecCompletionEvent);
const hasCronEvents = isCronEvent && cronEvents.length > 0;
const hasCronEvents = cronEvents.length > 0;
const prompt = hasExecCompletion
? EXEC_EVENT_PROMPT
: hasCronEvents

View File

@@ -2,7 +2,7 @@
// prefixed to the next prompt. We intentionally avoid persistence to keep
// events ephemeral. Events are session-scoped and require an explicit key.
export type SystemEvent = { text: string; ts: number };
export type SystemEvent = { text: string; ts: number; contextKey?: string | null };
const MAX_EVENTS = 20;
@@ -65,12 +65,17 @@ export function enqueueSystemEvent(text: string, options: SystemEventOptions) {
if (!cleaned) {
return;
}
entry.lastContextKey = normalizeContextKey(options?.contextKey);
const normalizedContextKey = normalizeContextKey(options?.contextKey);
entry.lastContextKey = normalizedContextKey;
if (entry.lastText === cleaned) {
return;
} // skip consecutive duplicates
entry.lastText = cleaned;
entry.queue.push({ text: cleaned, ts: Date.now() });
entry.queue.push({
text: cleaned,
ts: Date.now(),
contextKey: normalizedContextKey,
});
if (entry.queue.length > MAX_EVENTS) {
entry.queue.shift();
}
@@ -94,9 +99,13 @@ export function drainSystemEvents(sessionKey: string): string[] {
return drainSystemEventEntries(sessionKey).map((event) => event.text);
}
export function peekSystemEvents(sessionKey: string): string[] {
export function peekSystemEventEntries(sessionKey: string): SystemEvent[] {
const key = requireSessionKey(sessionKey);
return queues.get(key)?.queue.map((e) => e.text) ?? [];
return queues.get(key)?.queue.map((event) => ({ ...event })) ?? [];
}
export function peekSystemEvents(sessionKey: string): string[] {
return peekSystemEventEntries(sessionKey).map((event) => event.text);
}
export function hasSystemEvents(sessionKey: string) {