openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,707 lines • 65.6 kB
JavaScript
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { d as asPositiveFiniteNumber, l as asNonNegativeFiniteNumber, n as MAX_TIMER_TIMEOUT_MS } from "./number-coercion-D6u-4YD8.mjs";
import { o as isFastTestRuntimeEnv } from "./env-HehwidXj.mjs";
import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs";
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import "./utils-C8YECn2Q.mjs";
import { n as waitForAgentDatabaseWriteAdmission } from "./agent-database-preparation-context-CkVoUMTY.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import { j as parseAgentSessionKey, x as isCronSessionKey } from "./session-key-CqAyZeVk.mjs";
import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs";
import { O as tryResolveAmbientOwnerAgentId, a as resolveAgentDir, f as resolveAgentWorkspaceDir, r as resolveAgentConfig } from "./agent-scope-config-DmXgFGKP.mjs";
import { p as isDiagnosticsEnabled, s as emitTrustedDiagnosticEvent } from "./diagnostic-events-BjAH1Kbx.mjs";
import { T as runWithDiagnosticTraceContext, _ as createDiagnosticTraceContextFromActiveScope, h as createChildDiagnosticTraceContext, y as freezeDiagnosticTraceContext } from "./diagnostics-timeline-CSwiG24r.mjs";
import { a as hasBillableUsage, i as deriveSessionTotalTokens, n as deriveContextPromptTokens, o as hasNonzeroUsage } from "./usage-CHLnzpJG.mjs";
import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs";
import { t as createLazyImportLoader } from "./lazy-promise-DiCvjz9w.mjs";
import { w as hasPendingAutomationContinuation } from "./run-history-detail-rOrjKG4Z.mjs";
import { t as DEFAULT_CONTEXT_TOKENS } from "./defaults-BWyoTPqn.mjs";
import { o as resolveSessionModelOverrideSource } from "./model-override-provenance-DeIPDBg8.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { b as releaseAgentRunContext, i as claimAgentRunContext, l as getAgentRunContext } from "./agent-run-registry-D7vkrqFT.mjs";
import { C as withAgentRunLifecycleGeneration, d as getAgentEventLifecycleGeneration, t as assertAgentRunLifecycleGenerationCurrent } from "./agent-events-BdfWYmot.mjs";
import { n as withPluginRuntimeGenerationScope } from "./generation-scope-Cq7RLFex.mjs";
import { C as findModelInCatalog } from "./model-selection-shared-9Kz63Hhm.mjs";
import { n as extractTextFromChatContent } from "./chat-content-Dkam4EQe.mjs";
import { s as findErrorProperty, u as isFailoverError } from "./error-BCRqSFIY.mjs";
import { m as resolveAgentRunErrorLifecycleFields, o as createAgentRunRestartAbortError } from "./run-termination-0Ig0-bk6.mjs";
import { s as resolveCronScheduledToolPolicy } from "./scheduled-tool-policy-C_pucbBp.mjs";
import { r as resolveCronRunToolsAllow } from "./tools-allow-CYmLDCc7.mjs";
import { c as CODE_MODE_MCP_CATALOG_MISS_MESSAGE, i as mergeCronRunDiagnostics, l as isEmbeddedRunTerminalToolFailure, n as createCronRunDiagnosticsFromError, t as createCronRunDiagnosticsFromAgentResult } from "./run-diagnostics-D33n4kQR.mjs";
import { j as shouldSuppressReasoningPayload } from "./reply-payload-k5WsQWxi.mjs";
import { _ as projectCronRunUsage, d as consumeCronNextCheckProposal } from "./session-event-handoff-CC7Ui3SA.mjs";
import { d as resolveCreatorSandbox } from "./operator-role-policy-DhcqVpmG.mjs";
import { R as getCurrentSessionControllerOwner } from "./session-controller.lifecycle-C_Z3sybN.mjs";
import { a as isAgentHarnessSessionKey, n as AGENT_HARNESS_SESSION_ID_LOCKED_MESSAGE, r as AGENT_HARNESS_SESSION_KEY_RESERVED_MESSAGE } from "./agent-harness-session-key-BRYGtzM6.mjs";
import "./sessions-D5Vvu3AE.mjs";
import { n as resolveProjectedSessionContextTokens, r as resolveTrustedSessionContextTokens } from "./context-token-provenance-DpW0Nm2P.mjs";
import { i as logWarn } from "./logger-CIwfuhOU.mjs";
import { n as resolveAgentTimeoutMs } from "./timeout-BEnEcjB4.mjs";
import { a as withPreparedModelRuntimePluginGenerationScope, i as scopePreparedModelRuntimeLease } from "./prepared-model-runtime-generation-scope-Dpvf6WHJ.mjs";
import { i as resolveThinkingSelectionCore } from "./model-thinking-default-DTaWSs8g.mjs";
import { i as resolveSessionRuntimeOverrideForProvider } from "./session-runtime-compat-C_CO9LR_.mjs";
import { o as resolveEffectiveAgentRuntime } from "./thinking-runtime-BKWl4CUs.mjs";
import { n as hasAnyAuthProfileStoreSourceAsync } from "./source-check-1bfdqQg5.mjs";
import { r as resolveCronJobEffectiveAgentId } from "./agent-id-CX8HtxAT.mjs";
import { t as resolveCronAgentSessionKey } from "./session-key-BQPSZVRH.mjs";
import { r as resolveCronSessionWorkspaceOwnershipError, t as CronSessionLifecycleClaimError } from "./run-authority-CJXQKUzJ.mjs";
import { o as resolveCronDeliverySessionKey, r as isDetachedCronSessionTarget, s as resolveCronSessionTargetSessionKey } from "./session-target-C-4MLah6.mjs";
import { g as loadPublishedGatewayReplyDispatchRuntime, t as acquireAgentRunPreparedModelRuntime } from "./prepared-model-runtime-Bbo9uBdt.mjs";
import { t as ensureAgentWorkspace } from "./workspace-DLlXz3VE.mjs";
import { o as isCommandLaneTaskTimeoutError } from "./command-queue-BenRlAaO.mjs";
import { n as logMessageDispatchStarted, t as logMessageDispatchCompleted } from "./diagnostic-C-GjPJGO.mjs";
import { n as resolveDiagnosticModelContentCapturePolicy } from "./diagnostic-llm-content-CvUZCA61.mjs";
import { o as resolveCronJobsStorePathFromConfigAsync } from "./paths-CY4cvrR6.mjs";
import { r as resolveHookExternalContentSource } from "./external-content-source-BOt3r-v5.mjs";
import { r as resolveCronRuntimeSessionEntry } from "./inference-binding-WWjqX5o7.mjs";
import { n as isCronWithinActiveHours } from "./active-hours-DyXD6x9W.mjs";
import { t as withSessionTurn } from "./session-controller.admission-DDiE4tNx.mjs";
import { t as createDiagnosticMessageLifecycle } from "./message-lifecycle-DXuyekCU.mjs";
import { n as resolveSessionStableReplyMode } from "./session-stable-reply-mode-Bboydwa7.mjs";
import { l as retireSessionMcpRuntime } from "./agent-bundle-mcp-manager-api-Um6GkoIv.mjs";
import "./agent-bundle-mcp-tools-CjrVbt71.mjs";
import { r as hasOwedSessionSpawn } from "./accepted-session-spawn-DXCz6IHR.mjs";
import { s as projectChatDisplayMessages } from "./chat-display-projection.core-ApUvO4fQ.mjs";
import { l as readSessionMessagesAsync } from "./session-transcript-readers-D1WqgwbF.mjs";
import { t as classifyCronAgentTurnShellPrompt } from "./agent-turn-command-prompt-C2-lgNZN.mjs";
import { r as resolveIngressWorkspaceOverrideForSessionRun } from "./spawned-context-wZ6NGSBl.mjs";
import { n as resolveCronStyleNow } from "./current-time-DitOGqc6.mjs";
import { o as resolveCronChannelOutputPolicy, r as resolveCronPreflight } from "./run-fallback-policy-C7ybg2iz.mjs";
import "./run.runtime.js";
import { a as resolveCronAgentConfig, i as resolveCronActiveRuntimeConfig, n as resolveCronModelSelectionOwner, r as resolveCronThinkingSelection, t as resolveCronModelSelection } from "./model-selection-BZhMpZwE.mjs";
import { t as cleanupBrowserSessionsForLifecycleEnd } from "./browser-lifecycle-cleanup-CQ-0EGCY.mjs";
import { i as toNormalizedUsage, r as mergeUsageIntoAccumulator, t as createUsageAccumulator } from "./usage-accumulator-CWIvkatR.mjs";
import { a as normalizeCronRunErrorText, s as resolveCronAbortReasonText } from "./execution-errors-aeOsnaMY.mjs";
import "./chat-display-projection-lHBiRfmJ.mjs";
import { t as resolveSourceDeliveryOutcome } from "./source-delivery-plan-CVIba1RJ.mjs";
import { t as removeCronRunContinuationSessionIfIdle } from "./run-continuation-cleanup-BqcMy0vd.mjs";
import { t as createAgentLifecycleTerminalBackstop } from "./agent-lifecycle-terminal-DsT43SVO.mjs";
import { r as isCronOneShotContinuationJob } from "./one-shot-schedule-Ff0uCKas.mjs";
import { i as readCronScratchSnapshot, n as resolveCronAgentTerminalOutcome, t as resolveCronAgentErrorClassification } from "./run-error-reason-DZj2Hht2.mjs";
import { t as cleanupCronRunSessionAfterRun } from "./session-cleanup-Ds7EnY6w.mjs";
import { t as resolveDiagnosticModelResponse } from "./diagnostic-model-response-CbgexSbW.mjs";
import { n as prepareCronSession, t as loadCronSessionEntryLatest } from "./session-Wmk7eSa1.mjs";
import { n as buildCronCommandBody, r as isCronExecutionIdle, t as appendCronJobScratchPrompt } from "./run-prompt-C-aYfs0p.mjs";
import { t as CronOperatorSourceError } from "./operator-source-error-Da33p_8S.mjs";
import { n as resolveCronPayloadOutcome } from "./helpers-DUxe3ZGT.mjs";
import { a as resolveCronDeliveryContext, i as loadCronDeliveryRuntime, n as createCronToolsAllowPreflightDiagnostics, t as buildCronDeliveryTrace } from "./run-delivery-trace-CTRu-zNY.mjs";
import { a as setCronSessionAgentHarnessId, c as withCronSessionPreparation, i as createPersistCronSessionEntry, n as beginCronPreparationEffect, o as setCronSessionRuntimeModel, r as createCronRunContinuationSession, t as adoptCronRunSessionMetadata } from "./run-session-state-axJ2f0bL.mjs";
import { t as resolveCronSkillsSnapshot } from "./cron-snapshot-VV6k-dQC.mjs";
import { t as applyLegacyHeartbeatPromptContribution } from "./heartbeat-compat-AYOY9pUR.mjs";
import { t as prepareCronSessionWorktree } from "./run-workspace-YkX8ppOK.mjs";
import { randomUUID } from "node:crypto";
import fs from "node:fs/promises";
//#region src/cron/isolated-agent/run-usage.ts
const cronContextRuntimeLoader$1 = createLazyImportLoader(() => import("./run-context.runtime.js"));
function resolveCronRunUsage(e) {
if (e.length === 1) return e[0]?.runResult.meta?.agentMeta?.usage;
const t = createUsageAccumulator();
for (const { runResult: n } of e) {
const e = n.meta?.agentMeta?.usage;
if (!e) continue;
const r = (e.input ?? 0) + (e.output ?? 0) + (e.cacheRead ?? 0) + (e.cacheWrite ?? 0);
mergeUsageIntoAccumulator(t, {
...e,
total: Math.max(r, asNonNegativeFiniteNumber(e.total) ?? 0)
});
}
return toNormalizedUsage(t);
}
function applyCronRunUsage(e, t) {
const n = resolveCronRunUsage(t);
if (!hasNonzeroUsage(n) && !hasNonzeroUsage(t.at(-1)?.runResult.meta?.agentMeta?.usage)) return;
const r = n?.input ?? 0;
const i = n?.output ?? 0;
const a = n?.cacheRead ?? 0;
const o = n?.cacheWrite ?? 0;
e.cronSession.sessionEntry.inputTokens = r;
e.cronSession.sessionEntry.outputTokens = i;
e.cronSession.sessionEntry.cacheRead = a;
e.cronSession.sessionEntry.cacheWrite = o;
return projectCronRunUsage(n);
}
/** Preserve each completed prompt's prices and diagnostics across a continuation. */
async function recordCronRunUsage(e) {
const { prepared: t, runs: n } = e;
const r = n.filter(({ runResult: e }) => {
const t = e.meta?.agentMeta;
return hasBillableUsage(t?.usage) || hasBillableUsage(t?.diagnosticUsage);
});
if (r.length === 0) return;
const { estimateAggregateUsageCost: i, resolveModelCostConfig: a } = await import("./usage-format-CtPkK69W.mjs");
let o = 0;
let s = false;
for (const c of r) {
const r = c.runResult;
const l = r.meta?.agentMeta;
const u = l?.usage;
const d = l?.diagnosticUsage ?? u;
const f = l?.provider ?? c.fallbackProvider;
const p = l?.model ?? c.fallbackModel;
const m = a({
provider: f,
model: p,
config: t.cfgWithAgentDefaults,
agentDir: t.agentDir
});
if (hasBillableUsage(u)) {
s = true;
const e = asNonNegativeFiniteNumber(i({
usage: u,
cost: m
}));
o = o !== void 0 && e !== void 0 ? o + e : void 0;
}
if (!isDiagnosticsEnabled(t.cfgWithAgentDefaults) || !hasBillableUsage(d)) continue;
const h = d.input ?? 0;
const g = d.output ?? 0;
const _ = d.cacheRead ?? 0;
const v = d.cacheWrite ?? 0;
const y = h + _ + v;
const b = y + g;
const x = typeof d.total === "number" && Number.isFinite(d.total) ? Math.max(b, d.total) : b;
const S = asNonNegativeFiniteNumber(i({
usage: d,
cost: m
}));
const C = deriveContextPromptTokens({
lastCallUsage: l?.lastCallUsage,
promptTokens: l?.promptTokens,
usage: u
});
const w = (r === n.at(-1)?.runResult ? e.contextTokens : void 0) ?? asPositiveFiniteNumber(l?.contextTokens) ?? (await cronContextRuntimeLoader$1.load()).resolveModelContextTokenProjection({
cfg: t.cfgWithAgentDefaults,
provider: f,
model: p,
allowAsyncLoad: false
}).contextTokens ?? 2e5;
emitTrustedDiagnosticEvent({
type: "model.usage",
...r.diagnosticTrace ? { trace: freezeDiagnosticTraceContext(createChildDiagnosticTraceContext(r.diagnosticTrace)) } : {},
sessionKey: t.runSessionKey,
sessionId: t.currentRunSessionId(),
channel: "cron",
agentId: t.agentId,
provider: f,
model: p,
usage: {
input: h,
output: g,
cacheRead: _,
cacheWrite: v,
promptTokens: y,
total: x
},
lastCallUsage: l?.lastCallUsage,
context: {
limit: w,
...C !== void 0 ? { used: C } : {}
},
...S !== void 0 ? { costUsd: S } : {},
durationMs: c.runEndedAt - c.runStartedAt
});
}
if (s) t.cronSession.sessionEntry.estimatedCostUsd = o;
}
//#endregion
//#region src/cron/isolated-agent/run-finalize.ts
/** Final persistence, telemetry, and delivery for an isolated cron run. */
const cronContextRuntimeLoader = createLazyImportLoader(() => import("./run-context.runtime.js"));
async function finalizeCronRun(e) {
const { prepared: t, execution: n } = e;
const r = n.runResult;
const i = r.meta?.terminalReply?.disposition ?? "empty";
const a = hasPendingAutomationContinuation(r.meta);
const o = t.agentPayload?.includeReasoning === true;
const s = (r.payloads ?? []).filter((e) => !shouldSuppressReasoningPayload(e));
const cleanupRunSession = async (n) => {
await cleanupCronRunSessionAfterRun({
job: t.input.job,
agentSessionKey: t.agentSessionKey,
sessionId: t.currentRunSessionId(),
lifecycleRevision: t.cronSession.lifecycleRevision,
sessionUpdatedAt: t.cronSession.sessionEntry.updatedAt,
beforeDelete: e.beforeSessionDelete,
reason: n
});
e.markCronRunSessionCleanupHandled();
};
if (!e.isAborted()) {
if (r.meta?.systemPromptReport) t.cronSession.sessionEntry.systemPromptReport = r.meta.systemPromptReport;
if (r.meta?.executionTrace?.runner !== "cli") adoptCronRunSessionMetadata({
entry: t.cronSession.sessionEntry,
sessionKey: t.agentSessionKey,
runMeta: r.meta?.agentMeta
});
}
const c = resolveCronRunUsage(n.completedPromptRuns);
const l = r.meta?.agentMeta?.lastCallUsage;
const u = r.meta?.agentMeta?.promptTokens;
const d = r.meta?.agentMeta?.model ?? n.fallbackModel;
const f = r.meta?.agentMeta?.provider ?? n.fallbackProvider;
const p = asPositiveFiniteNumber(r.meta?.agentMeta?.contextTokens);
const { contextTokens: m, authoredContextTokens: h } = (await cronContextRuntimeLoader.load()).resolveModelContextTokenProjection({
cfg: t.cfgWithAgentDefaults,
provider: f,
model: d,
allowAsyncLoad: false
});
const g = normalizeOptionalString(r.meta?.agentMeta?.agentHarnessId);
const _ = resolveTrustedSessionContextTokens({
entry: t.cronSession.sessionEntry,
provider: f,
model: d,
agentHarnessId: g
});
const v = resolveProjectedSessionContextTokens({
entry: t.cronSession.sessionEntry,
provider: f,
model: d,
agentHarnessId: g,
resolvedContextTokens: m,
authoredContextTokens: h
});
const y = p ?? v ?? 2e5;
const b = _ !== void 0 && (t.cronSession.sessionEntry.modelSelectionLocked === true || h === void 0 && v === _);
const x = p !== void 0 ? r.meta?.agentMeta?.contextTokensSource ?? "resolved" : b ? t.cronSession.sessionEntry.contextTokensSource : "resolved";
if (!e.isAborted()) {
setCronSessionRuntimeModel({
entry: t.cronSession.sessionEntry,
provider: f,
model: d
});
setCronSessionAgentHarnessId({
entry: t.cronSession.sessionEntry,
agentHarnessId: g
});
t.cronSession.sessionEntry.contextTokens = y;
t.cronSession.sessionEntry.contextTokensSource = x;
}
if (hasNonzeroUsage(c) || hasNonzeroUsage(r.meta?.agentMeta?.usage)) {
const e = deriveSessionTotalTokens({
usage: l,
contextTokens: y,
promptTokens: u
});
if (typeof e === "number" && Number.isFinite(e) && e > 0) {
t.cronSession.sessionEntry.totalTokens = e;
t.cronSession.sessionEntry.totalTokensFresh = true;
t.cronSession.sessionEntry.totalTokensVersion = 1;
} else {
t.cronSession.sessionEntry.totalTokens = void 0;
t.cronSession.sessionEntry.totalTokensFresh = false;
t.cronSession.sessionEntry.totalTokensVersion = void 0;
}
}
const S = {
model: d,
provider: f,
usage: await e.settleUsage(y)
};
if (e.isAborted()) return t.withRunSession({
status: "error",
error: e.abortReason(),
replyDisposition: i,
diagnostics: mergeCronRunDiagnostics(t.preflightDiagnostics, createCronRunDiagnosticsFromAgentResult(r, { finalStatus: "error" }), createCronRunDiagnosticsFromError("cron-setup", e.abortReason())),
...S
});
const C = resolveCronPayloadOutcome({
payloads: s,
terminalReplyDisposition: i,
runLevelError: r.meta?.error,
failureSignal: r.meta?.failureSignal,
finalAssistantVisibleText: i === "visible" ? r.meta?.finalAssistantVisibleText : void 0,
preferFinalAssistantVisibleText: (await resolveCronChannelOutputPolicy(t.resolvedDelivery.channel, { deliveryRequested: t.deliveryRequested })).preferFinalAssistantVisibleText
});
if (r.meta?.aborted === true && !C.hasFatalErrorPayload) {
const e = normalizeOptionalString(r.meta.error?.message) ?? "cron isolated agent run aborted";
await cleanupRunSession("cron-delete-after-run-aborted");
return t.withRunSession({
status: "error",
error: e,
replyDisposition: i,
diagnostics: mergeCronRunDiagnostics(t.preflightDiagnostics, createCronRunDiagnosticsFromAgentResult(r, { finalStatus: "error" }), createCronRunDiagnosticsFromError("agent-run", e)),
...S
});
}
const { deliveryDisposition: w, hasFatalStructuredErrorPayload: T, pendingPresentationWarningError: E } = C;
let { synthesizedText: D, deliveryPayloads: O, summary: k, outputText: A, hasFatalErrorPayload: j, embeddedRunError: M } = C;
if (o && !j && w.kind === "visible") O = [...(r.payloads ?? []).filter(shouldSuppressReasoningPayload), ...O];
const N = r.meta?.terminalToolFailure;
const P = isEmbeddedRunTerminalToolFailure(N);
if (j && P) k = CODE_MODE_MCP_CATALOG_MISS_MESSAGE;
const F = createCronRunDiagnosticsFromAgentResult(r, { finalStatus: j ? "error" : "ok" });
const I = mergeCronRunDiagnostics(t.preflightDiagnostics, F);
const resolveRunOutcome = (n) => {
const r = n?.disposition;
const o = r?.kind === "error" && r.errorKind !== "delivery-target" ? r : void 0;
const s = j && !o;
const c = M ?? "cron isolated run returned an error payload";
const l = r && s ? void 0 : n?.deliveryError;
const u = l ?? o?.error;
const d = o ? {} : r && !s ? {
summary: n?.summary,
outputText: n?.outputText
} : {
summary: k,
outputText: A
};
return t.withRunSession({
status: o || j ? "error" : "ok",
...o ? {
error: o.error,
...o.errorKind ? { errorKind: o.errorKind } : {}
} : j ? { error: c } : {},
...d,
result: a || z || r?.kind === "pending" ? void 0 : e.automationResult,
...e.automationResult && !a && !z && !j && !o && r?.kind !== "pending" ? { summary: e.automationResult.outcome === "no_change" ? void 0 : e.automationResult.summary } : {},
replyDisposition: i,
deliveryState: n?.deliveryState,
delivered: s && r?.kind === "pending" ? void 0 : o?.delivered ?? n?.delivered,
deliveryAttempted: n?.deliveryAttempted,
deliveryError: l,
deliverySuppressionReason: n?.deliverySuppressionReason,
delivery: n?.delivery,
diagnostics: mergeCronRunDiagnostics(I, n?.diagnostics, s && !P ? createCronRunDiagnosticsFromError("agent-run", c) : void 0, u ? createCronRunDiagnosticsFromError("delivery", u) : void 0),
...S
});
};
const L = hasOwedSessionSpawn(r.acceptedSessionSpawns);
const R = !j && w.kind !== "visible";
const z = L && (R || O.length === 0 && normalizeOptionalString(D) === void 0);
if (z && R) {
O = [];
D = void 0;
k = void 0;
A = void 0;
}
const ee = t.deliveryRequested && R && !z;
const B = e.automationResult?.outcome === "no_change" && !j && !a && !z;
const V = !t.resolvedDelivery.ok ? t.resolvedDelivery.deliverySuppressionReason : void 0;
const H = resolveSourceDeliveryOutcome(t.sourceDelivery, {
didSendViaMessageTool: r.didSendViaMessagingTool,
messageToolSentTargets: r.messagingToolSentTargets
});
const U = i === "silent";
if (T && t.deliveryRequested) {
await cleanupRunSession("cron-delete-after-run-fatal-error");
const e = buildCronDeliveryTrace({
deliveryPlan: t.deliveryPlan,
resolvedDelivery: t.resolvedDelivery,
sourceDeliveryOutcome: H,
fallbackUsed: false,
delivered: H.verifiedMessageToolDelivery
});
return resolveRunOutcome({
delivered: H.verifiedMessageToolDelivery,
deliveryAttempted: H.verifiedMessageToolDelivery,
delivery: e
});
}
e.markCronRunSessionCleanupHandled();
const { dispatchCronDelivery: W } = await loadCronDeliveryRuntime();
const G = await W({
cfgWithAgentDefaults: t.cfgWithAgentDefaults,
deps: t.input.deps,
job: t.input.job,
deliveryAttemptFence: t.input.deliveryAttemptFence,
agentId: t.agentId,
agentSessionKey: t.agentSessionKey,
sourceSessionKey: t.sourceSessionKey,
sourceSessionGeneration: t.sourceSessionGeneration,
runSessionKey: t.runSessionKey,
sessionId: t.currentRunSessionId(),
lifecycleRevision: t.cronSession.lifecycleRevision,
sessionUpdatedAt: t.cronSession.sessionEntry.updatedAt,
beforeSessionDelete: e.beforeSessionDelete,
runStartedAt: n.runStartedAt,
timeoutMs: t.timeoutMs,
resolvedDelivery: t.resolvedDelivery,
deliveryPlan: t.deliveryPlan,
deliveryRequested: t.deliveryRequested,
undeliveredRunStatus: j || E ? "error" : "ok",
skipDelivery: V ?? (B ? "silent" : ee ? U ? "silent" : w.kind : void 0),
spawnOnlyHandoff: z,
sourceDeliveryOutcome: H,
deliveryBestEffort: t.input.job.delivery?.bestEffort === true,
deliveryPayloads: O,
synthesizedText: D,
ttsAuto: t.cronSession.sessionEntry.ttsAuto,
summary: k,
outputText: A,
abortSignal: t.input.abortSignal ?? t.input.signal,
isAborted: e.isAborted,
abortReason: e.abortReason
});
const K = buildCronDeliveryTrace({
deliveryPlan: t.deliveryPlan,
resolvedDelivery: t.resolvedDelivery,
sourceDeliveryOutcome: H,
fallbackUsed: t.deliveryRequested && G.deliveryAttempted && !H.satisfiesSourceDelivery,
delivered: G.delivered
});
if (!G.disposition) {
k = G.summary;
A = G.outputText;
}
if (E && G.delivered !== true) {
j = true;
M = E;
}
return resolveRunOutcome({
...G,
delivery: K
});
}
//#endregion
//#region src/cron/isolated-agent/run-current-context.ts
const CURRENT_CONTEXT_RAW_MESSAGES_MAX = 220;
const CURRENT_CONTEXT_READ_MAX_BYTES = 262144;
const CURRENT_CONTEXT_MAX_LINE_CHARS = 220;
const CURRENT_CONTEXT_MAX_BLOCK_CHARS = 1400;
const CURRENT_CONTEXT_HEADER = "Recent conversation:";
function truncateContextLine(e, t) {
const n = `- ${e === "user" ? "User" : "Assistant"}: `;
const r = CURRENT_CONTEXT_MAX_LINE_CHARS - n.length;
if (t.length <= r) return `${n}${t}`;
return `${n}${truncateUtf16Safe(t, r - 3).trimEnd()}...`;
}
function formatCurrentConversationContext(e) {
const t = projectChatDisplayMessages(e, {
maxChars: CURRENT_CONTEXT_MAX_LINE_CHARS,
resolveCronJobName: () => void 0
}).flatMap((e) => {
if (!e || typeof e !== "object" || Array.isArray(e)) return [];
const t = e;
if (t.role !== "user" && t.role !== "assistant") return [];
const n = extractTextFromChatContent(t.content);
return n ? [truncateContextLine(t.role, n)] : [];
}).slice(-10);
while (t.length > 0 && `${CURRENT_CONTEXT_HEADER}\n${t.join("\n")}`.length > CURRENT_CONTEXT_MAX_BLOCK_CHARS) t.shift();
return t.length > 0 ? `${CURRENT_CONTEXT_HEADER}\n${t.join("\n")}` : void 0;
}
async function buildCurrentConversationContextBlock(e, t = {}) {
const n = e.sourceSessionEntry.sessionId?.trim();
if (!n) return;
try {
const r = await (t.readSessionMessages ?? readSessionMessagesAsync)({
agentId: e.agentId,
sessionEntry: e.sourceSessionEntry,
sessionId: n,
sessionKey: e.sourceSessionKey,
storePath: e.storePath
}, {
mode: "recent",
maxBytes: CURRENT_CONTEXT_READ_MAX_BYTES,
maxLines: CURRENT_CONTEXT_RAW_MESSAGES_MAX,
maxMessages: CURRENT_CONTEXT_RAW_MESSAGES_MAX
});
return formatCurrentConversationContext(Array.isArray(r) ? r : []);
} catch {
return;
}
}
//#endregion
//#region src/cron/isolated-agent/run-automation-context.ts
/** Compose the admitted job message with its bounded conversation and receipt-owned prompt context. */
async function resolveCronAutomationMessage(e) {
const { job: t, sourceSessionKey: n, sourceEntry: r } = e;
const i = t.sessionTarget === "current" && t.payload.kind === "agentTurn" && n && r ? await buildCurrentConversationContextBlock({
agentId: e.agentId,
sourceSessionEntry: r,
sourceSessionKey: n,
storePath: e.storePath
}) : void 0;
const a = await applyLegacyHeartbeatPromptContribution({
cfg: e.cfg,
jobId: t.id,
name: t.name,
agentId: e.agentId,
sessionKey: e.runSessionKey,
prompt: t.payload.kind === "agentTurn" ? t.payload.message : e.message,
assertCurrent: e.assertCurrent
});
return i ? `${i}\n\n${a}` : a;
}
/** Keep hook wrapping before scratch while preparing one admitted automation prompt. */
async function prepareCronAutomationPrompt(e) {
const t = await resolveCronAutomationMessage(e);
const n = await buildCronCommandBody({
...e,
message: t
});
const r = await readCronScratchSnapshot(e.cronStorePath ?? await resolveCronJobsStorePathFromConfigAsync(e.cfg), {
kind: "job",
jobId: e.job.id,
createdAtMsFallback: e.job.createdAtMs
}, {}, {
assertCurrent: e.assertCurrent,
signal: e.signal
});
return {
...n,
commandBody: appendCronJobScratchPrompt(n.commandBody, r?.state.scratch)
};
}
//#endregion
//#region src/cron/isolated-agent/run-command-preflight.ts
/** Rejects deterministic command prompts whose stored cap cannot execute them. */
function resolveCronCommandPromptPreflight(e) {
if (e.payload.kind !== "agentTurn" || classifyCronAgentTurnShellPrompt({
...e.payload,
toolsAllow: resolveCronRunToolsAllow(e)
}) !== "commandPromptWithoutShellAccess") return;
const t = `Automation ${e.id} cannot run its requested command because the agent prompt contains a "Command to run:" block but toolsAllow does not grant shell/process access. No command was executed. Recreate it as a command automation with \`openclaw automations add ... --command "<shell>"\`, or explicitly reauthorize this job from a trusted operator shell with \`openclaw automations edit ${e.id} --tools exec,process\`.`;
return {
status: "error",
error: t,
diagnostics: createCronRunDiagnosticsFromError("cron-preflight", t)
};
}
//#endregion
//#region src/cron/isolated-agent/run-prepare-runtime.ts
/** Lazy preparation runtimes and session lifecycle helpers for cron runs. */
const sessionAccessorRuntimeLoader = createLazyImportLoader(() => import("./session-accessor-DTtHAol5.mjs"));
const cronAuthProfileRuntimeLoader = createLazyImportLoader(() => import("./run-auth-profile.runtime.js"));
async function loadSessionAccessorRuntime() {
return await sessionAccessorRuntimeLoader.load();
}
function createCronSessionRowWriter(e) {
const { agentId: t, agentSessionKey: n } = e;
let r = false;
return async ({ storePath: i, sessionKey: a, operation: o, resetBoundary: s, assertCommitAllowed: c }) => {
const assertCurrent = () => {
e.assertCurrent?.();
c?.();
};
if (s) {
const [{ applySessionEntryLifecycleMutation: e }, { projectCronSessionEntry: n }] = await Promise.all([loadSessionAccessorRuntime(), import("./session-entry-patch-operation-CucvtUFg.mjs")]);
let r = o.next;
await e({
activeSessionKey: a,
agentId: t,
storePath: i,
commitGuard: assertCurrent,
upserts: [{
sessionKey: a,
resetBoundary: s,
buildEntry: ({ currentEntry: e }) => r = n(o, e)
}],
skipMaintenance: true
});
return r;
}
const { applySessionEntryOperation: l } = await import("./session-accessor.sqlite-entry-JpsCiqbQ.mjs");
const u = await l({
storePath: i,
sessionKey: a,
agentId: t
}, o, {
fallbackEntry: o.next,
replaceEntry: true,
skipMaintenance: r || a !== n,
workerGuard: { assertCurrent }
});
if (a === n) r = true;
return u;
};
}
function hasConfiguredAuthProfiles(e) {
return Boolean(e.auth?.profiles && Object.keys(e.auth.profiles).length > 0) || Boolean(e.auth?.order && Object.keys(e.auth.order).length > 0);
}
/**
* Resolves the run's auth profile, skipping the lazy runtime entirely when no
* override, configured profile, or store source exists for it to find. Auth
* resolution may mutate session state, so it uses the store and key that
* persistence will write.
*/
async function resolveCronAuthSelection(e) {
if (!Boolean(e.cronSession.sessionEntry.authProfileOverride?.trim()) && !hasConfiguredAuthProfiles(e.cfg) && !await hasAnyAuthProfileStoreSourceAsync(e.agentDir)) return;
return await (await cronAuthProfileRuntimeLoader.load()).resolveSessionAuthSelection({
agentId: e.agentId,
cfg: e.cfg,
provider: e.provider,
modelId: e.modelId,
...e.configuredProfileId ? { configuredProfileId: e.configuredProfileId } : {},
agentDir: e.agentDir,
sessionEntry: e.cronSession.sessionEntry,
sessionStore: e.cronSession.store,
sessionKey: e.sessionKey,
storePath: e.cronSession.storePath,
isNewSession: e.isNewSession
});
}
async function retireRolledCronSessionMcpRuntime(e) {
if (e.job.sessionTarget === "isolated") return;
const t = normalizeOptionalString(e.cronSession.previousSessionId);
const n = normalizeOptionalString(e.cronSession.sessionEntry.sessionId);
if (!t || t === n) return;
await retireSessionMcpRuntime({
sessionId: t,
reason: "cron-session-rollover",
onError: (t, n) => {
logWarn(`[cron:${e.job.id}] Failed to dispose retired bundle MCP runtime for session ${n}: ${String(t)}`);
}
});
}
//#endregion
//#region src/cron/isolated-agent/run-timeout.ts
/** Converts cron payload timeout overrides into embedded-runner timeout signals. */
/** Converts explicit cron payload timeoutSeconds into a timer-safe millisecond override signal. */
function resolveCronRunTimeoutOverrideMs(e) {
const t = Math.floor((e ?? 0) * 1e3);
return Number.isFinite(e) && t > 0 ? Math.min(t, MAX_TIMER_TIMEOUT_MS) : void 0;
}
//#endregion
//#region src/cron/isolated-agent/run-workspace.ts
/** Keep workspace selection, provisioning, and failed-preparation lease cleanup together. */
async function prepareCronSessionWorkspace(e) {
const { sessionKey: t } = e;
const n = e.input.abortSignal ?? e.input.signal;
const assertCurrent = () => {
n?.throwIfAborted();
if (!e.sessionPreparationEffect.isActive()) throw new CronSessionLifecycleClaimError(t);
if (e.childParent?.binding) e.childParent.assertCurrent();
};
const r = await resolveCronSessionWorkspace({
cfg: e.cfg,
agentId: e.agentId,
sessionTarget: e.input.job.sessionTarget,
admissionSource: e.input.admissionSource,
ownerSessionKey: e.input.job.owner?.sessionKey,
sessionKey: e.sessionKey,
entry: e.cronSession.initialSessionEntry,
defaultWorkspaceDir: e.defaultWorkspaceDir,
parentBinding: e.childParent?.binding,
assertCurrent
});
try {
const t = await (await import("./acp-workspace-provisioning-B-ONZXXm.mjs")).resolveAcpAgentWorkspaceProvisioningForTurn({
cfg: e.cfg,
agentId: e.agentId,
workspaceDir: e.defaultWorkspaceDir,
cwd: r.cwd,
sessionKey: e.sessionKey,
sessionEntry: e.cronSession.sessionEntry
});
assertCurrent();
await ensureAgentWorkspace({
dir: e.defaultWorkspaceDir,
ensureBootstrapFiles: !e.agentCfg.skipBootstrap && !e.isFastTestEnv,
skipOptionalBootstrapFiles: e.agentCfg.skipOptionalBootstrapFiles,
provisioning: t,
guard: { assertHost: assertCurrent }
});
assertCurrent();
return r;
} catch (e) {
await r.lease?.release();
throw e;
}
}
/** Resolve only persisted session bindings; the job prompt never supplies filesystem authority. */
async function resolveCronSessionWorkspace(e) {
const t = e.parentBinding ?? resolveTargetBinding(e);
if (!t) return { workspaceDir: e.defaultWorkspaceDir };
const { sessionKey: n, entry: r } = t;
if (!r) return { workspaceDir: e.defaultWorkspaceDir };
const i = resolveIngressWorkspaceOverrideForSessionRun({
spawnedBy: r.spawnedBy,
workspaceDir: r.spawnedWorkspaceDir,
cwd: r.spawnedCwd
});
const a = normalizeOptionalString(r.spawnedCwd);
const o = resolveCronSessionWorkspaceOwnershipError({
...e,
sessionKey: n,
ownerSessionKey: e.ownerSessionKey,
hasWorkspaceBinding: Boolean(i || a || r.worktree)
});
if (o) throw new CronSessionLifecycleClaimError(e.sessionKey, o);
const s = i ? await fs.realpath(resolveUserPath(i)) : e.defaultWorkspaceDir;
const c = a ? await fs.realpath(resolveUserPath(a)) : void 0;
e.assertCurrent();
return await prepareCronSessionWorktree({
sessionKey: n,
entry: r,
workspaceDir: s,
cwd: c,
assertCurrent: e.assertCurrent
});
}
/** The in-session target's own row; it must be the session this run executes in. */
function resolveTargetBinding(e) {
const t = resolveCronSessionTargetSessionKey(e.sessionTarget);
if (!t) return;
if (resolveCronAgentSessionKey({
sessionKey: t,
agentId: e.agentId,
cfg: e.cfg,
mainKey: e.cfg.session?.mainKey
}) !== e.sessionKey) throw new CronSessionLifecycleClaimError(e.sessionKey, "Bound automation session is mismatched.");
return {
sessionKey: e.sessionKey,
entry: e.entry
};
}
//#endregion
//#region src/cron/isolated-agent/run-prepare.ts
/** Session identity and context preparation for isolated cron runs. */
async function prepareCronRunContext(e) {
try {
var t = _usingCtx();
const n = await resolveCronRunPreparation(e);
if (!n.ok) return n;
t.a(n.resources);
const prepareSession = () => withCronSessionPreparation(n.admission, async (t) => {
const r = await n.prepare(t);
const i = e.runPrepared;
if (!r.ok) return r;
if (!i) return {
...r,
completed: void 0
};
await n.resources.disposeAsync();
return await withSessionTurn({
sessionKey: r.context.runSessionKey,
sessionId: r.context.runSessionId,
agentId: n.admission.agentId,
storePath: r.context.cronSession.storePath,
abortSignal: t
}, async () => ({
...r,
completed: await i(r.context)
}));
});
return n.runtimeLease ? await n.runtimeLease.run(prepareSession) : await prepareSession();
} catch (e) {
t.e = e;
} finally {
await t.d();
}
}
async function resolveCronRunPreparation(e) {
try {
var t = _usingCtx();
let { input: n } = e;
n.assertCurrent?.();
const r = resolveCronCommandPromptPreflight(n.job);
if (r) return {
ok: false,
result: r
};
const i = resolveCronActiveRuntimeConfig(n.cfg);
const a = n.agentId?.trim() || n.job.agentId?.trim();
const o = (a ? normalizeAgentId(a) : void 0) ?? parseAgentSessionKey(n.job.sessionKey ?? n.sessionKey)?.agentId;
const s = resolveCronJobEffectiveAgentId({ agentId: o }, tryResolveAmbientOwnerAgentId(i));
await waitForAgentDatabaseWriteAdmission(s, { signal: n.abortSignal ?? n.signal });
const c = t.a(new AsyncDisposableStack());
let l;
const u = await loadPublishedGatewayReplyDispatchRuntime({
agentId: s,
demand: "scheduled",
abortSignal: n.abortSignal ?? n.signal,
onRuntimeLease: (e) => {
l = c.use(scopePreparedModelRuntimeLease(e));
}
});
const d = await resolveCronModelSelectionOwner({
cfg: i,
publishedRuntime: u,
...o ? {
agentId: s,
requiredAgentId: o,
agentDir: resolveAgentDir(i, s),
workspaceDir: resolveAgentWorkspaceDir(i, s)
} : {}
});
const { agentId: f, agentDir: p } = d;
const m = o ? resolveAgentConfig(d.config, f) : void 0;
const { runtimeConfig: h, agentDefaults: g } = resolveCronAgentConfig({
config: d.config,
agentConfigOverride: m
});
const _ = (n.sessionKey?.trim() || `cron:${n.job.id}`).trim();
const v = n.job.sessionTarget === "current" ? n.job.sessionKey?.trim() : void 0;
const y = isDetachedCronSessionTarget(n.job.sessionTarget) || Boolean(v);
const b = _.startsWith("cron:") || isCronSessionKey(_);
const x = y && !b ? `cron:${n.job.id}` : _;
const S = resolveCronAgentSessionKey({
sessionKey: x,
agentId: f,
mainKey: h.session?.mainKey,
cfg: h
});
const C = resolveCronAgentSessionKey({
sessionKey: v ?? _,
agentId: f,
mainKey: h.session?.mainKey,
cfg: h
});
const w = v && C !== S ? C : void 0;
const T = (n.job.payload.kind === "agentTurn" ? n.job.payload.externalContentSource : void 0) ?? resolveHookExternalContentSource(_);
const E = T === "gmail";
return {
ok: true,
resources: c.move(),
runtimeLease: l,
admission: {
agentId: f,
storePath: resolveSessionStorePathCore(h.session?.store, { agentId: f }),
sessionKey: S,
signal: n.abortSignal ?? n.signal,
onInterrupt: e.onLifecycleInterrupt,
onLaneWait: n.onLaneWait
},
prepare: async (e) => {
n = {
...n,
abortSignal: e
};
return await prepareAdmittedSession();
}
};
async function prepareAdmittedSession() {
const t = Date.now();
if (n.job.operatorSource) {
const e = resolveCronDeliverySessionKey(n.job);
if (!(e ? await loadCronSessionEntryLatest(resolveSessionStorePathCore(h.session?.store, { agentId: f }), e) : void 0)?.sessionId) throw new Error("Scheduled operator source conversation is unavailable");
}
const r = resolveCreatorSandbox(h, { actor: n.job.createdActor }) ?? n.occurrence.childParent?.sandbox;
const i = y || _.startsWith("cron:");
const a = await prepareCronSession({
cfg: h,
sessionKey: S,
sourceSessionKey: w,
skillLibrarySelections: n.job.skillLibrarySelections,
agentId: f,
nowMs: t,
forceNew: y,
exactRunSession: i,
hookExternalContentSource: T,
inferenceCaptured: Boolean(n.job.inferenceBinding?.runtime)
});
const o = w ? a.store[w] : void 0;
const s = n.job.sourceConversation ? {
sessionId: n.job.sourceConversation.sessionId,
lifecycleRevision: void 0
} : o && {
sessionId: o.sessionId,
lifecycleRevision: o.lifecycleRevision
};
const c = isAgentHarnessSessionKey(S);
if (a.initialSessionEntry?.modelSelectionLocked === true) throw new Error(c ? AGENT_HARNESS_SESSION_KEY_RESERVED_MESSAGE : AGENT_HARNESS_SESSION_ID_LOCKED_MESSAGE);
if (c && !a.initialSessionEntry) throw new Error(AGENT_HARNESS_SESSION_KEY_RESERVED_MESSAGE);
const l = a.sessionEntry.sessionId;
const currentRunSessionId = () => a.sessionEntry.sessionId ?? l;
const v = i ? `${S}:run:${l}` : S;
const b = await beginCronPreparationEffect({
agentId: f,
cronSession: a,
agentSessionKey: S,
runSessionKey: v,
usesDetachedRunSession: y,
signal: n.abortSignal ?? n.signal,
onInterrupt: e.onLifecycleInterrupt
});
let x;
let C;
let D = false;
try {
const c = await prepareCronSessionWorkspace({
cfg: h,
agentId: f,
input: n,
agentCfg: g,
sessionKey: S,
cronSession: a,
defaultWorkspaceDir: d.workspaceDir,
sessionPreparationEffect: b,
isFastTestEnv: e.isFastTestEnv,
childParent: n.occurrence.childParent
});
C = c.lease;
const O = c.workspaceDir;
const k = createCronSessionRowWriter({
agentId: f,
agentSessionKey: S,
assertCurrent: n.assertCurrent
});
const A = createPersistCronSessionEntry({
cronSession: a,
agentSessionKey: S,
createdActor: n.job.createdActor,
sandbox: r,
workspaceDir: O,
persistSessionEntry: k
});
const withRunSession = (e) => ({
...e,
sessionId: currentRunSessionId(),
sessionKey: v
});
if (!a.sessionEntry.label?.trim() && _.startsWith("cron:")) {
const e = typeof n.job.name === "string" && n.job.name.trim() ? n.job.name.trim() : n.job.id;
a.sessionEntry.label = `Automation: ${e}`;
}
const j = await resolveCronModelSelection({
cfg: h,
owner: d,
agentConfigOverride: m,
sessionEntry: a.sessionEntry,
payloadModel: n.job.payload.kind === "agentTurn" ? n.job.payload.model : void 0,
isGmailHook: E,
agentId: f,
agentDir: p,
workspaceDir: O
});
if (!j.ok) return {
ok: false,
result: withRunSession({
status: "error",
error: j.error,
diagnostics: createCronRunDiagnosticsFromError("cron-preflight", j.error)
})
};
const M = j.cfgWithAgentDefaults;
const { useSubagentFallbacks: N, inheritDefaultFallbacksForAgentStringModel: P } = j;
const F = j.modelSource === "session" ? resolveSessionModelOverrideSource(a.sessionEntry) ?? void 0 : void 0;
const I = await resolveCronPreflight({
cfg: M,
job: n.job,
agentId: d.agentId,
provider: j.provider,
model: j.model,
useSubagentFallbacks: N,
inheritDefaultFallbacksForAgentStringModel: P,
sessionModelOverrideSource: F
});
if (!I.ok) {
logWarn(`[cron:${n.job.id}] ${I.reason}`);
return {
ok: false,
result: withRunSession({
status: "skipped",
error: I.reason,
diagnostics: createCronRunDiagnosticsFromError("model-preflight", I.reason, { severity: "warn" }),
provider: j.provider,
model: j.model
})
};
}
const { provider: L, model: R, modelFallbacksOverride: z, runtimePluginCandidates: ee } = I;
const B = resolveCronRuntimeSessionEntry(n.job.inferenceBinding, a.sessionEntry);
const V = resolveEffectiveAgentRuntime({
cfg: M,
provider: L,
modelId: R,
agentId: d.agentId,
sessionKey: S,
sessionEntry: B
});
const H = await resolveCronThinkingSelection({
cfg: M,
owner: d,
provider: L,
model: R,
agentRuntime: V,
jobThinking: n.job.payload.kind === "agentTurn" ? n.job.payload.thinking : void 0,
hookThinking: E ? h.hooks?.gmail?.thinking : void 0,
sessionThinking: a.sessionEntry.thinkingLevel
});
const { requestedLevel: U, level: W, supported: G } = resolveThinkingSelectionCore({
cfg: M,
agentId: d.agentId,
provider: L,
model: R,
level: H.requestedThinkLevel,
catalog: H.catalog,
agentRuntime: V
});
if (!G && W !== U) logWarn(`[cron:${n.job.id}] Thinking level "${U}" is not supported for ${L}/${R}; using "${W}" for this candidate.`);
x = await acquireAgentRunPreparedModelRuntime({
config: d.config,
agentId: f,
agentDir: p,
workspaceDir: O,
allowGatewaySubagentBinding: true,
runtimePluginSelections: ee.map((e) => {
const t = resolveSessionRuntimeOverrideForProvider({
provider: e.provider,
entry: B,
cfg: M
});
return t ? {
provider: e.provider,
modelId: e.model,
runtime: t,
agentId: f
} : {
provider: e.provider,
modelId: e.model,
agentId: f
};
})
}, {
catalogMode: "static",
...u ? { pluginGeneration: u.pluginGeneration } : { pluginMetadataSnapshot: d.metadataSnapshot },
abortSignal: n.abortSignal ?? n.signal
});
const K = x.snapshot.config;
const q = n.job.payload.kind === "agentTurn" ? n.job.payload.timeoutSeconds : void 0;
const te = resolveAgentTimeoutMs({
cfg: M,
overrideSeconds: q
});
const ne = resolveCronRunTimeoutOverrideMs(q);
const J = n.job.payload.kind === "agentTurn" ? {
...n.job.payload,
toolsAllow: resolveCronRunToolsAllow(n.job)
} : null;
const Y = K.models?.providers?.[L];
const X = findModelInCatalog(H.catalog, L, R);
const Z = Y?.models?.find((e) => e.id === R);
const re = X?.api ?? Z?.api ?? Y?.api;
const ie = await createCronToolsAllowPreflightDiagnostics({
cfg: K,
jobId: n.job.id,
provider: L,
model: R,
modelApi: re,
modelBaseUrl: X?.baseUrl ?? Z?.baseUrl ?? Y?.baseUrl,
modelParams: X?.params ?? Z?.params,
agentId: d.agentId,
agentDir: d.agentDir,
sessionKey: S,
agentPayload: J
});
const { deliveryPlan: ae, deliveryRequested: oe, resolvedDelivery: se, sourceDelivery: Q, deliverySystemPrompt: ce, messageToolFormatPrompt: le } = await resolveCronDeliveryContext({
cfg: K,
job: n.job,
agentId: f
});
const ue = {
extraSystemPromptStatic: ce,
sourceReplyDeliveryMode: i ? Q.sourceReplyDeliveryMode : await resolveSessionStableReplyMode({
cfg: K,
metadataSnapshot: x.snapshot.metadataSnapshot,
ctx: { CommandAuthorized: false },
sessionEntry: a.sessionEntry,
sessionAgentId: f,
sessionKey: v
}),
requireExplicitMessageTarget: i ? Q.messageTool.requireExplicitTarget : void 0
};
const { formattedTime: de, timeLine: fe } = resolveCronStyleNow(h, t);
const assertPreparationCurrent = () => {
n.assertCurrent?.();
(n.abortSignal ?? n.signal)?.throwIfAborted();
if (!b.isActive()) throw new CronSessionLifecycleClaimError(S);
};
const { sourcePromptPrefix: pe, isExternalHook: me, commandBody: he } = await prepareCronAutomationPrompt({
cfg: K,
job: n.job,
agentId: f,
runSessionKey: v,
message: n.message,
sourceSessionKey: w,
sourceEntry: o,
storePath: a.storePath,
cronStorePath: n.cronStorePath,
assertCurrent: assertPreparationCurrent,
signal: n.abortSignal ?? n.signal,
baseSessionKey: _,
hookExternalContentSource: T,
formattedTime: de,
timeLine: fe
});
const $ = await resolveCronSkillsSnapshot({
workspaceDir: O,
config: K,
agentId: f,
existingSnapshot: a.sessionEntry.skillsSnapshot,
librarySelections: a.sessionEntry.skillLibrarySelections,
isFastTestEnv: e.isFastTestEnv
});
if (!e.isFastTestEnv && $ !== a.sessionEntry.skillsSnapshot) a.sessionEntry = {
...a.sessionEntry,
skillsSnapshot: $
};
setCronSessionRuntimeModel({
entry: a.sessionEntry,
provider: L,
model: R
});
setCronSessionAgentHarnessId({
entry: a.sessionEntry,
agentHarnessId: V
});
a.sessionEntry.systemSent = true;
let ge = false;
try {
await A();
ge = true;
} catch (e) {
if (e instanceof CronSessionLifecycleClaimError) throw e;
logWarn(`[cron:${n.job.id}] Failed to persist pre-run session entry: ${String(e)}`);
if (r === "required" || a.sessionEntry.sandbox === "required") throw e;
}
await retireRolledCronSessionMcpRuntime({
job: n.job,
cronSession: a
});
const _e = n.job.runtimeAuthority ? void 0 : n.job.inferenceBinding ? {
profileId: n.job.inferenceBinding.profileId,
source: n.job.inferenceBinding.source
} : await resolveCronAuthSelection({
agentId: f,
cfg: K,
provider: L,
modelId: R,
...L === j.provider && j.configuredProfileId ? { configuredProfileId: j.configuredProfileId } : {},
agentDir: p,
cronSession: a,
sessionKey: S,
isNewSession: a.isNewSession && n.job.sessionTarget !== "isolated"
});
const ve = _e?.profileId;
const ye = {
provider: L,
model: R,
agentRuntimeOverride: resolveSessionRuntimeOverrideForProvider({
provider: L,
entry: B,
cfg: K
}),
authProfileId: ve,
authProfileIdSource: _e?.source
};
const be = i ? createCronRunContinuationSession({
cronSession: a,
runSessionKey: v,
createdActor: n.job.createdActor,
sandbox: r,
thinkingLevel: U,
toolsAllow: J?.toolsAllow,
toolsAllowIsDefault: J?.toolsAllowIsDefault,
scheduledToolPolicy: resolveCronScheduledToolPolicy({
toolsAllow: J?.toolsAllow,
scheduledToolPolicy: n.job.scheduledToolPolicy,
owner: n.job.owner
}),
scheduledToolCallerOrigin: n.job.toolsAllowProvenance?.callerOrigin,
toolsAllowExecTarget: n.job.toolsAllowExecTarget,
toolsAllowExecTargetRequirement: n.job.toolsAllowExecTargetRequirement,
cliSessionBindingFacts: ue
}) : void 0;
await be?.initialize();
D = true;
return {
ok: true,
context: {
input: n,
cfgWithAgentDefaults: K,
agentId: f,
agentCfg: g,
agentDir: p,
agentSessionKey: S,
sourceSessionKey: n.job.sourceConversation?.sessionKey ?? w,
sourceSessionGeneration: s,
runSessionId: l,
currentRunSessionId,
runSessionKey: v,
usesDetachedRunSession: y,
workspaceDir: O,
cwd: c.cwd,
workspaceLease: C,
commandBody: he,
inputProvenance: J && !me ? {
kind: "internal_system",
sourceTool: "cron",
sourcePromptPrefix: pe,
jobId: n.job.id,
runId: l,
sourceSessionKey: v
} : void 0,
cronSession: a,
sessionPreparationEffect: b,
persistSessionEntry: A,
preRunSessionPersisted: ge,
runContinuationSession: be,
withRunSession,
agentPayload: J,
deliveryPlan: ae,
resolvedDelivery: se,
deliveryRequested: oe,
deliverySystemPrompt: ce,
messageToolFormatPrompt: le,
sourceDelivery: Q,
cliSessionBindingFacts: ue,
suppressExecNotifyOnExit: ae.mode === "none",
skillsSnapshot: $,
liveSelection: ye,
useSubagentFallbacks: N,
inheritDefaultFallbacksForAgentStringModel: P,
sessionModelOverrideSource: F,
modelFallbacksOverride: z,
thinkingSelection: H,
timeoutMs: te,
preflightDiagnostics: ie,
runTimeoutOverrideMs: ne,
preparedModelRuntimeLease: x
}
};
} catch (e) {
try {
var O = _usingCtx();
O.a(x);
throw e;
} catch (e) {
O.e = e;
} finally {
await O.d();
}
} finally {
if (!D) {
b.release();
await C?.release();
}
}
}
} catch (e) {
t.e = e;
} finally {
await t.d();
}
}
//#endregion
//#region src/cron/isolated-agent/run.ts
const cronExecutorRuntimeLoader = createLazyImportLoader(() => import("./run-executor.runtime.js"));
const cronOperatorSourceLoader = createLazyImportLoader(() => import("./cron-operator-source-CNcfA08u.mjs"));
async function disposeCronRunContext(e) {
releaseAgentRunContext(e.runId, e.runContextOwnerToken);
if (e.ownsSessionRuntime) await retireSessionMcpRuntime({
sessionId: e.sessionId,
reason: "isolated-cron-dispose",
onError: (e, t) => {
logWarn(`[cron] Failed to retire MCP runtime during isolated cron dispose ${t}: ${String(e)}`);
}
}).catch(() => {});
e.cronSession.store = {};
}
/** Runs one isolated cron agent turn, including setup, execution, delivery, and persistence. */
async function runCronIsolatedAgentTurn(e) {
return await runWithDiagnosticTraceContext(createDiagnosticTraceContextFromActiveScope(), () => runCronIsolatedAgentTurnInTrace(e));
}
async function runCronIsolatedAgentTurnInTrace(e) {
try {
var t = _usingCtx();
e.assertCurrent?.();
const n = getAgentEventLifecycleGeneration();
const r = e.abortSignal ?? e.signal;
const i = new AbortController();
const a = r ? AbortSignal.any([r, i.signal]) : i.signal;
const isAborted = () => a?.aborted ?? false;
const abortReason = () => resolveCronAbortReasonText(a?.reason) ?? "cron: job execution timed out";
const o = isFastTestRuntimeEnv();
const s = t.a(new AsyncDisposableStack());
let c;
try {
c = await prepareCronRunContext({
input: {
...e,
abortSignal: a
},
isFastTestEnv: o,
onLifecycleInterrupt: () => i.abort(createAgentRunRestartAbortError()),
runPrepared: runPreparedCronTurn
});
} catch (e) {
if (e instanceof CronSessionLifecycleClaimError) return {
status: "error",
error: e.message,
errorClassification: { kind: "session-conflict" },
executionStarted: false,
admissionDisposition: e.admissionDisposition
};
throw e;
}
if (!c.ok) return {
...c.result,
admissionDisposition: "rejected"
};
if (c.completed) return c.completed;
throw new Error("Cron controller invocation completed without a run result");
async function runPreparedCronTurn(t) {
try {
var r = _usingCtx();
const o = s.use(t.preparedModelRuntimeLease);
if (t.runContinuationSession) s.defer(async () => {
try {
await withPluginRuntimeGenerationScope(o.snapshot, () => removeCronRunContinuationSessionIfIdle(t.runSessionKey));
} catch (t) {
logWarn(`[cron:${e.job.id}] Failed to remove unused run continuation: ${String(t)}`);
}
});
const c = { context: t };
const l = r.u(new DisposableStack());
r.a({ [Symbol.asyncDispose]: async () => {
await c.context.workspaceLease?.release();
} });
let u = true;
try {
return await withPreparedModelRuntimePluginGenerationScope(o.pluginGeneration, () => withPluginRuntimeGenerationScope(o.snapshot, async () => {
const t = randomUUID();
const r = c.context.cronSession.sessionEntry.sessionId;
const o = e.job.sessionTarget === "isolated";
let s;
let u = n;
let d = false;
const assertInvocationCurrent = () => {
e.assertCurrent?.();
a.throwIfAborted();
assertAgentRunLifecycleGenerationCurrent(n);
if (!c.context.sessionPreparationEffect.isActive()) throw new Error("Automation run owner is closed");
};
const resolveUnstartedTerminalMetadata = () => d ? void 0 : {
executionStarted: false,
providerStarted: false
};
let f;
const p = getCurrentSessionControllerOwner();
const resolveStartDeferral = () => {
const t = resolveCronActiveRuntimeConfig(e.cfg);
if (!isCronWithinActiveHours(e.job.activeHours, Date.now(), t.agents?.defaults?.userTimezone)) return "active-hours";
return e.job.idleOnly && !isCronExecutionIdle(t, e.job, c.context.agentId, c.context.runSessionKey, p) ? "busy" : void 0;
};
const awaitStartPolicy = async (t) => {
assertInvocationCurrent();
let n = resolveStartDeferral();
while (n === "busy" && e.waitForIdle) {
await e.waitForIdle(c.context.runSessionKey, a, p);
assertInvocationCurrent();
n = resolveStartDeferral();
}
if (!n) t?.();
return n;
};
const deferredResult = (e) => c.context.withRunSession({
status: "skipped",
executionStarted: false,
admissionDeferred: true,
admissionDeferredReason: e,
summary: "Automation admission deferred by its current window or foreground activity"
});
const notifyExecutionStarted = async (n) => {
assertInvocationCurrent();
const markStarted = () => {
d = true;
if (n?.lifecycleGeneration) u = n.lifecycleGeneration;
e.onExecutionStarted?.({
jobId: e.job.id,
agentId: c.context.agentId,
sessionId: c.context.currentRunSessionId(),
sessionKey: c.context.runSessionKey,
runId: t,
...n?.isFallback === true ? { isFallback: true } : {},
phase: "runner_entered",
provider: n?.provider ?? c.context.liveSelection.provider,
model: n?.model ?? c.context.liveSelection.model
});
};
if (d) {
markStarted();
return;
}
const r = await awaitStartPolicy(markStarted);
if (r) {
f = r;
const e = /* @__PURE__ */ new Error("Automation admission deferred by its current window or foreground activity");
i.abort(e);
throw e;
}
};
const notifyExecutionPhase = (t) => {
e.onExecutionPhase?.({
jobId: e.job.id,
agentId: c.context.agentId,
sessionId: c.context.currentRunSessionId(),
sessionKey: c.context.runSessionKey,
provider: c.context.liveSelection.provider,
model: c.context.liveSelection.model,
...t
});
};
const m = Date.now();
const h = isDiagnosticsEnabled(e.cfg);
const g = (() => {
try {
const e = createDiagnosticMessageLifecycle({
enabled: h,
sessionId: c.context.runSessionId,
sessionKey: c.context.runSessionKey,
agentId: c.context.agentId,
channel: "cron",
source: "cron-isolated",
startedAtMs: m,
trackSessionState: true
});
e.markProcessing();
if (h) logMessageDispatchStarted({
sessionId: c.context.runSessionId,
sessionKey: c.context.runSessionKey,
channel: "cron",
source: "cron-isolated"
});
return e;
} catch (e) {
c.context.sessionPreparationEffect.release();
throw e;
}
})();
let _ = "completed";
let v;
let y;
let b = false;
let x = [];
let S;
let C;
let w;
const settleUsage = async (e) => {
w ??= (async () => {
C = applyCronRunUsage(c.context, x);
await recordCronRunUsage({
prepared: c.context,
runs: x,
contextTokens: e
});
await c.context.persistSessionEntry();
await c.context.runContinuationSession?.seal({ basePersisted: true });
})();
await w;
return C;
};
let T;
const E = createAgentLifecycleTerminalBackstop({
runId: t,
sessionKey: c.context.runSessionKey,
startedAt: m,
getLifecycleGeneration: () => u,
resolveTerminationFields: (e) => resolveAgentRunErrorLifecycleFields(e, a)
});
try {
const n = await awaitStartPolicy();
if (n) return deferredResult(n);
assertAgentRunLifecycleGenerationCurrent(u);
s = claimAgentRunContext(t, {
sessionKey: c.context.runSessionKey,
sessionId: r,
agentId: c.context.agentId,
lifecycleGeneration: u,
cronRunsByJobId: /* @__PURE__ */ new Map([[e.job.id, {
nextCheckEnabled: e.job.pacing !== void 0 || isCronOneShotContinuationJob(e.job),
assertCurrent: assertInvocationCurrent
}]])
}, {
trackOwner: true,
ownsContext: true
});
const { executeCronRun: i } = await cronExecutorRuntimeLoader.load();
const o = e.job.operatorSource ? await (await cronOperatorSourceLoader.load()).restoreCronOperatorSource({
job: e.job,
agentId: c.context.agentId,
sessionKey: c.context.runSessionKey,
signal: a,
deliveryAttemptFence: e.deliveryAttemptFence
}) : void 0;
if (o) l.defer(o.release);
const d = {
...c.context,
operatorAuthority: o?.authority,
occurrence: e.occurrence,
runId: t,
cfg: e.cfg,
job: e.job,
trigger: e.trigger,
deliveryAttemptFence: e.deliveryAttemptFence,
lane: e.lane,
agentVerboseDefault: c.context.agentCfg?.verboseDefault,
persistRunContinuationSession: c.context.runContinuationSession?.sync,
abortSignal: a,
lifecycle: {
...E,
capture: (e, t, n) => E.capture(e, t, {
...n,
...resolveUnstartedTerminalMetadata()
})
},
onPromptAdmission: (e) => {
S?.close();
S = e;
},
onExecutionStarted: notifyExecutionStarted,
onExecutionPhase: notifyExecutionPhase,
onLaneWait: e.onLaneWait,
onPromptCompleted: (e) => {
x = e;
},
abortReason,
isAborted,
immutableThinkLevel: c.context.thinkingSelection.immutableThinkLevel,
thinkingCatalog: c.context.thinkingSelection.catalog,
loadThinkingCatalog: c.context.thinkingSelection.loadThinkingCatalog,
executionIdentity: e.executionIdentity,
admissionSource: e.admissionSource
};
const f = await c.context.sessionPreparationEffect.run(() => withAgentRunLifecycleGeneration(u, () => i(d)));
T = resolveCronAgentTerminalOutcome({
phase: "end",
data: f.runResult.meta,
operation: p,
signal: a
});
E.emit("end", f.runResult, resolveUnstartedTerminalMetadata());
y = resolveDiagnosticModelContentCapturePolicy(e.cfg).outputMessages ? resolveDiagnosticModelResponse(f.runResult) : void 0;
await S?.finish();
const m = getAgentRunContext(t)?.cronRunsByJobId?.get(e.job.id);
const h = m?.result;
if (m) m.closed = true;
const g = await finalizeCronRun({
automationResult: h,
prepared: c.context,
execution: f,
abortReason,
isAborted,
settleUsage,
markCronRunSessionCleanupHandled: () => {
b = true;
},
beforeSessionDelete: c.context.sessionPreparationEffect.release
});
if (g.status === "error") {
_ = "error";
v = g.error;
g.errorClassification = resolveCronAgentErrorClassification(T);
g.interruptedByRestart = resolveAgentRunErrorLifecycleFields(void 0, a).stopReason === "restart";
}
const C = consumeCronNextCheckProposal(t, e.job.id);
return g.status !== "ok" || C === void 0 ? g : {
...g,
nextCheck: { delayMs: C }
};
} catch (n) {
T ??= resolveCronAgentTerminalOutcome({
phase: "error",
error: n,
data: isCommandLaneTaskTimeoutError(n) ? { stopReason: "timeout" } : void 0,
operation: p,
signal: a
});
E.emit("error", n, resolveUnstartedTerminalMetadata());
const r = resolveAgentRunErrorLifecycleFields(n, a).stopReason === "restart";
await S?.finish();
consumeCronNextCheckProposal(t, e.job.id);
if (f && !d) return deferredResult(f);
const i = isAborted() || isCommandLaneTaskTimeoutError(n, "cron-nested");
const o = i ? abortReason() : normalizeCronRunErrorText(n);
const s = findErrorProperty(n, (e) => isFailoverError(e) ? e.reason : void 0);
_ = "error";
v = o;
const l = n instanceof CronSessionLifecycleClaimError ? n.admissionDisposition : !d ? "rejected" : void 0;
if (x.length > 0) try {
await settleUsage();
} catch (t) {
if (t !== n) logWarn(`[cron:${e.job.id}] Failed to settle completed prompt usage: ${String(t)}`);
}
return c.context.withRunSession({
status: "error",
error: o,
interruptedByRestart: r,
errorClassification: n instanceof CronOperatorSourceError ? { kind: "permanent" } : n instanceof CronSessionLifecycleClaimError ? { kind: "session-conflict" } : resolveCronAgentErrorClassification(T, s),
executionStarted: d,
usage: C,
...l ? { admissionDisposition: l } : {},
provider: c.context.liveSelection.provider,
model: c.context.liveSelection.model,
diagnostics: mergeCronRunDiagnostics(c.context.preflightDiagnostics, createCronRunDiagnosticsFromError(i ? "cron-setup" : "agent-run", i ? o : n))
});
} finally {
await S?.finish();
try {
await c.context.runContinuationSession?.seal();
} catch (t) {
logWarn(`[cron:${e.job.id}] Failed to seal run continuation during cleanup: ${String(t)}`);
}
const n = {
sessionId: c.context.currentRunSessionId(),
sessionKey: c.context.runSessionKey
};
try {
if (h) logMessageDispatchCompleted({
...n,
channel: "cron",
source: "cron-isolated",
durationMs: Date.now() - m,
outcome: _,
error: v
});
g.markIdle(void 0, n);
g.markProcessed(_, {
...n,
error: v,
userPrompt: c.context.commandBody || void 0,
finalResponse: y
});
} finally {
try {
if (!b) await cleanupCronRunSessionAfterRun({
job: e.job,
agentSessionKey: c.context.agentSessionKey,
sessionId: c.context.currentRunSessionId(),
lifecycleRevision: c.context.cronSession.lifecycleRevision,
sessionUpdatedAt: c.context.cronSession.sessionEntry.updatedAt,
beforeDelete: c.context.sessionPreparationEffect.release,
reason: "cron-delete-after-run-finally"
});
} finally {
try {
try {
await disposeCronRunContext({
runId: t,
sessionId: r,
cronSession: c.context.cronSession,
ownsSessionRuntime: o,
runContextOwnerToken: s
});
} finally {
c.context.sessionPreparationEffect.release();
}
} finally {
if (c.context.runSessionKey !== c.context.agentSessionKey) await cleanupBrowserSessionsForLifecycleEnd({
cfg: c.context.cfgWithAgentDefaults,
sessionKeys: [c.context.runSessionKey],
onWarn: (t) => logWarn(`[cron:${e.job.id}] ${t}`)
});
}
}
}
}
}), () => u ? o.snapshot : void 0);
} finally {
u = false;
}
} catch (e) {
r.e = e;
} finally {
await r.d();
}
}
} catch (e) {
t.e = e;
} finally {
await t.d();
}
}
//#endregion
export { runCronIsolatedAgentTurn as t };