openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,485 lines • 76.7 kB
JavaScript
import { o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { t as MAX_DATE_TIMESTAMP_MS } from "./number-coercion-D6u-4YD8.mjs";
import { a as asOptionalRecord, l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { i as truncateWithMarker, r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import "./utils-C8YECn2Q.mjs";
import { j as parseAgentSessionKey, x as isCronSessionKey } from "./session-key-CqAyZeVk.mjs";
import { n as normalizeAccountId } from "./account-id-BqKT3GuY.mjs";
import { f as resolveAgentWorkspaceDir, r as resolveAgentConfig, x as resolveSessionAgentId } from "./agent-scope-config-DmXgFGKP.mjs";
import { i as AutomationResultSummarySchema, n as AutomationOutcomeSchema, r as AutomationResultSchema } from "./cron-automation-result-CAvrSzG4.mjs";
import { a as getRuntimeConfigSnapshot, h as readRuntimeConfig, n as createRuntimeConfigReader } from "./runtime-snapshot-WbwbY5b7.mjs";
import { Bd as CronScratchGetResultSchema, Ed as CronAddResultSchema, Hd as CronScratchSetResultSchema, Id as CronRunLogEntrySchema, Nd as CronJobSchema, kd as CronDeliveryPreviewSchema, wd as CronAddJobResultSchema } from "./src-BX8OAe1J.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { l as getAgentRunContext } from "./agent-run-registry-D7vkrqFT.mjs";
import { t as parseDurationMs } from "./parse-duration-D6UJm52I.mjs";
import { t as DEFAULT_EXEC_APPROVAL_TIMEOUT_MS } from "./exec-approvals-core-puBAw1bE.mjs";
import { n as extractTextFromChatContent } from "./chat-content-Dkam4EQe.mjs";
import { t as AUTOMATIONS_TOOL_NAME } from "./automations-tool-name-DNRDs0aJ.mjs";
import { r as CRON_TOOL_DISPLAY_SUMMARY } from "./tool-catalog-C1ALpCJD.mjs";
import { n as isWellFormedApprovalId } from "./approval-id-CfM0pBs_.mjs";
import { f as createAutomationResultRecorder, g as recordCronNextCheckProposal, p as createAutomationRunGuard } from "./session-event-handoff-CC7Ui3SA.mjs";
import { a as requiresExecApproval } from "./exec-approvals-policy-BGzNHuNm.mjs";
import { t as applyExecPolicyLayer } from "./exec-policy-B0KOmSWr.mjs";
import { r as projectEffectiveExecPolicy } from "./session-permission-exec-mode-vqqWNPSg.mjs";
import { f as withGatewayToolCallerIdentity, o as getGatewayToolCallerIdentity } from "./gateway-caller-context-BNidAW8G.mjs";
import { s as withToolEffectBoundary } from "./tool-effect-receipt-BbbEwqBS.mjs";
import { n as jsonResult } from "./tool-results-CcV0sxnb.mjs";
import { f as setToolTerminalPresentation } from "./agent-tool-metadata-nrQgRaqv.mjs";
import { c as readNonNegativeIntegerParam, m as readToolStringParam, u as readPositiveIntegerParam } from "./common-njQNtpnW.mjs";
import "./config-CMA-J084.mjs";
import { i as resolveSandboxConfigForAgent, n as captureSandboxConfig } from "./config-WbZbWrF1.mjs";
import { s as withSandboxRuntimeStatusInWorker } from "./runtime-status-C5ZOG7YR.mjs";
import { n as resolveEffectiveToolPolicy } from "./agent-tools.policy-CM-3Smt9.mjs";
import { n as resolveCronListPageNextOffset, t as readCanonicalCronListPage } from "./list-page-validation-B_xXQt9m.mjs";
import { a as loadExecApprovalsReadOnlyAsync } from "./exec-approvals-store-BUZ9uOWF.mjs";
import { i as createExecApprovalPolicySnapshot } from "./exec-approvals-authorization.kernel-DITNT1Lg.mjs";
import { n as resolveExecConfigState, s as resolvePreparedExecDefaultsAsync, t as prepareExecDefaults } from "./exec-defaults-BaVI-sJD.mjs";
import { t as GatewayClientRequestError } from "./request-error-C4C6eD0S.mjs";
import "./client-cXg8kULv.mjs";
import { n as readGatewayCallOptions, s as shouldUseInProcessGatewayTool, t as callGatewayTool } from "./gateway-DL_Nxi-v.mjs";
import { f as isCronModelManagementAllowed, n as attachCronStreamExecPolicy, t as CRON_MANAGEMENT_METHODS } from "./cron-creator-authority-grant-pGPjtQX_.mjs";
import { t as resolveCronCreationDelivery } from "./delivery-context-DuUP9x88.mjs";
import { t as assertCronDeliveryInputNonBlankFields } from "./delivery-target-validation-BQd2iGZZ.mjs";
import { r as normalizeCronJobPatch, t as normalizeCronJobCreate } from "./normalize-DLzfR3Jc.mjs";
import { n as CronStreamApprovalEndedSchema, r as readCronStreamApprovalEnded } from "./stream-approval-outcome-DvAGOpR7.mjs";
import { b as parseCronPacingBounds } from "./row-codec-D4aymQkb.mjs";
import { a as cronMutationRequiresStreamExecAuthority, c as cronUpdateRequiresStreamExecAuthority, i as cronCreateRequiresStreamExecAuthority, n as CronStreamExecApprovalRequiredError, t as CRON_STREAM_EXEC_AUTHORITY_ERROR } from "./stream-exec-authority-CRx6XpZo.mjs";
import { t as normalizeHttpWebhookUrl } from "./webhook-url-hdHTU0IF.mjs";
import { i as bindCronManagementGrant, o as bindCronRequesterGrant } from "./cron-creator-authority-context-D4fHKVAj.mjs";
import { _ as stripCronCreateNullClears, a as capCronJobToolsAllowOnCreate, c as hasCronCreatorGatewayExecTool, d as planCronJobUpdatePatch, g as readCronToolJob, h as prepareCronToolArguments, l as hasCronCreatorSandboxExecTool, m as isEmptyRecoveredCronPatch, n as INCOMPLETE_CRON_CREATOR_AUTHORITY_MESSAGE, p as resolveCronCreatorExecToolTarget, r as assertInheritedCronToolCaptureReady, s as cronCreateRequiresCreatorAuthority, t as CRON_CREATOR_AUTHORITY_RECOVERY_MESSAGE, u as isCronCreatorToolCaptureComplete } from "./cron-tool-creator-cap-sxVcNlMi.mjs";
import { t as createCachedToolSchema } from "./cached-schema-DxTpNYje.mjs";
import { n as stringEnum, t as optionalStringEnum } from "./string-enum-DXKqjXG0.mjs";
import { a as optionalNonNegativeIntegerSchema, o as optionalPositiveIntegerSchema } from "./typebox-BwU4K8-3.mjs";
import { t as gatewayCallOptionSchemaProperties } from "./gateway-schema-CGh2ao1T.mjs";
import { o as resolveInternalSessionKey, s as resolveMainSessionAlias } from "./sessions-resolution-B1MUJxVg.mjs";
import "./sessions-helpers-BN0PfnY4.mjs";
import { t as attachPluginCommandCreation } from "./plugin-command-creation-0shhhnSQ.mjs";
import { r as readStreamSandboxContext } from "./stream-context-CUn0Kkey.mjs";
import { n as defineToolOutputSchema } from "./tool-output-schema-Cs8aYtff.mjs";
import { isDeepStrictEqual } from "node:util";
import { Type } from "typebox";
//#region src/agents/tools/cron-tool-automation.ts
/** Model actions bound to one admitted automation invocation. */
function createCronAutomationActions(e) {
const t = e?.selfRemoveOnlyJobId?.trim();
const n = e?.runId && t ? getAgentRunContext(e.runId)?.cronRunsByJobId?.get(t) : void 0;
const r = Boolean(n?.assertCurrent && !n.closed);
const i = e?.runId && t && n ? createAutomationRunGuard(e.runId, t) : void 0;
const a = Boolean(r && n?.nextCheckEnabled);
const o = e?.runId && t && r ? createAutomationResultRecorder(e.runId, t) : void 0;
return {
activeRun: r,
nextCheckEnabled: a,
assertCurrent: i,
execute: async (n, a, s, c) => {
i?.();
switch (n) {
case "scratch_get":
case "scratch_set": {
if (!t || !r || !i) throw new Error("scratch actions are only available inside the currently running automation; use the automation editor for other jobs");
if (n === "scratch_get") return jsonResult(await s("cron.scratch.get", c, { id: t }));
if (typeof a.content !== "string" && a.content !== null) throw new Error("scratch_set requires complete content or null to clear");
const e = readNonNegativeIntegerParam(a, "expectedRevision");
if (e === void 0) throw new Error("scratch_set requires expectedRevision from scratch_get");
return jsonResult(await s("cron.scratch.set", c, {
id: t,
content: a.content,
expectedRevision: e
}));
}
case "record_result": {
if (!t || !o) throw new Error("record_result is only available inside the currently running automation");
const e = a.outcome;
const n = o({
outcome: e,
...a.summary !== void 0 ? { summary: a.summary } : {}
});
return jsonResult({
ok: true,
...n
});
}
case "next_check": {
const n = t;
const o = e?.runId?.trim();
if (!n || !o || !r || !i) throw new Error("cron next_check is only available to the currently running job");
const s = readToolStringParam(a, "in", { required: true });
let c;
try {
c = parseDurationMs(s);
} catch {
throw new Error("cron next_check in must be a positive duration");
}
if (c <= 0) throw new Error("cron next_check in must be a positive duration");
recordCronNextCheckProposal(o, n, c);
return jsonResult({
ok: true,
delayMs: c
});
}
default: throw new Error(`Unknown automation invocation action: ${n}`);
}
}
};
}
//#endregion
//#region src/agents/tools/cron-tool-schema.ts
/** Model-facing schema and input validation for the cron tool. */
const REMINDER_CONTEXT_MESSAGES_MAX = 10;
const CRON_TOOL_LIST_MAX_LIMIT = 200;
const CRON_ACTIONS = [
"status",
"list",
"get",
"add",
"update",
"remove",
"run",
"runs",
"wake",
"bind",
"scratch_get",
"scratch_set",
"record_result",
"next_check"
];
const CRON_SELF_ACTIONS = [
"status",
"list",
"get",
"remove",
"runs"
];
const CRON_SCHEDULE_KINDS = [
"at",
"every",
"cron",
"stream",
"event"
];
const CRON_SCHEDULE_KINDS_TRIGGERS_DISABLED = [
"at",
"every",
"cron"
];
const CRON_WAKE_MODES = ["now", "next-heartbeat"];
const CRON_PAYLOAD_KINDS = [
"systemEvent",
"agentTurn",
"script"
];
const CRON_PAYLOAD_KINDS_TRIGGERS_DISABLED = ["systemEvent", "agentTurn"];
const CRON_DELIVERY_MODES = [
"none",
"announce",
"webhook"
];
const CRON_RUN_MODES = ["due", "force"];
function nullableStringSchema(e) {
return Type.Optional(Type.Union([Type.String(), Type.Null()], { description: e }));
}
function nullableStringArraySchema(e) {
return Type.Optional(Type.Union([Type.Array(Type.String()), Type.Null()], { description: e }));
}
function deliveryStringSchema(e) {
return nullableStringSchema(`${e}, or null to clear`);
}
function createCronScheduleSchema(e) {
return Type.Optional(Type.Object({
kind: optionalStringEnum([...e.triggersEnabled ? CRON_SCHEDULE_KINDS : CRON_SCHEDULE_KINDS_TRIGGERS_DISABLED, ...e.management ? ["on-exit"] : []], { description: "Schedule kind" }),
...e.triggersEnabled ? {
source: Type.Optional(Type.String({ description: "Installed event-source plugin ID (kind=event)" })),
options: Type.Optional(Type.Record(Type.String(), Type.Unknown(), { description: "Event source options from its plugin catalog (kind=event)" }))
} : {},
at: Type.Optional(Type.String({ description: "ISO-8601 time (kind=at)" })),
everyMs: optionalPositiveIntegerSchema({
description: "Interval ms (kind=every)",
maximum: MAX_DATE_TIMESTAMP_MS
}),
anchorMs: optionalNonNegativeIntegerSchema({
description: "Start anchor ms (kind=every)",
maximum: MAX_DATE_TIMESTAMP_MS
}),
expr: Type.Optional(Type.String({ description: "Cron wall-time expr; never UTC-convert. Missing tz preserves the existing cron timezone on update; otherwise Gateway local. Example \"0 18 * * *\", \"Asia/Shanghai\"." })),
tz: Type.Optional(Type.String({ description: "IANA timezone for wall-clock fields. Omit on update to preserve the existing cron timezone; otherwise defaults to Gateway host local timezone. Example \"Asia/Shanghai\"." })),
staggerMs: optionalNonNegativeIntegerSchema({
description: "Jitter ms (kind=cron)",
maximum: MAX_DATE_TIMESTAMP_MS
}),
...e.triggersEnabled || e.management ? {
command: Type.Optional(Type.Union([Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }), ...e.management ? [Type.String()] : []], { description: "Supervised source argv (kind=stream; disabled when cron.triggers.enabled=false)" })),
cwd: Type.Optional(Type.String({ description: "Working directory (kind=stream)" })),
mode: optionalStringEnum(["line", "match"], { description: "Stream output: line accepts every line; match uses the match regex without a trigger script" }),
match: Type.Optional(Type.String({ description: "Regex source for mode=match, e.g. ERROR; matching output is appended to the payload" })),
batchMs: optionalNonNegativeIntegerSchema(),
maxBatchBytes: optionalNonNegativeIntegerSchema()
} : {}
}, { additionalProperties: true }));
}
function createCronPacingSchema() {
const e = Type.Object({
min: Type.Optional(Type.String({ description: "Minimum dynamic delay" })),
max: Type.Optional(Type.String({ description: "Maximum dynamic delay" }))
}, {
additionalProperties: false,
description: "Dynamic-cadence bounds; at least one of min or max is required"
});
return Type.Optional(Type.Union([e, Type.Null()]));
}
function assertCronPacingInput(e) {
if (e === void 0 || e === null) return;
if (!isRecord(e)) throw new Error("cron pacing must be an object");
parseCronPacingBounds(e);
}
function createCronPayloadSchema(e) {
return Type.Optional(Type.Object({
kind: optionalStringEnum([...e.triggersEnabled ? CRON_PAYLOAD_KINDS : CRON_PAYLOAD_KINDS_TRIGGERS_DISABLED, ...e.management ? ["command"] : []], { description: "Payload kind" }),
text: Type.Optional(Type.String({ description: "systemEvent text" })),
message: Type.Optional(Type.String({ description: "agentTurn prompt" })),
...e.management ? { argv: Type.Optional(Type.Array(Type.String(), { description: "Existing command job argv" })) } : {},
...e.triggersEnabled ? { script: Type.Optional(Type.String({ description: "Headless code-mode script" })) } : {},
model: nullableStringSchema("Model override, or null to clear"),
thinking: Type.Optional(Type.String({ description: "Thinking override" })),
timeoutSeconds: Type.Optional(Type.Union([Type.Number({ minimum: 0 }), Type.Null()], { description: "Timeout seconds; null restores the default on update (omission preserves it)" })),
...e.triggersEnabled ? { toolBudget: optionalPositiveIntegerSchema({ description: "Maximum script tool calls" }) } : {},
lightContext: Type.Optional(Type.Boolean({ description: "Lightweight bootstrap context (skip full workspace context)" })),
includeReasoning: Type.Optional(Type.Boolean({ description: "Include reasoning with a meaningful delivered result" })),
skipIfScratchEmpty: Type.Optional(Type.Boolean()),
allowUnsafeExternalContent: Type.Optional(Type.Boolean({ description: "Allow untrusted external content in prompt" })),
fallbacks: nullableStringArraySchema("Fallback models, or null to clear"),
toolsAllow: nullableStringArraySchema("Allowed tool ids, or null to clear")
}, { additionalProperties: true }));
}
function createCronTriggerSchema() {
const e = Type.Object({
script: Type.String({
minLength: 1,
maxLength: 65536
}),
once: Type.Optional(Type.Boolean())
}, { additionalProperties: false });
return Type.Optional(Type.Union([e, Type.Null()]));
}
function createCronDeliverySchema() {
const e = Type.Object({
channel: deliveryStringSchema("Failure delivery channel"),
to: deliveryStringSchema("Failure delivery target"),
accountId: deliveryStringSchema("Failure delivery account"),
mode: Type.Optional(Type.Union([
Type.Literal("announce"),
Type.Literal("webhook"),
Type.Null()
]))
}, { additionalProperties: true });
const t = Type.Object({
mode: Type.Literal("webhook"),
to: Type.String({
minLength: 1,
description: "Completion webhook target; only valid with delivery.mode=announce"
})
}, { additionalProperties: true });
return Type.Optional(Type.Object({
mode: optionalStringEnum(CRON_DELIVERY_MODES, { description: "Delivery mode" }),
target: Type.Optional(Type.Union([Type.Literal("owner"), Type.Null()])),
directPolicy: Type.Optional(Type.Union([stringEnum(["allow", "block"]), Type.Null()])),
channel: deliveryStringSchema("Delivery channel"),
to: deliveryStringSchema("Delivery target"),
threadId: Type.Optional(Type.Union([
Type.String(),
Type.Number(),
Type.Null()
], { description: "Thread/topic id" })),
bestEffort: Type.Optional(Type.Boolean({ description: "Omitted/false requires requested delivery for successful completion; true lets successful execution complete and delete a one-shot despite failed/unknown delivery. Intentional silence succeeds in either mode." })),
accountId: deliveryStringSchema("Delivery account"),
failureDestination: Type.Optional(Type.Union([e, Type.Null()], { description: "Failure-alert route override; required-delivery failures bypass after but share the execution-alert cooldown; null clears." })),
completionDestination: Type.Optional(Type.Union([t, Type.Null()], { description: "Completion webhook; requires delivery.mode=announce; null clears." }))
}, { additionalProperties: true }));
}
function createCronFailureAlertSchema() {
return Type.Optional(Type.Union([
Type.Object({
after: optionalPositiveIntegerSchema({ description: "Consecutive execution failures before alert; delivery failures bypass this threshold" }),
channel: Type.Optional(Type.String({ description: "Alert channel" })),
to: Type.Optional(Type.String({ description: "Alert target" })),
cooldownMs: optionalNonNegativeIntegerSchema({ description: "Alert cooldown ms" }),
includeSkipped: Type.Optional(Type.Boolean({ description: "Count skipped runs." })),
mode: optionalStringEnum(["announce", "webhook"]),
accountId: Type.Optional(Type.String())
}, { additionalProperties: true }),
Type.Literal(false),
Type.Null()
], { description: "Failure alert policy/route override; null clears. Route-backed jobs default to after=2 for execution failures and cooldownMs=3600000 for all failure alerts; false disables execution/delivery alerts but not the auto-disable safety notice." }));
}
function createCronToolSchema(e) {
return cronToolSchemas(e);
}
const cronToolSchemas = createCachedToolSchema({
key: (e) => JSON.stringify([
e?.triggersEnabled !== false,
e?.management ?? null,
e?.allowCommandJobs !== false,
e?.selfRemoveOnly === true,
e?.activeRun === true,
e?.nextCheckEnabled === true,
Boolean(e?.agentSessionKey?.trim())
]),
build: buildCronToolSchema
});
function buildCronToolSchema(e) {
const t = e?.triggersEnabled !== false;
const n = Boolean(e?.management);
const r = e?.management === "only";
const i = r ? CRON_MANAGEMENT_METHODS.map((e) => e.slice(5)) : CRON_ACTIONS;
const a = Type.Optional(Type.Object({
name: Type.Optional(Type.String({ description: "Job name" })),
declarationKey: Type.Optional(Type.String({
description: "Key to avoid duplicate declarations (add only).",
minLength: 1,
maxLength: 200
})),
displayName: Type.Optional(Type.Union([Type.String({ maxLength: 200 }), Type.Null()], { description: "Human-readable label; null clears it" })),
owner: Type.Optional(Type.Object({
agentId: Type.Optional(Type.String()),
sessionKey: Type.Optional(Type.String())
}, { additionalProperties: false })),
schedule: createCronScheduleSchema({
triggersEnabled: t,
management: n && e?.allowCommandJobs !== false
}),
pacing: createCronPacingSchema(),
activeHours: Type.Optional(Type.Union([Type.Object({
start: Type.String(),
end: Type.String(),
timezone: Type.Optional(Type.String())
}, { additionalProperties: false }), Type.Null()])),
idleOnly: Type.Optional(Type.Union([Type.Boolean(), Type.Null()])),
...t ? { trigger: createCronTriggerSchema() } : {},
sessionTarget: Type.Optional(Type.String({ description: "main | isolated | current (agentTurn default) | session:<id>" })),
wakeMode: optionalStringEnum(CRON_WAKE_MODES, { description: "Wake timing" }),
payload: createCronPayloadSchema({
triggersEnabled: t,
management: n && e?.allowCommandJobs !== false
}),
delivery: createCronDeliverySchema(),
...n || !e?.agentSessionKey?.trim() ? { agentId: nullableStringSchema("Agent id, or null to clear it") } : {},
description: Type.Optional(Type.String({ description: "Human description" })),
enabled: Type.Optional(Type.Boolean()),
deleteAfterRun: Type.Optional(Type.Boolean({ description: "Delete one-shot after successful completion: delivery confirmed, not requested, intentionally silent, or explicitly bestEffort. Failed/unknown required delivery retains it disabled." })),
sessionKey: nullableStringSchema("Explicit session key, or null to clear it"),
failureAlert: createCronFailureAlertSchema()
}, {
additionalProperties: true,
description: r ? "Partial update: only supplied fields change; null clears." : "Job fields. action=\"add\": full job. action=\"update\": partial patch — only supplied fields change; null clears."
}));
const o = Type.Object({
action: stringEnum(e?.selfRemoveOnly ? [...i.filter((e) => CRON_SELF_ACTIONS.some((t) => t === e)), ...!r && e.activeRun ? [
"scratch_get",
"scratch_set",
"record_result",
...e.nextCheckEnabled ? ["next_check"] : []
] : []] : i),
...gatewayCallOptionSchemaProperties(),
includeDisabled: Type.Optional(Type.Boolean({ description: "List: false by default; true includes disabled saved jobs." })),
limit: optionalPositiveIntegerSchema({
maximum: 200,
description: "Maximum jobs returned by action=\"list\""
}),
offset: optionalNonNegativeIntegerSchema({ description: "Job offset for action=\"list\"; use nextOffset to load the next page" }),
job: r ? Type.Optional(Type.Omit(a, ["declarationKey", "owner"])) : a,
jobId: Type.Optional(Type.String()),
id: Type.Optional(Type.String()),
content: Type.Optional(Type.Union([Type.String({ maxLength: 262144 }), Type.Null()])),
expectedRevision: optionalNonNegativeIntegerSchema(),
outcome: Type.Optional(AutomationOutcomeSchema),
summary: Type.Optional(AutomationResultSummarySchema),
in: Type.Optional(Type.String({ description: "Relative duration for action=\"next_check\" (for example, \"15m\")" })),
text: Type.Optional(Type.String({ description: "systemEvent text for action=\"wake\"" })),
mode: optionalStringEnum(CRON_WAKE_MODES, { description: "Wake mode for action=\"wake\" (default next-heartbeat)" }),
runMode: optionalStringEnum(CRON_RUN_MODES, { description: "Run mode for action=\"run\": omitted defaults to \"due\"; use \"force\" to trigger now." }),
runId: Type.Optional(Type.String({ description: "Run id from action=\"run\" to read with action=\"runs\"" })),
contextMessages: Type.Optional(Type.Integer({
minimum: 0,
maximum: 10
})),
agentId: Type.Optional(Type.String({ description: r ? "Agent filter for action=\"list\"." : "List filter for `action: \"list\"`; wake target override for `action: \"wake\"` (defaults to the calling agent when omitted on wake)" })),
sessionKey: Type.Optional(Type.String({ description: "Wake target override for `action: \"wake\"`: route the event to another session owned by the calling agent. Defaults to the resolved calling-session key when omitted." }))
}, { additionalProperties: true });
if (e?.selfRemoveOnly) return Type.Pick(o, [
"action",
"gatewayUrl",
"gatewayToken",
"timeoutMs",
"includeDisabled",
"jobId",
"id",
...r ? [] : [
"in",
"runId",
...e.activeRun ? [
"content",
"expectedRevision",
"outcome",
"summary"
] : []
]
]);
return r ? Type.Omit(o, [
"in",
"text",
"mode",
"contextMessages",
"sessionKey",
"runId"
]) : o;
}
//#endregion
//#region src/agents/tools/cron-tool-context.ts
const REMINDER_CONTEXT_PER_MESSAGE_MAX = 220;
const REMINDER_CONTEXT_TOTAL_MAX = 700;
const REMINDER_CONTEXT_MARKER = "\n\nRecent context:\n";
function stripExistingContext(e) {
const t = e.indexOf(REMINDER_CONTEXT_MARKER);
if (t === -1) return e;
return e.slice(0, t).trim();
}
function truncateText(e, t) {
return truncateWithMarker(e, t, {
marker: "...",
reserve: 3,
trimEnd: true
});
}
function extractMessageText(e) {
const t = e.role;
if (t !== "user" && t !== "assistant") return null;
const n = extractTextFromChatContent(e.content);
return n ? {
role: t,
text: n
} : null;
}
async function buildReminderContextLines(e) {
const t = Math.min(10, Math.max(0, Math.floor(e.contextMessages)));
if (t <= 0) return [];
const n = e.agentSessionKey?.trim();
if (!n) return [];
const r = readRuntimeConfig();
const { alias: i } = resolveMainSessionAlias(r);
const a = resolveInternalSessionKey({
key: n,
alias: i
});
try {
const n = await e.callGatewayTool("chat.history", e.gatewayOpts, {
sessionKey: a,
agentId: e.agentId,
limit: t
});
const r = (Array.isArray(n?.messages) ? n.messages : []).map((e) => extractMessageText(e)).filter((e) => Boolean(e)).slice(-t);
const i = [];
let o = 0;
for (const e of r) {
const t = `- ${e.role === "user" ? "User" : "Assistant"}: ${truncateText(e.text, REMINDER_CONTEXT_PER_MESSAGE_MAX)}`;
o += t.length;
if (o > REMINDER_CONTEXT_TOTAL_MAX) break;
i.push(t);
}
return i;
} catch {
return [];
}
}
//#endregion
//#region src/agents/tools/cron-tool-presentation.ts
/** Only canonical job facts may supply the immediate tool outcome. */
function readToolStreamLifecycle(e) {
const t = asOptionalRecord(e);
if (!t || t.saved === false || t.status !== void 0 || t.error !== void 0) return;
const n = asOptionalRecord(t.job) ?? t;
const r = asOptionalRecord(n.state);
const i = n.id;
if (typeof i !== "string" || i.length > 1024 || i.trim() !== i || !isWellFormedApprovalId(i) || asOptionalRecord(n.schedule)?.kind !== "stream" || typeof n.enabled !== "boolean" || !r) return;
const a = r.streamStatus;
if (a !== "starting" && a !== "running" && a !== "restarting" && a !== "stopped" && a !== "disabled" && a !== "error" && a !== void 0) return;
return {
jobId: i,
name: typeof n.name === "string" && n.name.trim() ? truncateUtf16Safe(n.name, 512) : i,
enabled: n.enabled,
status: a ?? "unknown"
};
}
function formatCronTerminalPresentation(e, t) {
if (!isRecord(e) || !isRecord(t) || !isRecord(t.details)) return;
if (e.action === "get" || e.action === "add" || e.action === "update") {
const e = readToolStreamLifecycle(t.details);
if (e && t.isError !== true) {
const t = e.status === "stopped" || e.status === "disabled" ? "Source termination confirmed." : !e.enabled ? "Paused. Source termination is not confirmed." : e.status === "unknown" ? "Saved. Source state is not confirmed." : e.status === "error" ? "Source needs attention. Termination is not confirmed." : `Source ${e.status}.`;
return { text: `Recorded watcher observation: ${e.name}\n${t}\nAutomation ID: ${e.jobId}` };
}
}
switch (e.action) {
case "status": return { text: `Automations scheduler status.\nEnabled: ${t.details.enabled === true ? "yes" : "no"}` };
case "list": {
const e = (typeof t.details.total === "number" && Number.isFinite(t.details.total) && t.details.total >= 0 ? Math.floor(t.details.total) : void 0) ?? (Array.isArray(t.details.jobs) ? t.details.jobs.length : void 0);
return e === void 0 ? { text: "Automations listed." } : { text: `Automations listed.\nCount: ${e}` };
}
case "get": return { text: "Automation loaded." };
case "runs": {
const e = Array.isArray(t.details.entries) ? t.details.entries.length : void 0;
return e === void 0 ? { text: "Automation run history loaded." } : { text: `Automation run history loaded.\nCount: ${e}` };
}
default: return;
}
}
function buildCronSelfDescription(e) {
const t = "Inspect or remove only the current automation. Actions: status; list [includeDisabled] (enabled only by default); get/runs/remove jobId. Use get with the current job ID to inspect its saved state. To stop a finished job, remove it; creating/updating/running jobs and waking sessions are unavailable. Return the task result; the scheduler owns delivery.";
if (!e.activeRun) return t;
return t + " scratch_get reads this job's checklist and revision; scratch_set replaces or clears content using expectedRevision from the read (reread after a revision conflict). record_result accepts one outcome (no_change, progress, done, blocked, needs_attention). Omit summary for no_change; other outcomes require a trimmed 1–2000-character summary. Unchanged state and repeated known blockers stay quiet with no_change and NO_REPLY; explicit recurring digests/reports still deliver as requested. Use existing deterministic condition triggers or scripts to skip inference for machine-checkable no-change. no_change or NO_REPLY keeps the response silent." + (e.nextCheckEnabled ? " next_check in:\"15m\" proposes the next delay for this paced job or one-shot session continuation. A successful one-shot proposal rearms this same job from run end (minimum 2s); without one it completes normally." : "");
}
//#endregion
//#region src/agents/tools/cron-tool-description.ts
function buildCronToolDescription(e) {
if (e.selfRemoveOnly) return e.managementOnly ? "Inspect or remove only the current automation. Actions: list [includeDisabled] (enabled only by default), get jobId (saved state), remove jobId. Use the current job ID; other jobs and management actions are unavailable." : buildCronSelfDescription({
activeRun: e.activeRun === true,
nextCheckEnabled: e.nextCheckEnabled === true
});
const t = e.allowCommandJobs === false ? "\nGateway policy forbids creating, editing, enabling or running command jobs and on-exit command watchers. Use direct Gateway administration for those operations." : "";
if (e.managementOnly) return "Manage any existing automation on this Gateway with the admitted automation management authority. Actions: list [includeDisabled,limit,offset] (enabled-only compact summaries by default; follow nextOffset); get jobId (full saved state, including streamStatus for a known watcher); update jobId job (partial patch, null clears); run jobId (runMode:\"force\" runs now; waits up to timeoutMs, default 60s; unfinished runs return runId); remove jobId (operator removal requests cancellation of an active run; the result reports activeRunCancellationRequested:true); bind jobId (links an automation that names this conversation only by key to its current incarnation). To stop a saved watcher, use update with job:{enabled:false}, or open it on the Automations page and turn off its Active switch. This pauses the watcher without deleting its saved record. The enabled flag alone does not prove source termination; use get jobId to inspect state.streamStatus. Creator attribution and scheduled execution policy stay intact. Use the Automations page for other actions." + t;
const n = e.callerScoped ? "Gateway policy restricts every model turn to caller-visible automations, including administrator-started conversations. Lists and counts reflect only this scope" : "Authenticated configured channel owners and Control UI administrators can manage any Gateway automation. Other turns see caller-visible jobs and scoped counts only";
const r = e.callerScoped ? "ask an authorized administrator to check through the Automations page" : "ask an authorized administrator to check through a fresh authenticated owner/administrator turn or the Automations page";
const i = e.triggersEnabled ? "\n- {kind:\"stream\",command:[argv],mode:\"match\",match:\"ERROR\"}: persistent source in the creator's supported Docker sandbox or on the Gateway. Match output with a regex; omit mode/match for every line. Matching lines trigger the payload and its delivery without another user turn." : "";
const a = e.triggersEnabled ? `
WATCH OUTPUT: for continuous log monitoring and future alerts, add one saved stream directly. Example (replace the path with the requested log):
{action:"add",job:{name:"Application errors",schedule:{kind:"stream",command:["tail","-n","0","-F","<log path>"],mode:"match",match:"ERROR"},sessionTarget:"current",payload:{kind:"agentTurn",message:"Report the matching application errors."}}}
Use built-in match mode for a simple condition; no custom trigger script or separate background exec watcher is needed. Inspect finitely if needed before proposing it.
STREAM CONSENT: creation, source changes and reactivation require current creator exec authority. When exec asks, add/update waits for user approval through the native client before saving the persistent watcher and its automatic restarts. A saved add/update result means any required approval has already completed. Say "Approved by an operator" when streamExecutionApproval is present; it records human approval but does not identify the person. Do not ask again or disable the saved stream solely because no user approval reply is visible in chat. A saved:false result ends that proposal: clean up temporary monitoring, explain the recorded outcome, and wait for a new user instruction before retrying or starting a substitute.
` : "";
const o = e.triggersEnabled ? "\n- {kind:\"event\",source:\"plugin-id\",options:{...}}: durable source-plugin events; discover options through its catalog. Requires agentTurn. Payload is untrusted data and never grants tools or privileges." : "";
const s = e.triggersEnabled ? "\n- {kind:\"script\",script}: headless, main|isolated only; automations is self-scoped (no add/update/run/wake), cannot resume a conversation." : "";
const c = e.triggersEnabled ? `TRIGGER (condition watcher on every/cron): {script}. Never model-poll. Headless check: 30s/5 tool calls/16KB state. Read frozen trigger.state; return json({fire,message?,state?}) with new state for dedupe. fire:false saves state without a model call; fire:true runs payload with self-contained message. Fire on failures/timeouts too. Keep checks read-only; actions belong in payload. once:true disables after first fire. Code Mode: await exec({command:"..."}).` : `TRIGGERS DISABLED (cron.triggers.enabled=false): triggers, script payloads, stream schedules, and event sources are unavailable. For a conditional watcher, say it is unsupported; never model-poll or silently substitute an unconditional job. Plain time-based schedules remain available.`;
const l = e.triggersEnabled ? " Silent watcher=>mode:\"none\"." : "";
const u = e.triggersEnabled ? " Use triggers/script payloads to skip the model on quiet checks. Scripts reach MCP only through toolsAllow entries <server>__tool or <server>__*. Throw to record script failure (returning {error} succeeds); recurring-job failure alerts wait for consecutive failures, run output follows delivery." : "";
return `Schedule reminders, delayed self-wakeups, recurring work${e.triggersEnabled ? ", event watchers" : ""}. Never exec sleep/poll as timer.
ACTIONS: status | list (enabled-only summaries by default; includeDisabled:true includes paused records; follow nextOffset) | get jobId (full details) | add job | update jobId job (partial; null clears) | remove jobId (operator removal requests active-run cancellation) | run jobId (runMode:"force"=now; waits up to timeoutMs, default 60s; unfinished runs return runId) | runs jobId runId? (history) | wake text (caller-owned session; mode defaults to next-heartbeat) | bind jobId (owner turn in the automation's parent conversation; links a key-only automation to this conversation). Check unfinished runs later with runs, never a scheduled verification job. wake has no delay; for a later resume use an at job below.
To pause a saved watcher without deleting its record, update job:{enabled:false}, or turn off its Active switch on the Automations page. The enabled flag and list absence do not prove source termination; use get jobId to inspect state.streamStatus.
SCOPE: ${n}: an empty list or failed list/get/update/remove (including not-found) does not establish global absence, even for IDs from your history. Never recreate or replace a known automation for update/remove/reconciliation based on these results; report the visibility limit and ${r}. New requested automations may still be created.
ADD: job requires name+schedule+payload.
${a}
SCHEDULE:
- {kind:"at",at:"ISO-8601"}: one-shot; missing timezone=UTC. Auto-deletes after successful completion unless an explicit session continuation calls next_check; failed/unknown required delivery retains it disabled.
- {kind:"every",everyMs}.
- {kind:"cron",expr,tz?:"IANA"}: wall time in tz, never UTC-convert; omitted tz=Gateway host local.${i}${o}
TARGET+PAYLOAD:
- "current" (agentTurn default) = this conversation's context: the run stays detached, reads bounded chat context, then delivers its final visible assistant result to the resolved destination (this conversation unless another destination is configured). Delayed work/loop = at|every + agentTurn + current. This is not a resumed parent turn: it has its own session identity; while this conversation is current it works at this conversation's saved workspace root with its sandbox (otherwise the scheduled agent workspace), and resetting the conversation ends the run. It never inherits cloud worker placement. In-flight turns sent through the job's stable cron key are canceled if that key is reassigned. Verify required checkout/tool access before delegating repository work; result delivery alone does not resume the original agent.
- "isolated" = fresh detached session; standalone background work recorded in cron run history.
- "main" = heartbeat lane; payload {kind:"systemEvent",text} (systemEvent default target).
- "session:<key>" + agentTurn runs a turn inside that existing conversation (same history, saved workspace/worktree). To come back here later (wait for CI, recheck), add an at + agentTurn job with sessionTarget "session:<your session key from Runtime>" and message = instructions for your next turn. If that one-shot turn still needs to wait, call next_check in:"5m" to rearm this same job after successful run completion (minimum 2s); target, payload, and tool cap stay unchanged. Without a proposal it completes normally.
- {kind:"agentTurn",message,includeReasoning?}; includeReasoning includes reasoning only alongside a meaningful delivered result; timeoutSeconds 0=none.
- Inherited MCP authority covers model-callable tools, not interactive app-view-only capabilities.${s}
PACED LOOP: recurring job + pacing{min?,max?} durations (at least one). Call next_check in:"15m" inside its run; delay is clamped to bounds and measured from run end. Failed runs keep normal backoff.
AUTHORING: keep repeatable logic in workspace scripts and detailed instructions in referenced files. Name exact tools/arguments; cap toolsAllow to what the run needs.${u}
${c}
DELIVERY: omitted=announce. Agent, command, and script jobs send their final visible result to the destination, then add confirmed delivery once to that conversation, independently of isolated/current/persistent execution. Set channel/to/accountId/threadId to select another destination; the creating conversation is the fallback when no external route exists. Verified matching message-tool delivery suppresses the notification resend, not the conversation result. Failed or uncertain external sends are not added to conversation history; a failed history write after confirmed delivery records a warning without failing delivery. With no external route, the conversation commit completes delivery and appears live and after reconnect. Use none for no automatic result or notification. ${l} webhook posts finished-run event (successful empty summary is intentional silence, no POST) to URL in \`to\`. To keep announce delivery and also POST completion, use mode:"announce" with completionDestination:{mode:"webhook",to:"https://..."}.
FAILURE ALERTS: routed jobs default to 2 consecutive execution failures and 1h cooldown; terminal one-shot failures bypass that count. failureAlert:false disables execution/delivery alerts, not auto-disable notices. bestEffort suppresses inherited execution alerts. Required-delivery failures use an alternate route, bypass after, and share the cooldown without incrementing the execution streak.
Optional job policy: activeHours{start,end,timezone?} is an end-exclusive execution window (including manual runs); idleOnly yields to foreground work. delivery.target:"owner" resolves the owner DM dynamically, never the last group; delivery.directPolicy:"block" prohibits DMs. agentTurn skipIfScratchEmpty skips an explicitly empty checklist, not missing scratch.
Main-job wakeMode: "now"(default)|"next-heartbeat". contextMessages 0-10 embeds recent chat lines in reminder text.
Inside a scheduled run only: ${buildCronSelfDescription({
activeRun: true,
nextCheckEnabled: true
})}${t}`;
}
//#endregion
//#region src/agents/tools/cron-tool-write.ts
/** Retain the config owner when tools are assembled, before a later config publication. */
function captureCronStreamPolicyConfigCurrentness(e) {
const t = e?.config ? createRuntimeConfigReader(e.config) : () => void 0;
const project = (t) => {
const { agentId: n, globalExec: r, agentExec: i } = resolveExecConfigState({
cfg: t,
agentId: e?.agentId,
sessionKey: e?.agentSessionKey
});
return {
globalExec: r,
agentExec: i,
tools: resolveEffectiveToolPolicy({
config: t,
agentId: n,
sessionKey: e?.agentSessionKey
}),
globalProviderTools: t?.tools?.byProvider,
subagentTools: t?.tools?.subagents?.tools,
agentProviderTools: t && n ? resolveAgentConfig(t, n)?.tools?.byProvider : void 0,
sandbox: resolveSandboxConfigForAgent(t, n),
workspaceDir: t && n ? resolveAgentWorkspaceDir(t, n) : void 0
};
};
const { sandbox: n, ...r } = project(e?.config);
const i = {
...structuredClone(r),
sandbox: captureSandboxConfig(n)
};
return () => {
if (!isDeepStrictEqual(project(t()), i)) throw new TypeError("Creator execution policy changed before saving the stream; retry from the current turn.");
};
}
function assertCronStreamExecAuthority(e) {
if (!(e.required ?? cronMutationRequiresStreamExecAuthority(e.value))) return;
const t = resolveCronCreatorExecToolTarget(e.creatorToolAllowlist)?.ask ?? e.execDefaults?.ask;
const n = e.execDefaults?.effectiveHost === "sandbox";
if (!e.execDefaults || (n ? !e.sandboxContext || !hasCronCreatorSandboxExecTool(e.creatorToolAllowlist) || e.sandboxExplicitlyDenied : !hasCronCreatorGatewayExecTool(e.creatorToolAllowlist) || e.execDefaults.effectiveHost !== "gateway" || e.execDefaults.security === "deny" || e.execDefaults.security === "allowlist" && t === "off")) throw new TypeError(CRON_STREAM_EXEC_AUTHORITY_ERROR);
if (n && e.sandboxContext) readStreamSandboxContext(e.sandboxContext);
if (e.policyKey !== void 0 && (n ? t !== "off" : requiresExecApproval({
security: e.execDefaults.security,
ask: t ?? e.execDefaults.ask,
analysisOk: false,
allowlistSatisfied: false
})) && e.approvedPolicyKey !== e.policyKey) throw new CronStreamExecApprovalRequiredError(e.policyKey, e.execDefaults.security, t ?? e.execDefaults.ask);
}
/** Prepares the caller's policy for revalidation by the cron write owner. */
async function prepareCronStreamExecPolicy(e) {
const { opts: t, creatorTools: n, operationSignal: r } = e;
const assertCurrentSource = () => {
r?.throwIfAborted();
e.assertConfigCurrent();
};
assertCurrentSource();
const i = {
cfg: t?.config,
sessionEntry: t?.execSession,
execOverrides: t?.execOverrides,
agentId: t?.agentId,
sessionKey: t?.agentSessionKey,
sandboxAvailable: t?.sandboxed
};
const { agentId: a, globalExec: o, agentExec: s } = resolveExecConfigState(i);
const c = projectEffectiveExecPolicy({
base: applyExecPolicyLayer(o ?? {}, s),
overrides: i.execOverrides,
permissionPolicy: i.sessionEntry?.permissionMode ? { mode: i.sessionEntry.permissionMode } : void 0
});
const l = c.security === "deny" || c.mode === "deny";
return await withSandboxRuntimeStatusInWorker({
cfg: i.cfg,
agentId: a,
sessionKey: i.sessionKey
}, {
env: process.env,
cwd: process.cwd(),
assertCurrent: assertCurrentSource
}, async (e) => {
const r = prepareExecDefaults(i, e);
const o = n ? structuredClone(n) : void 0;
const s = await resolvePreparedExecDefaultsAsync(r, loadExecApprovalsReadOnlyAsync);
assertCurrentSource();
const c = s.effectiveHost === "sandbox" ? t?.sandboxContext : void 0;
assertCronStreamExecAuthority({
value: void 0,
required: true,
creatorToolAllowlist: o,
execDefaults: s,
sandboxContext: c,
sandboxExplicitlyDenied: l
});
const assertDefaults = (e, t, n) => {
assertCurrentSource();
assertCronStreamExecAuthority({
value: void 0,
required: true,
creatorToolAllowlist: o,
execDefaults: e,
sandboxContext: c,
sandboxExplicitlyDenied: l,
policyKey: t,
approvedPolicyKey: n
});
};
return r.kind === "resolved" ? {
kind: "resolved",
sandboxContext: c,
assertCurrentSource,
assertCurrent: (e) => assertDefaults(r.defaults, JSON.stringify(r.defaults), e)
} : {
kind: "needs-approvals",
assertCurrentSource,
assertCurrent: (e, t) => assertDefaults(r.resolve(e), JSON.stringify([r.resolve(e), createExecApprovalPolicySnapshot({
file: e,
agentId: a
})]), t)
};
});
}
/** Context-free operator calls cannot silently bypass an agent tool's required question. */
async function assertCronStreamExecPolicyWithoutApproval(e) {
if (e.sandboxContext) throw new TypeError("Sandbox streams require a current creator grant to carry their sandbox target.");
if (e.kind === "resolved") e.assertCurrent();
else e.assertCurrent(await loadExecApprovalsReadOnlyAsync());
}
function assertNoCronShellExecution(e) {
if (!isRecord(e)) return;
const t = isRecord(e.payload) ? e.payload : void 0;
if (normalizeLowercaseStringOrEmpty(t?.kind) === "command") throw new Error("automation command payloads cannot be created or edited through the agent automations tool; use the CLI or Gateway API.");
if ((isRecord(e.schedule) ? e.schedule : void 0)?.kind === "on-exit") throw new Error("automation on-exit schedules cannot be created or edited through the agent automations tool; use the CLI or Gateway API.");
}
function assertCronCreatorAuthorityResolutionAvailable(e) {
if (!e.required || e.resolveCreatorToolAuthority) return;
if (e.unavailableReason === "queued-local-operator-configured-mcp" || !isCronCreatorToolCaptureComplete(e.creatorToolAllowlistCaptureRef)) throw new Error(e.unavailableReason === "queued-local-operator-configured-mcp" ? `Configured MCP authority is unavailable because this local operator turn was queued. ${CRON_CREATOR_AUTHORITY_RECOVERY_MESSAGE}` : INCOMPLETE_CRON_CREATOR_AUTHORITY_MESSAGE);
}
function readCronScheduleWithoutTimezone(e) {
const t = e.schedule;
return isRecord(t) && t.kind === "cron" && t.tz === void 0 ? t : void 0;
}
function inheritCronScheduleTimezone(e, t) {
const n = readCronScheduleWithoutTimezone(e);
const r = t?.schedule;
if (!n || !isRecord(r) || r.kind !== "cron" || typeof r.tz !== "string") return e;
return {
...e,
schedule: {
...n,
tz: r.tz
}
};
}
async function prepareCronJobUpdateForGateway(e) {
e.operationSignal?.throwIfAborted();
const t = planCronJobUpdatePatch({
patch: e.patch,
creatorToolAllowlist: e.creatorToolAllowlist,
creatorAuthorityComplete: e.creatorAuthorityComplete
});
if (t.kind === "ready" && !readCronScheduleWithoutTimezone(t.patch)) return {
patch: t.patch,
expectedConfigRevision: e.expectedConfigRevision,
streamExecAuthorityRequired: false
};
const n = await e.callGateway("cron.get", e.gatewayOpts, { id: e.id });
e.operationSignal?.throwIfAborted();
const r = isRecord(n) ? n : void 0;
const i = r?.configRevision;
if (!r || typeof i !== "string" || i.length === 0) throw new Error("cron.get response is missing configRevision; restart the Gateway before retrying this update");
if (e.expectedConfigRevision !== void 0 && e.expectedConfigRevision !== i) throw new Error("The selected automation changed while waiting. Select its current definition again.");
let a;
let o = planCronJobUpdatePatch({
patch: e.patch,
creatorToolAllowlist: e.creatorToolAllowlist,
currentJob: r,
creatorAuthorityComplete: e.creatorAuthorityComplete
});
if (o.kind === "needs-creator-authority") {
assertCronCreatorAuthorityResolutionAvailable({
required: true,
resolveCreatorToolAuthority: e.resolveCreatorToolAuthority,
creatorToolAllowlistCaptureRef: e.creatorToolAllowlistCaptureRef,
unavailableReason: e.creatorAuthorityUnavailableReason
});
if (!e.resolveCreatorToolAuthority) throw new Error("cron update requires complete creator tool authority");
a = await e.resolveCreatorToolAuthority({ signal: e.operationSignal });
e.operationSignal?.throwIfAborted();
o = planCronJobUpdatePatch({
patch: e.patch,
creatorToolAllowlist: a.tools,
currentJob: r,
creatorAuthorityComplete: true,
creatorHoldsRuntimeAuthority: a.holdsRuntimeAuthority
});
}
if (o.kind !== "ready") throw new Error("cron update patch planning did not use the loaded job");
return {
patch: inheritCronScheduleTimezone(o.patch, r),
expectedConfigRevision: i,
resolvedAuthority: a,
streamExecAuthorityRequired: cronUpdateRequiresStreamExecAuthority(o.patch, r)
};
}
function isCronJobConfigRevisionConflict(e) {
if (!(e instanceof Error) || e.name !== "GatewayClientRequestError") return false;
return (isRecord(e.details) ? e.details : void 0)?.code === "CRON_JOB_CHANGED";
}
async function updateCronJobFromAgentTool(e) {
const t = isRecord(e.patch.payload);
let n;
const r = e.resolveCreatorToolAuthority ? (t) => n ??= e.resolveCreatorToolAuthority(t) : void 0;
for (let n = 0; n < 2; n += 1) {
e.operationSignal?.throwIfAborted();
const i = await prepareCronJobUpdateForGateway({
...e,
creatorAuthorityComplete: isCronCreatorToolCaptureComplete(e.creatorToolAllowlistCaptureRef) && r === void 0 && e.creatorAuthorityUnavailableReason === void 0,
resolveCreatorToolAuthority: r
});
if (!e.adminManagement && t) assertNoCronShellExecution(i.patch);
if (i.streamExecAuthorityRequired) await e.prepareStreamExecAuthority(i.resolvedAuthority?.tools ?? e.creatorToolAllowlist);
assertInheritedCronToolCaptureReady(i.patch, i.resolvedAuthority ? { value: i.resolvedAuthority.provenance } : e.creatorToolAllowlistCaptureRef);
if (i.resolvedAuthority && !e.withCreatorAuthorityProvenance) throw new Error("fresh configured MCP cron authority requires an authenticated local agent run");
try {
const write = async () => {
e.operationSignal?.throwIfAborted();
return await e.callGateway("cron.update", e.gatewayOpts, {
id: e.id,
patch: i.patch,
...i.expectedConfigRevision ? { expectedConfigRevision: i.expectedConfigRevision } : {}
});
};
return i.resolvedAuthority && e.withCreatorAuthorityProvenance ? await e.withCreatorAuthorityProvenance(i.resolvedAuthority, write) : await write();
} catch (t) {
if (n === 0 && e.expectedConfigRevision === void 0 && isCronJobConfigRevisionConflict(t)) continue;
throw t;
}
}
throw new Error("cron update retry exhausted");
}
//#endregion
//#region src/agents/tools/cron-tool-gateway.ts
/** Each cron request carries its current creator or management grants. */
function createCronToolGatewayCaller({ managementAuthority: e, requesterAuthority: t, operationSignal: n, readStreamExecPolicy: r, onEffectsStart: i, assertCurrent: a }) {
return async (...o) => {
n?.throwIfAborted();
a?.();
if (o[0] === "cron.add" || o[0] === "cron.update") i?.();
const s = getGatewayToolCallerIdentity();
const c = e?.mint(o[0], n);
const l = !c && !s?.cronCreatorAuthorityGrant && (o[0] === "cron.add" || o[0] === "cron.update") ? (t ?? s?.mintCronRequesterGrant)?.(n) : void 0;
if ((c || l) && !s) throw new Error("Automation management requires the active configured channel owner or Control UI administrator turn.");
const u = r();
if (u && (o[0] === "cron.add" || o[0] === "cron.update")) {
const e = c ?? l ?? s?.cronCreatorAuthorityGrant;
if (e) attachCronStreamExecPolicy(e, u);
else await assertCronStreamExecPolicyWithoutApproval(u);
}
n?.throwIfAborted();
a?.();
o[2] = attachPluginCommandCreation(o[0], o[2], shouldUseInProcessGatewayTool(o[1]));
const d = (c || l) && s ? await withGatewayToolCallerIdentity({
...s,
...c ? { cronManagementGrant: c } : {},
...l ? { cronCreatorAuthorityGrant: l } : {}
}, () => callGatewayTool(...o)) : await callGatewayTool(...o);
n?.throwIfAborted();
a?.();
return d;
};
}
//#endregion
//#region src/agents/tools/cron-tool-output-schema.ts
function closedObject(e) {
return Type.Object(e, { additionalProperties: false });
}
const nullableNumber = Type.Union([Type.Number(), Type.Null()]);
const nullableString = Type.Union([Type.String(), Type.Null()]);
const job = CronJobSchema.properties;
const CompactCronJobSchema = closedObject({
id: job.id,
name: job.name,
agentId: job.agentId,
updatedAtMs: Type.Optional(job.updatedAtMs),
declarationKey: job.declarationKey,
displayName: job.displayName,
owner: job.owner,
enabled: job.enabled,
effectiveAgentId: Type.Optional(nullableString),
nextRunAt: nullableString,
nextRunAtMs: nullableNumber,
scheduleKind: Type.Union([
Type.Literal("at"),
Type.Literal("every"),
Type.Literal("cron"),
Type.Literal("on-exit"),
Type.Literal("stream"),
Type.Literal("event")
]),
streamExecutionHost: job.streamExecutionHost,
schedule: Type.Optional(Type.Union(job.schedule.anyOf.filter((e) => [
"at",
"every",
"cron"
].includes(e.properties.kind.const)))),
trigger: Type.Optional(Type.Literal(true)),
lastRunAt: nullableString,
lastRunAtMs: nullableNumber,
lastRunStatus: Type.Union([...job.lastRunStatus.anyOf, Type.Null()]),
lastRunError: nullableString,
runningAtMs: job.state.properties.runningAtMs,
lastDurationMs: job.state.properties.lastDurationMs,
lastTriggerEvalAtMs: job.state.properties.lastTriggerEvalAtMs,
lastMeaningfulResult: job.state.properties.lastMeaningfulResult,
autoDisabled: job.state.properties.autoDisabled,
lastDelivered: job.lastDelivered,
lastDeliveryStatus: job.lastDeliveryStatus,
lastDeliveryError: job.lastDeliveryError,
deliverySuppressionReason: job.deliverySuppressionReason,
lastFailureNotificationDelivered: job.lastFailureNotificationDelivered,
lastFailureNotificationDeliveryStatus: job.lastFailureNotificationDeliveryStatus,
lastFailureNotificationDeliveryError: job.lastFailureNotificationDeliveryError
});
const FullCronListJobSchema = closedObject({
...job,
effectiveAgentId: Type.Optional(nullableString)
});
const page = {
total: Type.Integer({ minimum: 0 }),
offset: Type.Integer({ minimum: 0 }),
limit: Type.Integer({ minimum: 0 }),
hasMore: Type.Boolean(),
nextOffset: Type.Union([Type.Integer({ minimum: 0 }), Type.Null()])
};
const CronListOutputSchema = closedObject({
jobs: Type.Array(Type.Union([CompactCronJobSchema, FullCronListJobSchema])),
...page,
includeDisabled: Type.Boolean(),
inventoryHint: Type.String(),
snapshotRevision: Type.Optional(Type.String()),
scope: Type.Optional(Type.Union([Type.Literal("caller"), Type.Literal("gateway")])),
scopeHint: Type.Optional(Type.String()),
deliveryPreviews: Type.Optional(Type.Object({}, { additionalProperties: CronDeliveryPreviewSchema }))
});
const CronStatusOutputSchema = closedObject({
enabled: Type.Boolean(),
triggersEnabled: Type.Optional(Type.Boolean()),
storePath: Type.Optional(Type.String()),
storage: Type.Optional(Type.Literal("sqlite")),
sqlitePath: Type.Optional(Type.String()),
jobs: Type.Optional(Type.Integer({ minimum: 0 })),
nextWakeAtMs: Type.Optional(nullableNumber)
});
const runEntry = CronRunLogEntrySchema.properties;
const processInstanceId = Type.Optional(Type.String());
const CronRunOutputSchema = Type.Union([
closedObject({
ok: Type.Literal(false),
processInstanceId
}),
closedObject({
ok: Type.Literal(true),
ran: Type.Literal(true),
processInstanceId
}),
closedObject({
ok: Type.Literal(true),
enqueued: Type.Literal(true),
runId: Type.String(),
processInstanceId,
run: Type.Optional(Type.Object({
runId: runEntry.runId,
status: runEntry.status,
completionStatus: runEntry.completionStatus,
error: runEntry.error,
summary: runEntry.summary,
deliveryStatus: runEntry.deliveryStatus,
deliveryError: runEntry.deliveryError,
durationMs: runEntry.durationMs
}, { additionalProperties: true })),
finished: Type.Optional(Type.Literal(true)),
note: Type.Optional(Type.String())
}),
closedObject({
ok: Type.Literal(true),
ran: Type.Literal(false),
reason: Type.Union([
Type.Literal("disabled"),
Type.Literal("not-due"),
Type.Literal("already-running"),
Type.Literal("invalid-spec"),
Type.Literal("stopped"),
Type.Literal("ownerless")
]),
processInstanceId
})
]);
const streamExecutionApproval = Type.Optional(Type.Object({
approvalId: Type.String(),
decision: Type.Literal("allow-once"),
source: Type.Literal("operator"),
message: Type.String({
minLength: 1,
description: "Human-readable attribution; the receipt does not identify the approver."
})
}, {
additionalProperties: false,
description: "Native operator approval of this persistent watcher and its automatic restarts completed and was consumed by this successful save. This is a completed approval, not a pending question or permission for future agent actions."
}));
const CronAddToolOutputSchema = Type.Union([...CronAddResultSchema.anyOf.map((e) => Type.Object({
...e.properties,
streamExecutionApproval
}, { additionalProperties: false })), CronStreamApprovalEndedSchema]);
const CronUpdateToolOutputSchema = Type.Union([Type.Object({
...CronAddJobResultSchema.properties,
streamExecutionApproval
}, { additionalProperties: false }), CronStreamApprovalEndedSchema]);
/** Every non-throwing automations result, reusing the canonical job/history contracts. */
const CronToolOutputSchema = defineToolOutputSchema({
inputProperty: "action",
variants: {
status: CronStatusOutputSchema,
list: CronListOutputSchema,
get: CronJobSchema,
add: CronAddToolOutputSchema,
update: CronUpdateToolOutputSchema,
remove: Type.Union([closedObject({
ok: Type.Literal(true),
removed: Type.Boolean(),
activeRunCancellationRequested: Type.Optional(Type.Literal(true)),
sessionCleanup: Type.Optional(Type.Literal("pending"))
}), closedObject({
ok: Type.Literal(false),
removed: Type.Literal(false)
})]),
run: CronRunOutputSchema,
runs: closedObject({
entries: Type.Array(CronRunLogEntrySchema),
...page
}),
next_check: closedObject({
ok: Type.Literal(true),
delayMs: Type.Number({ exclusiveMinimum: 0 })
}),
scratch_get: CronScratchGetResultSchema,
scratch_set: CronScratchSetResultSchema,
record_result: Type.Union(AutomationResultSchema.anyOf.map((e) => closedObject({
ok: Type.Literal(true),
...e.properties
}))),
wake: Type.Union([closedObject({ ok: Type.Literal(true) }), closedObject({
ok: Type.Literal(false),
reason: Type.Optional(Type.Literal("unwakeable-session-key"))
})])
}
});
//#endregion
//#region src/agents/tools/cron-tool-self-list.ts
const CRON_SELF_LIST_MAX_PAGES = 50;
function filterDeliveryPreviewsByJobId(e, t) {
if (!isRecord(e)) return e;
return Object.hasOwn(e, t) ? { [t]: e[t] } : {};
}
function filterCronListResultToJobId(e, t) {
const n = e.jobs.filter((e) => isRecord(e) && e.id === t);
const { snapshotRevision: r, ...i } = e;
return {
...i,
jobs: n,
total: n.length,
offset: 0,
limit: n.length,
hasMore: false,
nextOffset: null,
...Object.hasOwn(e, "deliveryPreviews") ? { deliveryPreviews: filterDeliveryPreviewsByJobId(e.deliveryPreviews, t) } : {}
};
}
async function listCronSelfJob(e) {
let t = 0;
for (let n = 0; n < CRON_SELF_LIST_MAX_PAGES; n += 1) {
const n = readCanonicalCronListPage(await e.requestPage({
limit: e.pageSize,
offset: t
}), e.pageSize);
const r = resolveCronListPageNextOffset(n, t);
if (n.jobs.some((t) => isRecord(t) && t.id === e.jobId) || r === null) return filterCronListResultToJobId(n, e.jobId);
t = r;
}
throw new Error("cron.list pagination exceeded maximum pages while reading current automation");
}
//#endregion
//#region src/agents/tools/cron-tool.ts
function requireCronJobIdParam(e) {
const t = readToolStringParam(e, "jobId") ?? readToolStringParam(e, "id");
if (!t) throw new Error("jobId required (id accepted for backward compatibility)");
return t;
}
const CRON_RUN_MAX_WAIT_MS = 6e5;
const CRON_RUN_ENQUEUE_TIMEOUT_MS = 6e4;
const CRON_SELF_REMOVE_SCOPE_ERROR = "Automations tool is restricted to the current automation.";
function readCronSelfRemoveOnlyJobId(e) {
return e?.selfRemoveOnlyJobId?.trim() || void 0;
}
function assertCronSelfRemoveScope(e, t, n) {
const r = readCronSelfRemoveOnlyJobId(e);
if (!r || t === "status" || t === "list") return;
const i = [
"next_check",
"scratch_get",
"scratch_set",
"record_result"
].includes(t);
if (i || [
"get",
"remove",
"runs"
].includes(t)) {
const e = readToolStringParam(n, "jobId") ?? readToolStringParam(n, "id");
if (e === r || i && !e) return;
}
throw new Error(CRON_SELF_REMOVE_SCOPE_ERROR);
}
function isOlderGatewayRejectingParam(e, t, n) {
return e instanceof GatewayClientRequestError && e.gatewayCode === "INVALID_REQUEST" && e.message.includes(`invalid ${t} params`) && e.message.includes(`unexpected property '${n}'`);
}
function createCronTool(e) {
const t = e?.config ?? getRuntimeConfigSnapshot() ?? void 0;
const n = captureCronStreamPolicyConfigCurrentness(e);
const r = bindCronManagementGrant(e?.runId, t);
const i = bindCronRequesterGrant(e?.runId);
const a = t?.tools?.gatewayPolicy?.automations?.allowCommandJobs !== false;
const o = createCronAutomationActions(e);
const { activeRun: s, nextCheckEnabled: c, assertCurrent: l } = o;
const u = e?.config?.cron?.triggers?.enabled !== false;
const d = Boolean(readCronSelfRemoveOnlyJobId(e)) && (!e?.agentSessionKey?.trim() || isCronSessionKey(e.agentSessionKey));
const f = {
label: "Automations",
name: AUTOMATIONS_TOOL_NAME,
displaySummary: CRON_TOOL_DISPLAY_SUMMARY,
description: buildCronToolDescription({
triggersEnabled: u,
callerScoped: !isCronModelManagementAllowed(t),
selfRemoveOnly: d,
activeRun: s,
nextCheckEnabled: c,
managementOnly: r?.managementOnly,
allowCommandJobs: a
}),
outputSchema: CronToolOutputSchema,
parameters: createCronToolSchema({
allowCommandJobs: a,
agentSessionKey: e?.agentSessionKey,
triggersEnabled: u,
selfRemoveOnly: d,
activeRun: s,
nextCheckEnabled: c,
management: r && (r.managementOnly ? "only" : "also")
}),
prepareArguments: prepareCronToolArguments,
execute: async (t, s, c) => {
c?.throwIfAborted();
l?.();
let u;
let d;
const mutationResult = (e) => jsonResult(d && isRecord(e) ? {
...e,
streamExecutionApproval: {
...d,
message: "A human operator approved this watcher and its automatic restarts. The approver's identity is not supplied."
}
} : e);
const f = s;
const p = readToolStringParam(f, "action", { required: true });
if (r?.managementOnly && !CRON_MANAGEMENT_METHODS.some((e) => e === `cron.${p}`)) throw new Error("This turn can only list, get, update, run, remove, or bind automations. Use the Automations page for other actions.");
assertCronSelfRemoveScope(e, p, f);
const m = readGatewayCallOptions(f);
const h = {
...m,
timeoutMs: m.timeoutMs ?? (p === "add" || p === "update" ? 18e5 + 1e4 : 6e4)
};
const g = readRuntimeConfig();
const { alias: _ } = resolveMainSessionAlias(g);
const v = e?.agentSessionKey ? resolveInternalSessionKey({
key: e.agentSessionKey,
alias: _
}) : void 0;
const y = e?.agentSessionKey?.trim() ? resolveSessionAgentId({
sessionKey: e.agentSessionKey,
config: g,
agentId: e.agentId
}) : void 0;
const b = resolveCronCreatorExecToolTarget(e?.creatorToolAllowlist);
const x = y && e?.agentSessionKey?.trim() ? {
agentId: y,
sessionKey: e.agentSessionKey.trim(),
turnSourceAccountId: e.agentAccountId,
...l ? { receiptAuthority: l } : {},
...readCronSelfRemoveOnlyJobId(e) ? { cronSelfManagementJobId: readCronSelfRemoveOnlyJobId(e) } : {},
...e?.creatorToolAllowlistCaptureRef?.value?.version === 1 && e.creatorToolAllowlistCaptureRef.value.source === "final-executable-surface" ? {
cronToolsAllowCapture: "final-executable-surface",
...b ? { cronExecToolTarget: b } : {}
} : {}
} : void 0;
const withCreatorAuthorityProvenance = async (e, t) => {
if (!e) return await t();
if (!x) throw new Error("fresh configured MCP cron authority requires an authenticated local agent run");
const n = resolveCronCreatorExecToolTarget(e.tools);
return await withGatewayToolCallerIdentity({
...x,
cronToolsAllowCapture: "final-executable-surface",
...n ? { cronExecToolTarget: n } : {},
cronCreatorAuthorityGrant: e.grant
}, t);
};
const executeAction = async (t) => {
const prepareStreamExecAuthority = async (r) => {
t?.();
u = await prepareCronStreamExecPolicy({
opts: e,
creatorTools: r,
operationSignal: c,
assertConfigCurrent: n
});
u.onApprovalCommitted = (e) => {
d = e;
};
};
const s = createCronToolGatewayCaller({
managementAuthority: r,
requesterAuthority: i,
operationSignal: c,
readStreamExecPolicy: () => u,
assertCurrent: l,
onEffectsStart: t
});
const readTargetRevision = async (t) => {
if (!getGatewayToolCallerIdentity()?.sessionKey || readCronSelfRemoveOnlyJobId(e) === t) return;
const n = await s("cron.get", h, { id: t });
c?.throwIfAborted();
if (getGatewayToolCallerIdentity()?.receiptAuthority?.() === false) throw new Error("The requesting turn is no longer active.");
if (!isRecord(n) || typeof n.configRevision !== "string") throw new Error("Automation target has no current revision. Inspect it again before retrying.");
return n.configRevision;
};
return await withGatewayToolCallerIdentity(x, async () => {
switch (p) {
case "status": {
const t = await s("cron.status", h, {});
return jsonResult(readCronSelfRemoveOnlyJobId(e) ? { enabled: isRecord(t) && t.enabled === true } : t);
}
case "list": {
const t = readCronSelfRemoveOnlyJobId(e);
const n = readToolStringParam(f, "agentId");
const i = Boolean(f.includeDisabled);
const a = t ? void 0 : readPositiveIntegerParam(f, "limit", {
max: 200,
message: `limit must be a positive integer no greater than ${200}`
});
const o = t ? void 0 : readNonNegativeIntegerParam(f, "offset");
let c = true;
const requestListPage = async (e) => {
for (;;) try {
return await s("cron.list", h, {
includeDisabled: i,
...c ? { compact: true } : {},
...n ? { agentId: n } : {},
...e
});
} catch (e) {
if (!c || !isOlderGatewayRejectingParam(e, "cron.list", "compact")) throw e;
c = false;
}
};
const l = t ? await listCronSelfJob({
jobId: t,
pageSize: 200,
requestPage: requestListPage
}) : await requestListPage({
...a !== void 0 ? { limit: a } : {},
...o !== void 0 ? { offset: o } : {}
});
if (!isRecord(l)) throw new Error("cron.list returned an invalid inventory response");
return jsonResult({
...l,
includeDisabled: i,
inventoryHint: `${i ? "Enabled and disabled automations are included." : "Disabled automations are omitted."} Counts and pagination describe this filtered view. Absence does not prove deletion or source termination. For a known watcher, use get jobId to inspect its saved state and streamStatus.`,
...!t ? {
scope: r ? "gateway" : "caller",
...!r ? { scopeHint: "Restricted automation inventory. For Gateway-wide management, use a fresh authenticated configured channel owner or Control UI administrator turn or the Automations page." } : {}
} : {}
});
}
case "remove": {
const e = requireCronJobIdParam(f);
const t = await readTargetRevision(e);
return jsonResult(await s("cron.remove", h, {
id: e,
...t ? { expectedConfigRevision: t } : {}
}));
}
case "get":
case "runs":
case "bind": {
const e = requireCronJobIdParam(f);
const t = p === "runs" ? readToolStringParam(f, "runId") : void 0;
return jsonResult(await s(`cron.${p}`, h, {
id: e,
...t ? { runId: t } : {}
}));
}
case "add": {
const t = stripCronCreateNullClears(readCronToolJob(f, "add").job);
assertNoCronShellExecution(t);
assertCronDeliveryInputNonBlankFields(t.delivery);
assertCronPacingInput(t.pacing);
if (typeof t.declarationKey === "string" && t.declarationKey.trim().length === 0) throw new Error("declarationKey must be a non-empty string");
if (typeof t.displayName === "string" && t.displayName.trim().length === 0) throw new Error("displayName must be a non-empty string");
const n = typeof t.enabled === "boolean";
const r = normalizeCronJobCreate(t, { sessionContext: { sessionKey: e?.agentSessionKey } }) ?? t;
if (typeof r.declarationKey === "string" && r.declarationKey.length > 0 && !n) delete r.enabled;
const i = cronCreateRequiresCreatorAuthority(r, e?.creatorToolAllowlist);
assertCronCreatorAuthorityResolutionAvailable({
required: i,
resolveCreatorToolAuthority: e?.resolveCreatorToolAuthority,
creatorToolAllowlistCaptureRef: e?.creatorToolAllowlistCaptureRef,
unavailableReason: e?.creatorAuthorityUnavailableReason
});
const a = i && e?.resolveCreatorToolAuthority ? await e.resolveCreatorToolAuthority({ signal: c }) : void 0;
c?.throwIfAborted();
const o = a?.tools ?? e?.creatorToolAllowlist;
const l = a ? { value: a.provenance } : e?.creatorToolAllowlistCaptureRef;
if (cronCreateRequiresStreamExecAuthority(r)) await prepareStreamExecAuthority(o);
capCronJobToolsAllowOnCreate(r, o, a?.holdsRuntimeAuthority);
assertInheritedCronToolCaptureReady(r, l);
const u = normalizeLowercaseStringOrEmpty(r.sessionTarget);
if (!("sessionKey" in r) && v && u !== "isolated") r.sessionKey = v;
if ((e?.agentSessionKey || e?.currentDeliveryContext) && "payload" in r && r.payload?.kind === "agentTurn") {
const t = r.delivery;
const n = isRecord(t) ? t : void 0;
const i = typeof n?.mode === "string" ? n.mode : "";
const a = normalizeLowercaseStringOrEmpty(i);
if (a === "webhook") {
const e = normalizeHttpWebhookUrl(n?.to);
if (!e) throw new Error("delivery.mode=\"webhook\" requires delivery.to to be a valid http(s) URL");
if (n) n.to = e;
}
const o = typeof n?.channel === "string" && n.channel.trim() || typeof n?.to === "string" && n.to.trim();
if ((t == null || n) && (a === "" || a === "announce") && !o && n?.target !== "owner") {
const t = await resolveCronCreationDelivery({
cfg: g,
agentId: y,
currentDeliveryContext: e.currentDeliveryContext,
agentSessionKey: e.agentSessionKey
});
if (t) r.delivery = {
...t,
...n
};
}
}
const d = readNonNegativeIntegerParam(f, "contextMessages") ?? 0;
if ("payload" in r && r.payload?.kind === "systemEvent") {
const t = r.payload;
if (typeof t.text === "string" && t.text.trim()) {
const n = await buildReminderContextLines({
agentSessionKey: e?.agentSessionKey,
agentId: y,
gatewayOpts: h,
contextMessages: d,
callGatewayTool: s
});
if (n.length > 0) t.text = `${stripExistingContext(t.text)}${REMINDER_CONTEXT_MARKER}${n.join("\n")}`;
}
}
return mutationResult(await withCreatorAuthorityProvenance(a, () => s("cron.add", h, r)));
}
case "update": {
const t = requireCronJobIdParam(f);
const { job: n, recovered: i } = readCronToolJob(f, "update");
if (!r || !a) assertNoCronShellExecution(n);
assertCronDeliveryInputNonBlankFields(n.delivery);
assertCronPacingInput(n.pacing);
if (typeof n.displayName === "string" && n.displayName.trim().length === 0) throw new Error("displayName must be a non-empty string or null");
const o = normalizeCronJobPatch(n) ?? n;
if (i && isEmptyRecoveredCronPatch(o)) throw new Error("job required");
let l = r ? void 0 : e;
if (r && e?.resolveCreatorToolAuthority && isRecord(o.payload) && Object.hasOwn(o.payload, "toolsAllow")) {
const n = await s("cron.get", h, { id: t });
if (n.owner?.sessionKey === x?.sessionKey && normalizeAccountId(n.owner?.accountId) === normalizeAccountId(e?.agentAccountId)) l = {
...e,
creatorToolAllowlist: void 0
};
}
const update = async (n) => mutationResult(await updateCronJobFromAgentTool({
id: t,
expectedConfigRevision: n,
patch: o,
adminManagement: Boolean(r) && a,
creatorToolAllowlist: l?.creatorToolAllowlist,
creatorToolAllowlistCaptureRef: l?.creatorToolAllowlistCaptureRef,
resolveCreatorToolAuthority: l?.resolveCreatorToolAuthority,
withCreatorAuthorityProvenance,
gatewayOpts: h,
callGateway: s,
operationSignal: c,
creatorAuthorityUnavailableReason: l?.creatorAuthorityUnavailableReason,
prepareStreamExecAuthority: async (t) => {
assertCronCreatorAuthorityResolutionAvailable({
required: l === void 0,
creatorToolAllowlistCaptureRef: e?.creatorToolAllowlistCaptureRef,
unavailableReason: e?.creatorAuthorityUnavailableReason
});
await prepareStreamExecAuthority(t ?? e?.creatorToolAllowlist);
}
}));
return o.enabled === false ? await update(await readTargetRevision(t)) : await update();
}
case "run": {
const e = requireCronJobIdParam(f);
const t = f.runMode === "due" || f.runMode === "force" ? f.runMode : "due";
const n = Math.min(m.timeoutMs ?? 6e4, CRON_RUN_MAX_WAIT_MS);
let i;
try {
i = await s("cron.run", {
...h,
timeoutMs: n + CRON_RUN_ENQUEUE_TIMEOUT_MS
}, {
id: e,
mode: t,
waitTimeoutMs: n
});
} catch (n) {
if (!isOlderGatewayRejectingParam(n, "cron.run", "waitTimeoutMs")) throw n;
i = await s("cron.run", h, {
id: e,
mode: t
});
}
if (i.enqueued !== true || i.run) return jsonResult(i);
const a = r?.managementOnly ? "check it later on the Automations page" : "check it later with runs jobId runId";
if (!isRecord(i)) throw new Error("cron.list returned an invalid inventory response");
return jsonResult({
...i,
note: i.finished ? `Finished, but its run history is not visible to this turn (a one-shot may have deleted itself after succeeding); ${a} if needed.` : `Not finished yet: it is still running, or it runs in this session and starts after this turn. Its delivery follows the job settings; ${a}. Do not schedule a verification job.`
});
}
case "scratch_get":
case "scratch_set":
case "record_result":
case "next_check": return await o.execute(p, f, s, h);
case "wake": {
const e = readToolStringParam(f, "text", { required: true });
const t = f.mode === "now" || f.mode === "next-heartbeat" ? f.mode : "next-heartbeat";
const n = readToolStringParam(f, "sessionKey");
const r = readToolStringParam(f, "agentId");
const i = n ?? v;
const a = n ? parseAgentSessionKey(n)?.agentId : void 0;
const o = r ?? (n ? a : y);
return jsonResult(await s("wake", h, {
mode: t,
text: e,
...i ? { sessionKey: i } : {},
...o ? { agentId: o } : {}
}, { expectFinal: false }));
}
default: throw new Error(`Unknown action: ${p}`);
}
}).catch((e) => {
const t = e instanceof GatewayClientRequestError && e.gatewayCode === "FORBIDDEN" ? readCronStreamApprovalEnded(e.details) : void 0;
if (t && t.action === p) return jsonResult(t);
throw e;
});
};
return await (p === "add" || p === "update" ? withToolEffectBoundary(executeAction) : executeAction());
}
};
return setToolTerminalPresentation(f, formatCronTerminalPresentation);
}
//#endregion
export { createCronTool as t };