Skip to content

Commit 133d5ff

Browse files
authored
fix(cron): deliver current-session completions to the source chat (#126860)
* fix(cron): persist current-session completions * test: refresh cron prompt snapshots * fix(cron): preserve current-session completion delivery * fix(cron): defer current-session awareness until commit failure
1 parent f0881cf commit 133d5ff

18 files changed

Lines changed: 865 additions & 54 deletions

‎docs/automation/cron-jobs.md‎

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -303,18 +303,18 @@ envelope continue their ordinary non-app behavior; recreate or reauthorize one
303303
only when it needs Codex app access. See
304304
[Native Codex plugins](/plugins/codex-native-plugins#scheduled-automations).
305305

306-
| Style | `--session` value | Runs in | Best for |
307-
| --------------- | ------------------- | --------------------------- | ------------------------------- |
308-
| Main session | `main` | Owning agent's main session | Reminders, system events |
309-
| Isolated | `isolated` | Dedicated `cron:<jobId>` | Reports, background chores |
310-
| Current session | `current` | Bound at creation time | Context-aware recurring work |
311-
| Custom session | `session:custom-id` | Persistent named session | Workflows that build on history |
306+
| Style | `--session` value | Runs in | Best for |
307+
| --------------- | ------------------- | ---------------------------------------------------- | ------------------------------- |
308+
| Main session | `main` | Owning agent's main session | Reminders, system events |
309+
| Isolated | `isolated` | Dedicated `cron:<jobId>` | Reports, background chores |
310+
| Current session | `current` | Detached; commits to the creation-bound conversation | Context-aware recurring work |
311+
| Custom session | `session:custom-id` | Persistent named session | Workflows that build on history |
312312

313313
Agent-turn jobs default to the creating conversation when the create request carries session context. Callers without a session key, including CLI and API callers that do not supply one, fall back to `isolated`. System events and heartbeats still default to `main`; command and script payloads still default to `isolated`.
314314

315315
<AccordionGroup>
316-
<Accordion title="Main session vs isolated vs custom">
317-
**Main session** jobs enqueue a system event into the owning agent's main session and optionally wake the heartbeat (`--wake now` or `--wake next-heartbeat`). The event is processed with that session's existing context and last delivery context. Internal automation turns do not extend daily or idle reset freshness; only visible user activity updates session freshness. **Isolated** jobs run a dedicated agent turn with a fresh session. **Custom sessions** (`session:xxx`) persist context across runs, enabling workflows like daily standups that build on previous summaries.
316+
<Accordion title="Main session vs current vs isolated vs custom">
317+
**Main session** jobs enqueue a system event into the owning agent's main session and optionally wake the heartbeat (`--wake now` or `--wake next-heartbeat`). The event is processed with that session's existing context and last delivery context. Internal automation turns do not extend daily or idle reset freshness; only visible user activity updates session freshness. **Current-session** jobs execute in a detached run session, read a bounded tail of the conversation captured when the job was created, and commit the final visible assistant result back to that exact conversation. **Isolated** jobs run a dedicated agent turn with a fresh session. **Custom sessions** (`session:xxx`) persist context across runs, enabling workflows like daily standups that build on previous summaries.
318318

319319
Main-session automation events are self-contained system-event reminders. They do not automatically include the default heartbeat prompt or the heartbeat monitor scratch; say it explicitly in the automation event text if a reminder should consult that context.
320320

@@ -344,6 +344,12 @@ Agent-turn jobs default to the creating conversation when the create request car
344344
| `webhook` | POST finished event payload to a URL |
345345
| `none` | No runner fallback delivery |
346346

347+
For a `current` job using `announce` (the default), the final assistant result is a first-class session completion, not a WebChat-specific outbound message. OpenClaw waits for active turns in the creation-bound conversation, verifies that the same session generation still owns the key, and commits the result through the canonical transcript writer with cron job/run provenance and a job/run idempotency key. A retry cannot append the same result twice.
348+
349+
WebChat receives the committed `session.message` event immediately. The same assistant result comes from `chat.history` after a refresh or reconnect; no follow-up user message is required. Delivery is successful only after that transcript/event commit succeeds.
350+
351+
If the bound conversation is an external channel, OpenClaw also performs its normal durable channel send. That send still happens at most once, and the required session commit does not create a second external message. A verified `message` tool send suppresses the automatic channel resend but does not suppress the session commit. The run is reported delivered only after both the external recipient handoff (when required) and the canonical session commit succeed.
352+
347353
<Warning>
348354
Every outbound automation webhook uses the strict SSRF guard. Loopback,
349355
private/internal, link-local, and other special-use targets are refused by

‎src/agents/tools/cron-tool.test.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -933,6 +933,15 @@ describe("cron tool", () => {
933933
expect(tool.description).toContain(
934934
"Inherited configured MCP authority includes only model-callable tools; interactive app-view-only capabilities are excluded from headless jobs.",
935935
);
936+
expect(tool.description).toContain(
937+
"the run stays detached, reads bounded chat context, then commits its final visible assistant result to this conversation's durable history",
938+
);
939+
expect(tool.description).toContain(
940+
"current=>canonical session commit, plus one normal channel send for external chats",
941+
);
942+
expect(tool.description).toContain(
943+
"WebChat observes that commit live and after reconnect without another user message",
944+
);
936945
});
937946

938947
it("documents the event-trigger authoring contract", () => {

‎src/agents/tools/cron-tool.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,7 @@ SCHEDULE:
193193
- {kind:"cron",expr,tz?:"IANA"}: expr is wall time in tz; never pre-convert to UTC; no tz=gateway host local. 18:00 Shanghai => {expr:"0 18 * * *",tz:"Asia/Shanghai"}.${streamScheduleLine}
194194
195195
TARGET+PAYLOAD:
196-
- "current" (agentTurn default) = this conversation: run carries this chat's context, result lands here. Self-wakeup/"continue later"/loop = at|every + agentTurn + current.
196+
- "current" (agentTurn default) = this conversation: the run stays detached, reads bounded chat context, then commits its final visible assistant result to this conversation's durable history. Self-wakeup/"continue later"/loop = at|every + agentTurn + current.
197197
- "isolated" = fresh detached session (shows in \`openclaw tasks\`); standalone background work.
198198
- "main" = heartbeat lane; payload {kind:"systemEvent",text} (systemEvent default target).
199199
- "session:<key>" = named session.
@@ -204,7 +204,7 @@ PACED LOOP: recurring job + pacing{min?,max?} durations ("15m","4h"; at least on
204204
205205
${triggerSection}
206206
207-
DELIVERY {mode:"none"|"announce"|"webhook",channel?,to?,threadId?,bestEffort?,completionDestination?}: where detached run output goes. Omitted=announce (current=>this chat; isolated=>last route; set channel/to for a specific chat — no messaging tool inside the run).${silentWatcherCue} webhook posts finished-run event to URL in \`to\`. To keep announce delivery and also POST completion, use mode:"announce" with completionDestination:{mode:"webhook",to:"https://..."}.
207+
DELIVERY {mode:"none"|"announce"|"webhook",channel?,to?,threadId?,bestEffort?,completionDestination?}: where detached run output goes. Omitted=announce (current=>canonical session commit, plus one normal channel send for external chats; isolated=>last route; set channel/to for a specific chat — no messaging tool inside the run). A current announce succeeds only after its history commit; WebChat observes that commit live and after reconnect without another user message.${silentWatcherCue} webhook posts finished-run event to URL in \`to\`. To keep announce delivery and also POST completion, use mode:"announce" with completionDestination:{mode:"webhook",to:"https://..."}.
208208
209209
FAILURE ALERTS: jobs with a failure route default to alerting after 2 consecutive execution failures with a 1h cooldown. Route order: job failureAlert fields, delivery.failureDestination over global cron.failureAlert destination fields, then primary announce. failureAlert:false disables execution/delivery alerts, not the auto-disable safety notice; a failureAlert object activates/tunes. bestEffort suppresses inherited execution alerts. Required completion-delivery failure uses only an alternate route immediately and does not increment the execution streak.
210210
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
2+
import {
3+
createOutboundPayloadPlan,
4+
projectOutboundPayloadPlanForMirror,
5+
} from "../../infra/outbound/payloads.js";
6+
import { parseAgentSessionKey } from "../../routing/session-key.js";
7+
import { commitBackgroundResultToSession } from "../../sessions/background-session-result.js";
8+
import { createCronExecutionId } from "../run-id.js";
9+
import {
10+
buildDirectCronTranscriptMirrorPayloads,
11+
resolveDirectCronTranscriptMirrorText,
12+
} from "./delivery-dispatch-awareness.js";
13+
import type { DispatchCronDeliveryParams } from "./delivery-dispatch-types.js";
14+
15+
type CurrentSessionCompletionResult =
16+
| { ok: false; reason: string }
17+
| { ok: true; requiresExternalDelivery: boolean };
18+
19+
export async function commitCurrentSessionCronCompletion(
20+
params: DispatchCronDeliveryParams,
21+
text?: string,
22+
): Promise<CurrentSessionCompletionResult> {
23+
const sourceSessionKey = params.sourceSessionKey?.trim();
24+
if (!sourceSessionKey) {
25+
return { ok: false, reason: "current cron delivery is missing its source session binding" };
26+
}
27+
const completionText =
28+
resolveDirectCronTranscriptMirrorText(
29+
projectOutboundPayloadPlanForMirror(
30+
createOutboundPayloadPlan(buildDirectCronTranscriptMirrorPayloads(params.deliveryPayloads)),
31+
),
32+
) ?? normalizeOptionalString(text);
33+
if (!completionText) {
34+
return { ok: false, reason: "current cron completion has no durable transcript projection" };
35+
}
36+
const runId = createCronExecutionId(params.job.id, params.runStartedAt);
37+
const committed = await commitBackgroundResultToSession({
38+
agentId: params.agentId,
39+
sessionKey: sourceSessionKey,
40+
text: completionText,
41+
idempotencyKey: `cron-current-completion:${runId}`,
42+
provenance: { kind: "cron", jobId: params.job.id, runId },
43+
config: params.cfgWithAgentDefaults,
44+
signal: params.abortSignal,
45+
});
46+
if (!committed.ok) {
47+
return committed;
48+
}
49+
if (params.sourceDeliveryOutcome.satisfiesSourceDelivery) {
50+
return { ok: true, requiresExternalDelivery: false };
51+
}
52+
if (params.resolvedDelivery.ok) {
53+
return { ok: true, requiresExternalDelivery: true };
54+
}
55+
const sourceChannel = parseAgentSessionKey(sourceSessionKey)?.rest.split(":")[0];
56+
if (params.resolvedDelivery.channel === "webchat" || sourceChannel === "webchat") {
57+
return { ok: true, requiresExternalDelivery: false };
58+
}
59+
return { ok: false, reason: params.resolvedDelivery.error.message };
60+
}

‎src/cron/isolated-agent/delivery-dispatch-awareness.ts‎

Lines changed: 25 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -191,13 +191,12 @@ export async function queueCronAwarenessSystemEvent(params: {
191191
targetSessionKey &&
192192
(!isSameSessionKey(targetSessionKey, mainSessionKey) || !params.queueMainSession);
193193
if (shouldQueueTargetSession) {
194-
enqueueSystemEvent(
195-
params.targetText ?? formatTargetCronDeliveryAwarenessText(params.text),
196-
withSystemEventOwner(
197-
{ sessionKey: targetSessionKey, contextKey: params.deliveryIdempotencyKey },
198-
params.agentId,
199-
),
194+
const text = params.targetText ?? formatTargetCronDeliveryAwarenessText(params.text);
195+
const options = withSystemEventOwner(
196+
{ sessionKey: targetSessionKey, contextKey: params.deliveryIdempotencyKey },
197+
params.agentId,
200198
);
199+
enqueueSystemEvent(text, options);
201200
}
202201
} catch (err) {
203202
await logCronDeliveryWarn(
@@ -464,11 +463,13 @@ export async function queueCronMessageToolDeliveryAwareness(params: {
464463
job: CronJob;
465464
agentId: string;
466465
agentSessionKey: string;
466+
deferredTargetSessionKey?: string;
467467
runStartedAt: number;
468468
resolvedDelivery: DeliveryTargetResolution;
469469
sourceDeliveryOutcome: SourceDeliveryOutcome;
470-
}): Promise<void> {
470+
}): Promise<(() => Promise<void>) | undefined> {
471471
const seen = new Set<string>();
472+
const deferredAwareness: Array<() => Promise<void>> = [];
472473
for (const delivery of params.sourceDeliveryOutcome.visibleDeliveries) {
473474
const target = resolveCronMessageToolAwarenessTarget({
474475
delivery,
@@ -501,16 +502,31 @@ export async function queueCronMessageToolDeliveryAwareness(params: {
501502
runStartedAt: params.runStartedAt,
502503
delivery: target,
503504
});
504-
await queueCronAwarenessSystemEvent({
505+
const awarenessParams = {
505506
cfg: params.cfg,
506507
jobId: params.job.id,
507508
agentId: params.agentId,
508509
deliveryIdempotencyKey,
509510
queueMainSession: false,
510511
targetSessionKey,
511512
text: target.text,
512-
});
513+
};
514+
if (isSameSessionKey(targetSessionKey, params.deferredTargetSessionKey)) {
515+
// A current-session completion owns this target durably. Keep awareness
516+
// unavailable until that commit fails so reply admission cannot race it.
517+
deferredAwareness.push(() => queueCronAwarenessSystemEvent(awarenessParams));
518+
continue;
519+
}
520+
await queueCronAwarenessSystemEvent(awarenessParams);
521+
}
522+
if (deferredAwareness.length === 0) {
523+
return undefined;
513524
}
525+
return async () => {
526+
for (const queue of deferredAwareness) {
527+
await queue();
528+
}
529+
};
514530
}
515531

516532
async function appendDirectCronDeliveryTranscriptMirror(params: {

‎src/cron/isolated-agent/delivery-dispatch-types.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ export type DispatchCronDeliveryParams = {
1717
job: CronJob;
1818
agentId: string;
1919
agentSessionKey: string;
20+
sourceSessionKey?: string;
2021
runSessionKey: string;
2122
sessionId: string;
2223
lifecycleRevision: string;
@@ -30,6 +31,8 @@ export type DispatchCronDeliveryParams = {
3031
skipHeartbeatDelivery: boolean;
3132
spawnOnlyHandoff: boolean;
3233
sourceDeliveryOutcome: SourceDeliveryOutcome;
34+
/** Queues same-source fallback awareness only after a durable completion commit fails. */
35+
queueSourceSessionMessageToolAwareness?: () => Promise<void>;
3336
deliveryBestEffort: boolean;
3437
deliveryPayloadHasStructuredContent: boolean;
3538
deliveryPayloads: ReplyPayload[];

0 commit comments

Comments
 (0)