UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

2,092 lines • 80.3 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { V as timestampMsToIsoString, o as asDateTimestampMs, z as resolveTimestampMsToIsoString } from "./number-coercion-D6u-4YD8.mjs";
import { a as asOptionalRecord, l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import "./utils-C8YECn2Q.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import { r as isIncognitoSessionKey } from "./session-key-DW1jcHbM.mjs";
import { C as isSubagentSessionKey, j as parseAgentSessionKey, w as parseCronRunScopeSuffix } from "./session-key-CqAyZeVk.mjs";
import { n as normalizeAccountId } from "./account-id-BqKT3GuY.mjs";
import { n as freezeTrustedJsonSnapshot } from "./immutable-data-Y7xVjZoy.mjs";
import { i as listAgentIds } from "./agent-roster-t1ooUdXp.mjs";
import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs";
import { O as tryResolveAmbientOwnerAgentId } from "./agent-scope-config-DmXgFGKP.mjs";
import { t as areDiagnosticsEnabledForProcess } from "./diagnostic-events-BjAH1Kbx.mjs";
import { T as runWithDiagnosticTraceContext, b as getActiveDiagnosticTraceContext } from "./diagnostics-timeline-CSwiG24r.mjs";
import { t as SessionMetadataUnavailableError } from "./session-metadata-unavailable-error-ClU33Nog.mjs";
import { Md as CronHistoryResultSchema, Xa as validateWakeParams, ai as validateCronRemoveParams, ci as validateCronScratchGetParams, di as validateCronUpdateParams, ei as validateCronAddParams, ii as validateCronListParams, li as validateCronScratchSetParams, ni as validateCronGetParams, oi as validateCronRunParams, ri as validateCronHistoryParams, si as validateCronRunsParams, ti as validateCronBindParams, ui as validateCronStatusParams } from "./src-BX8OAe1J.mjs";
import { c as formatExecCommand } from "./shell-wrapper-resolution-BEK558J4.mjs";
import { t as DEFAULT_EXEC_APPROVAL_TIMEOUT_MS } from "./exec-approvals-core-puBAw1bE.mjs";
import { S as readAgentDatabaseAdmissionRefusal, c as createAgentDatabaseAdmissionErrorShape } from "./agent-database-admission-CL6wHJ_N.mjs";
import { r as bindCronSelfRemovalCommitGuard } from "./active-jobs-DAhIn24S.mjs";
import { n as cronJobUsesToolRuntime } from "./tools-allow-CYmLDCc7.mjs";
import { r as GatewayErrorDetailCodes, t as ErrorCodes } from "./gateway-error-details-B69XiHdh.mjs";
import { p as errorShape } from "./error-codes-BzF7aRQ0.mjs";
import { r as authorizeGatewaySessionCreation } from "./operator-role-policy-DhcqVpmG.mjs";
import { l as withSessionEntryReadOnlyInWorker } from "./session-entry-read-runtime-1Fp1sybj.mjs";
import { t as captureSessionExecutionPolicy } from "./session-entry-execution-policy-bm1K3DBK.mjs";
import { r as resolveRequestedSessionAgentId } from "./session-request-agent-tfwWH53J.mjs";
import { a as resolveSessionStoreIdentity } from "./session-store-key-CEwU3noi.mjs";
import { a as isAgentHarnessSessionKey, d as resolveAgentHarnessSessionStoreEntryError, r as AGENT_HARNESS_SESSION_KEY_RESERVED_MESSAGE } from "./agent-harness-session-key-BRYGtzM6.mjs";
import { r as requireSessionRowProjection } from "./session-row-projection-access-CjLImwLs.mjs";
import { n as captureSessionEntryCurrentRead } from "./session-entry-current-runtime-Csc_-WE9.mjs";
import { r as resolveGatewaySessionStoreTargetInWorker, t as loadGatewaySessionEntryReadOnlyInWorker } from "./session-utils-store-worker-BU_tdh8T.mjs";
import { o as prepareProjectedSessionSharing } from "./session-sharing-read-BqjuH16A.mjs";
import "./session-sharing-BIP3raq1.mjs";
import { i as registerSerializedJsonArray } from "./serialized-json-Ji3ULdJD.mjs";
import { t as createPreparedReadHandler } from "./prepared-read-BXLtRH-W.mjs";
import { i as tryResolveCronJobEffectiveAgentId, t as CRON_AGENT_SELECTION_REQUIRED_MESSAGE } from "./agent-id-CX8HtxAT.mjs";
import { i as isInvalidCronSessionTargetIdError, o as resolveCronDeliverySessionKey, s as resolveCronSessionTargetSessionKey } from "./session-target-C-4MLah6.mjs";
import { n as resolveCronJobSessionBindings } from "./job-session-bindings-Ge1kV-9N.mjs";
import { t as CronStoreSelectionRequiredError } from "./selection-error-CCb6S-v3.mjs";
import { a as sanitizeExecApprovalWarningTextWithStatus, r as sanitizeExecApprovalDisplayTextWithStatus } from "./exec-approval-text-sanitize-Xx3Q87a8.mjs";
import { r as resolveOperatorSessionCreation } from "./session-creation-provenance-DCFhTDpD.mjs";
import { t as respondError } from "./response-C7fEiIN1.mjs";
import { n as defineValidatedGatewayHandler, t as assertValidParams } from "./validation-DwNk6A-B.mjs";
import { _ as withCronManagementGrant, a as getCronManagementAuthority } from "./cron-creator-authority-grant-pGPjtQX_.mjs";
import { n as hasExplicitCronDeliveryTarget } from "./delivery-target-validation-BQd2iGZZ.mjs";
import { a as hasCanonicalCronDeliveryMode, t as CRON_DELIVERY_REPAIR_REQUIRED_MESSAGE } from "./delivery-codec-BaSNePUi.mjs";
import { t as parseAbsoluteTimeMs } from "./parse-CSwpxE6Q.mjs";
import { t as CronStreamApprovalEndedError } from "./stream-approval-outcome-DvAGOpR7.mjs";
import { r as resolveCronJobConfigRevision, t as CronJobConfigRevisionConflictError } from "./config-revision-ChGg5L01.mjs";
import { c as cronUpdateRequiresStreamExecAuthority, i as cronCreateRequiresStreamExecAuthority, n as CronStreamExecApprovalRequiredError, o as cronStreamExecApprovalBinding, r as CronStreamPolicyDeniedError } from "./stream-exec-authority-CRx6XpZo.mjs";
import { n as readPluginCommandCreation } from "./plugin-command-creation-0shhhnSQ.mjs";
import { n as captureCronStreamSandboxTarget } from "./stream-context-CUn0Kkey.mjs";
import { t as CRON_JOB_SCRATCH_MAX_BYTES } from "./scratch-contract-COS3OFt4.mjs";
import { a as selectCronRunHistoryPage, i as projectCronRunHistoryPage, n as isInvalidCronRunJobIdError } from "./run-history-Blg2uCsC.mjs";
import { t as createStageTimingTracker } from "./stage-timing-By2RFvzf.mjs";
import "./system-run-command-Al2Xy1OR.mjs";
import { u as resolveCronOperatorExecutionRevision } from "./jobs-tool-policy-zcItpTHY.mjs";
import { c as readCronRunHistoryRecords, o as readCronRunHistoryBinding, s as readCronRunHistoryCandidates } from "./read-only-C2x_PRgh.mjs";
import { t as readSessionHistoryPageInWorker } from "./session-history-worker-runtime-CRJi5EUs.mjs";
import { t as toPublicCronJob } from "./public-job-CuHjHVvy.mjs";
import { t as cronStoreKey } from "./key-BNWVX7Bb.mjs";
import { n as resolveCronBindParent } from "./bind-parent-BxHpjtqB.mjs";
import { t as resolveCronDeliveryPlan } from "./delivery-plan-BMeGAb9T.mjs";
import { i as cronScratchReadView, r as cronJobReadView, t as cronAddResultReadView } from "./job-read-view-Dos4UvqZ.mjs";
import { n as requiresExternalCronDelivery, r as resolveDeliveryTarget, t as prepareCronDeliveryTargetContexts } from "./delivery-target-BPDm3s8R.mjs";
import { t as assertActiveAgentRuntimeAuthority } from "./agent-runtime-authority-CtOnoFP2.mjs";
import { t as SLOW_GATEWAY_REQUEST_MS } from "./slow-request-diagnostics-DXxiICr7.mjs";
import { t as bindApprovalRequesterMetadata } from "./approval-shared-C8HrUVTB.mjs";
import { t as handlePendingApprovalRequestWithDelivery } from "./approval-request-delivery-2N7Slhd-.mjs";
import { t as getGatewayProcessInstanceId } from "./process-instance-CwB3RMsz.mjs";
import { a as cronRunQueuesBehindCaller, c as requiresExplicitAgentRuntimeToolsAllow, i as captureCronUpdatedInferenceBinding, l as assertValidCronCreateDelivery, n as assertValidCronUpdatePatch, o as normalizeCronAddRequest, r as captureCronCreatorSession, s as normalizeCronUpdateRequest, t as assertCronDoesNotTargetAgentHarness } from "./cron-input-validation-B-SgceJ2.mjs";
import { a as cronJobMatchesCallerScope, c as cronTrustedJobOwnedByCaller, d as resolveCronJobOwnerAgentId, f as resolveCronMutationCommitGuard, h as resolveCronStreamExecPolicy, i as cronCreateMatchesCallerScope, l as readCronCallerScope, m as resolveCronScheduledToolPolicyForCaller, n as assertCronModelJobAllowed, o as cronJobMatchesDeclarationScope, p as resolveCronRequesterProvenanceForJob, r as cronCallerRunsJob, s as cronPatchSessionRefsMatchCaller, t as applyCronCreateCallerScopeDefault, u as resolveCronCreatorAuthorityCapture } from "./cron-caller-scope-CgMeVDFb.mjs";
import { randomUUID } from "node:crypto";
import { performance } from "node:perf_hooks";
import { isDeepStrictEqual } from "node:util";
import { Value } from "typebox/value";
//#region src/cron/delivery-preview.ts
function formatTarget(e, t) {
	if (!e) return "last";
	if (t) return `${e}:${t}`;
	return e;
}
function prepareCronDeliveryPreview(e) {
	if (!hasCanonicalCronDeliveryMode(e.job.delivery)) return { preview: {
		label: "delivery requires review",
		detail: CRON_DELIVERY_REPAIR_REQUIRED_MESSAGE,
		failed: true
	} };
	const t = tryResolveCronJobEffectiveAgentId(e.job, e.defaultAgentId ?? tryResolveAmbientOwnerAgentId(e.cfg));
	const n = t ? readAgentDatabaseAdmissionRefusal(t) : void 0;
	if (n) return { preview: {
		label: `agent ${t} unavailable`,
		detail: `${n.reason}\n${n.repairHint}`,
		failed: true
	} };
	const r = resolveCronDeliveryPlan(e.job);
	if (r.mode === "none" && !hasExplicitCronDeliveryTarget(r)) return { preview: {
		label: "not requested",
		detail: "not requested"
	} };
	if (r.mode === "webhook") return { preview: {
		label: r.to ? `webhook:${r.to}` : "webhook",
		detail: r.to ? "webhook" : "webhook target missing",
		...!r.to ? { failed: true } : {}
	} };
	const i = r.channel ?? "last";
	if (!t) return { preview: {
		label: `${r.mode} -> unresolved owner`,
		detail: CRON_AGENT_SELECTION_REQUIRED_MESSAGE,
		failed: true
	} };
	return {
		plan: r,
		requestedChannel: i,
		agentId: t,
		sessionTarget: e.job.sourceConversation || e.job.payload.kind === "agentTurn" ? e.job.sessionTarget : void 0,
		deliverySessionKey: resolveCronDeliverySessionKey(e.job),
		sourceConversation: r.mode === "announce" ? e.job.sourceConversation : void 0
	};
}
async function resolvePreparedCronDeliveryPreview(e, t, n) {
	if (t.preview) return t.preview;
	const { plan: r, requestedChannel: i, agentId: a, sessionTarget: o, deliverySessionKey: s, sourceConversation: c } = t;
	let l;
	try {
		if (n && !n.ok) throw n.error;
		l = await resolveDeliveryTarget(e, a, {
			...r,
			sessionTarget: o,
			sourceConversation: c,
			sessionKey: s
		}, {
			dryRun: true,
			...n ? { sessionContext: n.value } : {}
		});
	} catch (e) {
		if (!(e instanceof SessionMetadataUnavailableError)) throw e;
		return {
			label: `${r.mode} -> ${formatTarget(i, r.to ?? null)}`,
			detail: `delivery preview unavailable: ${formatErrorMessage(e)}`
		};
	}
	if (!l.ok) {
		if ((o === "current" || c !== void 0) && r.mode === "announce" && !l.sourceConversationUnavailable && !requiresExternalCronDelivery(r, l)) return {
			label: `announce -> ${o === "current" ? "current session" : "creating conversation"}`,
			detail: "commits to this conversation (no external channel route)"
		};
		const e = r.mode === "none" ? `message tool target unresolved: ${l.error.message}` : `${r.target === "owner" ? "owner has no route: " : i === "last" ? "last -> no route, will be blocked: " : ""}${l.error.message}`;
		return {
			label: `${r.mode} -> ${formatTarget(i, r.to ?? null)}`,
			detail: r.mode === "none" ? e : `${e} Configure a channel and delivery target, or use delivery:{mode:"none"} for no automatic delivery.`,
			...r.mode !== "none" ? { failed: true } : {}
		};
	}
	return {
		label: `${r.mode} -> ${formatTarget(l.channel, l.to)}`,
		detail: r.mode === "announce" ? "commits to the destination conversation; sends one external notification" : r.target === "owner" ? "resolved from configured owner" : i !== "last" ? "explicit" : s ? `resolved from last, session ${s}` : "resolved from last, main session"
	};
}
/** Builds the user-visible cron delivery preview for one job without sending anything. */
async function resolveCronDeliveryPreview(e) {
	const { failed: t, ...n } = await resolvePreparedCronDeliveryPreview(e.cfg, prepareCronDeliveryPreview(e));
	return n;
}
/** Reuses the preview decision without adding successful-route bytes to update results. */
async function resolveCronDeliveryFailurePreview(e) {
	const { failed: t, ...n } = await resolvePreparedCronDeliveryPreview(e.cfg, prepareCronDeliveryPreview(e));
	return t ? n : void 0;
}
/** Builds cron delivery previews keyed by job id. */
async function resolveCronDeliveryPreviews(e) {
	const t = e.jobs.map((t) => prepareCronDeliveryPreview({
		...e,
		job: t
	}));
	const n = t.flatMap((e, t) => e.preview ? [] : [{
		index: t,
		agentId: e.agentId,
		sessionKey: e.deliverySessionKey
	}]);
	const r = await prepareCronDeliveryTargetContexts(e.cfg, n);
	const i = new Map(n.map((e, t) => [e.index, r[t]]));
	const a = await Promise.all(e.jobs.map(async (n, r) => {
		const a = i.get(r);
		const { failed: o, ...s } = await resolvePreparedCronDeliveryPreview(e.cfg, t[r], a);
		return [n.id, s];
	}));
	return Object.fromEntries(a);
}
//#endregion
//#region src/cron/validate-timestamp.ts
/** Validates user-supplied one-shot cron timestamps before scheduling. */
const ONE_MINUTE_MS = 6e4;
const TEN_YEARS_MS = 315576e6;
/**
* Validates one-shot cron timestamps with a small past grace window and far-future cap.
*/
function validateScheduleTimestamp(e, t = Date.now()) {
	if (e.kind !== "at") return { ok: true };
	const n = normalizeOptionalString(e.at) ?? "";
	const r = n ? parseAbsoluteTimeMs(n) : null;
	if (r === null || !Number.isFinite(r)) return {
		ok: false,
		message: `Invalid schedule.at: expected ISO-8601 timestamp (got ${e.at})`
	};
	const i = asDateTimestampMs(t) ?? asDateTimestampMs(Date.now()) ?? 0;
	const a = r - i;
	if (a < -6e4) {
		const e = resolveTimestampMsToIsoString(i);
		return {
			ok: false,
			message: `schedule.at is in the past: ${resolveTimestampMsToIsoString(r)} (${Math.floor(-a / ONE_MINUTE_MS)} minutes ago). Current time: ${e}`
		};
	}
	if (a > TEN_YEARS_MS) return {
		ok: false,
		message: `schedule.at is too far in the future: ${resolveTimestampMsToIsoString(r)} (${Math.floor(a / 315576e5)} years ahead). Maximum allowed: 10 years`
	};
	return { ok: true };
}
//#endregion
//#region src/gateway/server-methods/cron-creator-session.ts
/** Retains creator-session facts and their live checks across the durable write. */
async function prepareCronCreatorSession(e) {
	const { context: t, client: n, callerScope: r, sessionMutationCommitGuard: i, hasCurrentClientAuthority: a } = e;
	const o = r ? void 0 : resolveOperatorSessionCreation(n).actor;
	const s = t.getRuntimeConfig();
	const c = s.session?.store;
	const assertCreatorStoreCurrent = () => {
		if (t.getRuntimeConfig().session?.store !== c) throw new Error("Creator session store changed before scheduling; retry from the current turn.");
	};
	const assertCreatorReadCurrent = () => {
		assertActiveAgentRuntimeAuthority(n, t, i);
		assertCreatorStoreCurrent();
		if (a?.() === false) throw new TypeError("Gateway caller authority is no longer active.");
	};
	const l = r?.sessionKey ? await resolveGatewaySessionStoreTargetInWorker({
		cfg: s,
		key: r.sessionKey,
		agentId: r.agentId,
		assertActive: assertCreatorReadCurrent
	}) : void 0;
	const u = l ? {
		sessionKey: l.canonicalKey,
		agentId: l.agentId,
		storePath: l.storePath
	} : void 0;
	const d = u ? await withSessionEntryReadOnlyInWorker(u, assertCreatorReadCurrent, async (e, t) => {
		if (!e.ok) throw e.error;
		return {
			entry: e.value,
			current: e.value ? captureSessionEntryCurrentRead(u, t) : void 0
		};
	}) : void 0;
	const f = d?.entry;
	const p = o ?? f?.createdActor;
	const m = normalizeOptionalString(p?.id);
	const h = p ? {
		...p,
		...m ? { id: m } : {}
	} : void 0;
	const g = JSON.stringify(f?.skillLibrarySelections);
	const _ = e.retainExecutionPolicy ? captureSessionExecutionPolicy(f) : void 0;
	const assertCreatorSessionCurrent = (t) => {
		if (t?.sessionId !== f?.sessionId || t?.lifecycleRevision !== f?.lifecycleRevision || JSON.stringify(t?.skillLibrarySelections) !== g || e.retainExecutionPolicy && !isDeepStrictEqual(t?.executionPolicy, _)) throw new Error("Creator session changed before scheduling; retry from the current turn.");
	};
	const v = d?.current?.kind === "file" ? {
		source: d.current.source,
		assertCurrent: assertCreatorSessionCurrent
	} : void 0;
	const assertCurrent = () => {
		if (f) assertCreatorStoreCurrent();
		d?.current?.assertSourceCurrent();
		if (d?.current && d.current.kind !== "file") assertCreatorSessionCurrent(d.current.readCurrent());
	};
	return {
		session: f && u ? {
			entry: f,
			agentId: u.agentId,
			sessionKey: u.sessionKey
		} : void 0,
		createdActor: h,
		skillLibrarySelections: f?.skillLibrarySelections,
		sessionEntryCurrent: v,
		assertCurrent
	};
}
//#endregion
//#region src/gateway/server-methods/cron-error-classification.ts
function isCronInvalidRequestError(e) {
	const t = formatErrorMessage(e);
	return t === "Agent-less cron job has no resolvable owner. Pass --agent <id> when creating or editing the job, or set agents.defaults.systemAgent.agentId." || t === "cron delivery requires an explicit mode: \"none\", \"announce\", or \"webhook\"; run openclaw doctor --fix for legacy settings or explicitly edit delivery.mode" || t.startsWith("unknown cron job id:") || t.startsWith("cron job already exists:") || t.includes("cron job id must not be blank") || t.startsWith("cron bind") || t.includes("cron declarationKey") || t.includes("cron displayName") || t.includes("cron announce delivery requires an explicit channel") || t.includes("cron script payload has a syntax error") || t.includes("cron trigger script has a syntax error") || t.includes("cron script payload must not be empty") || t.includes("cron script payloads cannot be combined") || t.includes("cron script payloads are disabled") || t.includes("cron triggers are disabled") || t.includes("cron triggers require") || t.includes("cron trigger every interval") || t.includes("cron job is missing sessionTarget") || t.includes("invalid cron sessionTarget session id") || t.startsWith("cron sessionTarget \"") || t.includes("has no upcoming run time and would never fire") || t.includes("sessionTarget \"main\" is only valid for the default agent") || t.includes("cron.update payload.kind=\"systemEvent\" requires text") || t.includes("cron.update payload.kind=\"agentTurn\" requires message") || t.includes("cron webhook delivery requires") || t.includes("delivery.channel") || t.includes("delivery.accountId") || t.includes("delivery.failureDestination.channel") || t.includes("failureAlert.channel") || t.includes("cron completion destination webhook requires") || t.includes("cron failure destination webhook requires") || t.includes("cron channel delivery config is only supported") || t.includes("cron delivery.failureDestination is only supported");
}
//#endregion
//#region src/gateway/server-methods/cron-visibility.ts
function resolveCronEntryFilter(e, t) {
	const n = e?.internal?.agentRuntimeIdentity;
	if (n && getCronManagementAuthority(n)) return;
	const r = prepareProjectedSessionSharing({
		client: e,
		cfg: t,
		isMember: () => false
	});
	return r.sessionCap === "none" || r.sessionCap === "invited" ? r.entryFilter : void 0;
}
/** The Gateway projection owns sharing facts and consumes committed write receipts. */
function createCronSessionVisibility(e, t) {
	return {
		async prepare() {
			if (!resolveCronEntryFilter(e, t.getRuntimeConfig())) return;
			const n = requireSessionRowProjection(t);
			await n.prepareSelection({ metadataOnly: true });
			await n.prepareMembership();
		},
		resolve() {
			if (!resolveCronEntryFilter(e, t.getRuntimeConfig())) return;
			return (n, r) => {
				const i = t.getRuntimeConfig();
				if (!resolveCronEntryFilter(e, i)) return true;
				const a = resolveSessionStoreIdentity({
					sessionKey: n,
					agentId: r,
					cfg: i
				});
				const o = requireSessionRowProjection(t);
				let s = {
					agentId: a.agentId,
					key: a.canonicalKey
				};
				const c = parseAgentSessionKey(n);
				if (c?.agentId === "main" && !isIncognitoSessionKey(n) && !listAgentIds(i).includes(c.agentId)) {
					const e = {
						agentId: c.agentId,
						key: `agent:${c.agentId}:${c.rest}`
					};
					if (o.capture(e)) s = e;
				}
				const l = o.sharingTarget(s);
				const u = prepareProjectedSessionSharing({
					client: e,
					cfg: i,
					isMember: (e, t) => o.hasMembership(e.storePath, e.storeKey, t)
				});
				return Boolean(l && u.canReadTarget(l));
			};
		}
	};
}
function cronJobVisibilityTarget(e, t) {
	if (!e) return;
	const n = e.owner?.sessionKey ?? resolveCronSessionTargetSessionKey(e.sessionTarget) ?? e.sessionKey;
	if (!n) return;
	const r = resolveCronJobOwnerAgentId(e) ?? tryResolveCronJobEffectiveAgentId(e, t);
	return r ? {
		sessionKey: n,
		agentId: r
	} : void 0;
}
function cronJobIsVisible(e, t, n) {
	if (!t) return true;
	const r = cronJobVisibilityTarget(e, n);
	return Boolean(r && t(r.sessionKey, r.agentId));
}
//#endregion
//#region src/gateway/server-methods/cron-job-access.ts
function isLegacyCreatorPromptUpdate(e, t) {
	return e.scheduledToolPolicy === void 0 && e.payload.kind === "agentTurn" && t.payload !== void 0 && (t.payload.kind === void 0 || t.payload.kind === "agentTurn") && Object.keys(t).every((e) => e === "payload") && Object.keys(t.payload).every((e) => e === "kind" || e === "message");
}
/** Plain refusal a scoped model caller can act on when a tool-runtime edit needs ownership. */
function resolveCronScopedToolEditRefusal(e) {
	const { job: t, nextJob: n, patch: r, callerScope: i } = e;
	if (!i || i.manageAll || !cronJobUsesToolRuntime(n)) return;
	if (!(i.sessionKey !== void 0 && t.owner?.sessionKey === i.sessionKey && t.owner?.accountId === i.accountId)) return t.owner?.sessionKey ? "This automation belongs to another conversation or account. Only its owner, a Gateway owner or an operator can change its prompt or tools; you can create a new automation here instead." : "This automation has no recorded owner, so only a Gateway owner or an operator can change its prompt or tools (for example on the Automations page). You can still enable, disable, reschedule or remove it, or create a new automation here.";
	return requiresExplicitAgentRuntimeToolsAllow({
		job: n,
		callerScope: i
	}) && !isLegacyCreatorPromptUpdate(t, r) ? "Include payload.toolsAllow listing the tools this automation needs (use [] for none)." : void 0;
}
const TRUSTED_LIFECYCLE_PATCH_KEYS = /* @__PURE__ */ new Set([
	"enabled",
	"schedule",
	"displayName",
	"description",
	"deleteAfterRun",
	"wakeMode",
	"pacing",
	"activeHours",
	"idleOnly"
]);
/** Any other edit (prompt, tools, routes, failure alerts, future fields) narrows the job to the caller. */
function cronUpdateNarrowsTrustedJob(e, t, n) {
	return e.scheduledToolPolicy?.mode === "trusted" && n !== void 0 && (!n.manageAll || !e.owner?.sessionKey) && Object.keys(t).some((e) => !TRUSTED_LIFECYCLE_PATCH_KEYS.has(e));
}
/** Narrowing needs the owner's proven account; legacy owner records keep lifecycle edits only. */
function assertTrustedJobNarrowingOwner(e, t) {
	if (!t || !cronTrustedJobOwnedByCaller(e, t, { requireAccount: true })) {
		const t = e.owner ? "its owner record has no account" : "it has no owner conversation";
		throw new TypeError(`This automation runs with operator access and ${t}, so from here you can only pause, resume, reschedule or remove it. To change what it runs or its name, where it reports or where failures alert, create a new automation here or use the Automations page.`);
	}
}
function respondRefusedCronAgent(e, t) {
	const n = e ? readAgentDatabaseAdmissionRefusal(e) : void 0;
	if (!n) return false;
	t(false, void 0, createAgentDatabaseAdmissionErrorShape(n));
	return true;
}
function assertCronReadCurrent(e) {
	e.signal?.throwIfAborted();
	if (e.hasCurrentClientAuthority?.() === false) throw new Error("Cron history authority closed");
	assertActiveAgentRuntimeAuthority(e.client, e.context);
}
function resolveCronJobId(e) {
	return normalizeOptionalString(e.id ?? e.jobId);
}
function respondInvalidCronParams(e, t, n) {
	e(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, `invalid ${t} params: ${n}`));
}
function respondMissingCronJobId(e, t) {
	respondInvalidCronParams(e, t, "missing id");
}
function respondCronJobNotFound(e, t, n = {}) {
	const r = n.preserveCronGetWireMessage ? `cron job not found: ${t}. List automations and retry with a current job id.` : `Automation not found: ${t}. List automations and retry with a current job id.`;
	e(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, `${r} For cross-session management, use a fresh authenticated configured channel owner or Control UI administrator turn or the Automations page.`, { details: {
		code: GatewayErrorDetailCodes.CRON_JOB_NOT_FOUND,
		jobId: t
	} }));
}
function scopedCronJobHandler(e, t, n, r = {}) {
	return defineValidatedGatewayHandler(e, t, async (t) => {
		const { params: i, respond: a, client: o, context: s } = t;
		const c = resolveCronJobId(i);
		if (!c) {
			respondMissingCronJobId(a, e);
			return;
		}
		const l = createCronSessionVisibility(o, s);
		const u = await s.cron.readJob(c);
		const d = r.checkVisibility && l.resolve() !== void 0;
		if (d) await l.prepare();
		if (r.checkVisibility) assertCronReadCurrent(t);
		const f = readCronCallerScope(o);
		const p = d ? s.cron.getJob(c) : u;
		const m = r.checkVisibility ? l.resolve() : void 0;
		if (!p || r.checkVisibility && !cronJobIsVisible(p, m, s.cron.getDefaultAgentId()) || !cronJobMatchesCallerScope({
			job: p,
			callerScope: f,
			defaultAgentId: s.cron.getDefaultAgentId(),
			allowCurrentJob: r.allowCurrentJob
		})) {
			respondCronJobNotFound(a, c, r);
			return;
		}
		return await n(t, {
			jobId: c,
			callerScope: f,
			job: p
		});
	});
}
//#endregion
//#region src/gateway/server-methods/cron-stream-approval.ts
/** Human waits happen after confirmed rollback, outside cron and SQLite locks. */
async function withCronStreamExecApproval(e) {
	const t = Date.now() + DEFAULT_EXEC_APPROVAL_TIMEOUT_MS;
	e.assertCurrent();
	let n;
	try {
		return await e.mutate();
	} catch (e) {
		n = e;
	}
	for (;;) {
		const r = n;
		if (!(r instanceof CronStreamExecApprovalRequiredError) || !r.mutation) throw r;
		const i = e.context.execApprovalManager;
		const a = e.client?.internal?.agentRuntimeIdentity;
		const o = t - Date.now();
		if (!i || !a || !e.creatorSessionId || o <= 0) throw new TypeError("Stream was not saved: user approval is unavailable or expired.");
		e.assertCurrent();
		const s = r.mutation;
		const c = s.job;
		if (c.schedule.kind !== "stream") throw r;
		const l = cronStreamExecApprovalBinding(s);
		const u = c.streamSandbox;
		const d = c.schedule.cwd ?? c.streamSandbox?.containerWorkdir ?? process.cwd();
		const f = u ? await (async () => {
			if (!e.sandboxContext) throw new CronStreamPolicyDeniedError("Sandbox stream approval requires its original admitted sandbox.");
			const { prepareCronStreamSandboxApproval: t } = await import("./cron-stream-sandbox-approval-EKgb8sCN.mjs");
			return await t({
				sandbox: e.sandboxContext,
				target: u
			});
		})() : await (await import("./cron-stream-execution-binding-CIJunFYJ.mjs")).prepareCronStreamExecutionBinding({
			argv: c.schedule.command,
			cwd: d
		});
		e.assertCurrent();
		const p = sanitizeExecApprovalDisplayTextWithStatus(formatExecCommand(c.schedule.command));
		const m = sanitizeExecApprovalDisplayTextWithStatus(d);
		const h = c.payload.kind === "agentTurn" ? `starts the agent task ${JSON.stringify(c.payload.message)}` : c.payload.kind === "systemEvent" ? `posts the session event ${JSON.stringify(c.payload.text)}` : "runs this automation's configured script";
		const g = c.schedule.mode === "match" ? `Output matching ${JSON.stringify(c.schedule.match)}` : "Each batch of output";
		const _ = sanitizeExecApprovalWarningTextWithStatus(`${s.method === "cron.add" ? "Create" : "Reactivate or change"} persistent stream ${JSON.stringify(c.name)}? Watcher ID: ${JSON.stringify(c.id)}. ` + (c.streamSandbox ? "Each start uses a fresh Docker container with this session's approved mounts and configured filesystem, network, and resource restrictions. Sandbox setup runs each time; files outside those mounts are discarded between starts. It keeps running " : "It runs on your Gateway ") + `after this conversation ends and automatically restarts after interruptions, including Gateway restarts, until disabled or deleted. Approve once authorizes this saved watcher and its automatic restarts. ${g} ${h}. Notification delivery: ${c.delivery ? JSON.stringify(c.delivery) : "the session’s configured route"}.`);
		if (p.truncated || p.oversized || m.truncated || m.oversized || _.truncated || _.oversized) throw new TypeError("Stream was not saved: its proposal is too large to display completely for approval.");
		const v = {
			command: p.text,
			commandArgv: [...c.schedule.command],
			cwd: m.text,
			host: c.streamSandbox ? "sandbox" : "gateway",
			security: r.security,
			ask: r.ask,
			allowedDecisions: ["allow-once", "deny"],
			unavailableDecisions: ["allow-always"],
			warningText: _.text,
			streamProposal: {
				jobId: c.id,
				name: sanitizeExecApprovalDisplayTextWithStatus(c.name).text,
				operation: s.method === "cron.add" ? "add" : "update"
			},
			agentId: a.agentId,
			sessionKey: a.sessionKey,
			sessionId: e.creatorSessionId,
			runId: a.operationalRunInstance.runId,
			turnSourceChannel: a.turnSourceChannel,
			turnSourceTo: a.turnSourceTo,
			turnSourceAccountId: a.turnSourceAccountId,
			turnSourceThreadId: a.turnSourceThreadId
		};
		const y = i.create(v, o, `cron-stream:${randomUUID()}`);
		y.agentRuntimeDelegatedAuthority = a.delegatedAuthority;
		y.executionIdentityToken = a.executionIdentity;
		y.approvalAuthority = e.assertCurrent;
		bindApprovalRequesterMetadata({
			record: y,
			client: e.client
		});
		await i.register(y, o);
		let b;
		await handlePendingApprovalRequestWithDelivery({
			approvalKind: "exec",
			manager: i,
			record: y,
			respond: () => {},
			context: e.context,
			twoPhase: false,
			requireDeliveryRoute: true,
			forwardRequest: e.context.forwardExecApprovalRequest,
			getIosPushDelivery: () => e.context.execApprovalIosPushDelivery,
			afterDecision: async (t) => {
				try {
					e.assertCurrent();
					const assertOperatorDecision = () => {
						e.assertCurrent();
						const n = i.getLocalSnapshot(y.id);
						const ended = (e) => {
							return new CronStreamApprovalEndedError({
								action: s.method === "cron.add" ? "add" : "update",
								approvalId: y.id,
								outcome: e
							});
						};
						if (n?.status === "expired") throw ended("expired");
						if (n?.status === "cancelled") throw ended("cancelled");
						const r = n?.resolutionSource === "operator";
						if (r && n?.status === "denied" && n.terminalReason === "user" && t === "deny") throw ended("operator-denied");
						if (!r || i.projectDecisionIfActive(y.id, t) !== "allow-once") throw new TypeError("Stream was not saved: affirmative user approval is required.");
					};
					assertOperatorDecision();
					await f.revalidate?.();
					assertOperatorDecision();
					const n = i.prepareConsumeAllowOnce(y.id, `cron.stream:${s.method}:${c.id}`);
					if (!n) throw new TypeError("Stream was not saved: approval is no longer active.");
					let a;
					b = {
						value: await e.mutate({
							policyKey: r.policyKey,
							binding: l,
							createdAtMs: c.createdAtMs,
							consumption: {
								...n,
								markCommitted: (e) => {
									n.markCommitted(e);
									a = {
										approvalId: e.id,
										decision: "allow-once",
										source: "operator"
									};
								},
								assertCurrent: () => {
									assertOperatorDecision();
									f.assertCurrent();
									n.assertCurrent();
								}
							}
						}),
						...a ? { approval: a } : {}
					};
				} catch (e) {
					b = { error: e };
				}
			}
		});
		if (!b) throw new TypeError("Stream was not saved: no approval was received. Retry from an approval-capable chat or client.");
		if ("error" in b) {
			n = b.error;
			continue;
		}
		if (b.approval) e.onApprovalCommitted?.(b.approval);
		return b.value;
	}
}
//#endregion
//#region src/gateway/server-methods/cron-add.ts
const cronAddHandler = async ({ params: e, respond: t, context: n, client: r, signal: i, sessionMutationCommitGuard: a, hasCurrentClientAuthority: o }) => {
	assertActiveAgentRuntimeAuthority(r, n);
	a?.();
	if (o?.() === false) throw new Error("Automation caller authority is no longer active");
	const s = readPluginCommandCreation(e);
	const c = s.params;
	let l;
	let u;
	try {
		({candidate: l, enabledExplicit: u} = normalizeCronAddRequest(c));
	} catch (e) {
		respondInvalidCronParams(t, "cron.add", formatErrorMessage(e));
		return;
	}
	if (!assertValidParams(l, validateCronAddParams, "cron.add", t)) return;
	const d = readCronCallerScope(r);
	const f = applyCronCreateCallerScopeDefault(l, d);
	const p = n.getRuntimeConfig();
	const m = await prepareCronCreatorSession({
		context: n,
		client: r,
		callerScope: d,
		sessionMutationCommitGuard: a,
		hasCurrentClientAuthority: o,
		retainExecutionPolicy: cronCreateRequiresStreamExecAuthority(l)
	});
	if (s.creation) {
		const e = s.creation.envelope;
		const t = r?.internal?.agentRuntimeIdentity;
		const n = m.session;
		if (!t || t.agentId !== e.parent.agentId || t.sessionKey !== e.parent.sessionKey || t.operationalRunInstance.runId !== e.sourceRunId || n?.agentId !== e.parent.agentId || n.sessionKey !== e.parent.sessionKey || n.entry.sessionId !== e.parent.sessionId || n.entry.lifecycleRevision !== e.parent.lifecycleRevision) throw new Error("Scheduled command creator does not match its admitted parent incarnation.");
	}
	let h;
	let g;
	try {
		assertCronModelJobAllowed(r, p, f);
		g = resolveCronCreatorAuthorityCapture(d);
		h = resolveCronStreamExecPolicy(r, cronCreateRequiresStreamExecAuthority(l), n);
		if (h && !f.id) f.id = randomUUID();
	} catch (e) {
		respondInvalidCronParams(t, "cron.add", formatErrorMessage(e));
		return;
	}
	const _ = resolveCronMutationCommitGuard(r, n, void 0, {
		sessionMutationCommitGuard: a,
		hasCurrentClientAuthority: o
	});
	if (!cronCreateMatchesCallerScope({
		job: f,
		callerScope: d,
		defaultAgentId: n.cron.getDefaultAgentId()
	})) {
		respondInvalidCronParams(t, "cron.add", "job agentId outside caller scope");
		return;
	}
	if (requiresExplicitAgentRuntimeToolsAllow({
		job: f,
		callerScope: d
	})) {
		respondInvalidCronParams(t, "cron.add", "agent-runtime tool jobs require an explicit payload.toolsAllow cap");
		return;
	}
	const v = validateScheduleTimestamp(f.schedule);
	if (!v.ok) {
		t(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, v.message));
		return;
	}
	if (respondRefusedCronAgent(tryResolveCronJobEffectiveAgentId(f, n.cron.getDefaultAgentId()), t)) return;
	let y;
	const commitGuard = () => {
		s.creation?.assertCurrent();
		_?.();
		g?.assertCurrent();
		y?.assertInferenceSelectionCurrent?.();
		assertCronModelJobAllowed(r, p, f);
		y?.assertOperatorSourceCurrent?.();
		m.assertCurrent();
		h?.assertCurrentSource?.();
	};
	try {
		const e = g?.captureRuntimeAuthority();
		g &&= {
			...g,
			captureRuntimeAuthority: () => e
		};
		y = await captureCronCreatorSession(f, d, {
			client: r,
			context: n,
			signal: i
		}, p, e !== void 0);
		await assertCronDoesNotTargetAgentHarness(f, p);
		await assertValidCronCreateDelivery(p, f);
	} catch (e) {
		y?.disposeInferenceAuthorization?.();
		respondInvalidCronParams(t, "cron.add", formatErrorMessage(e));
		return;
	}
	const b = {
		cfg: p,
		defaultAgentId: n.cron.getDefaultAgentId()
	};
	let x;
	let S;
	try {
		x = await resolveCronDeliveryPreview({
			...b,
			job: {
				...f,
				sourceConversation: y.sourceConversation
			}
		});
		const e = h?.sandboxContext ? (() => {
			if (!m.session) throw new TypeError("A sandbox stream requires its current creator session.");
			return captureCronStreamSandboxTarget({
				sandbox: h.sandboxContext,
				...m.session
			});
		})() : void 0;
		S = await withCronStreamExecApproval({
			context: n,
			client: r,
			creatorSessionId: m.session?.entry.sessionId,
			sandboxContext: h?.sandboxContext,
			assertCurrent: commitGuard,
			onApprovalCommitted: h?.onApprovalCommitted,
			mutate: (t) => n.cron.add(f, {
				streamExecApproval: t,
				streamSandbox: e,
				execPolicy: h,
				sessionEntryCurrent: m.sessionEntryCurrent,
				enabledExplicit: u,
				...y,
				...s.creation ? {
					pluginCommand: s.creation.envelope,
					pluginCommandSourceDigest: s.creation.sourceDigest
				} : {},
				commitGuard,
				...g ? { captureRuntimeAuthority: g.captureRuntimeAuthority } : {},
				matchesExisting: (e) => cronJobMatchesDeclarationScope({
					job: e,
					input: f,
					callerScope: d,
					defaultAgentId: n.cron.getDefaultAgentId()
				}),
				...cronJobUsesToolRuntime(f) ? {
					scheduledToolPolicy: resolveCronScheduledToolPolicyForCaller(d),
					...d?.toolsAllowProvenance ? { toolsAllowProvenance: d.toolsAllowProvenance } : {},
					...d?.toolsAllowExecTarget ? { toolsAllowExecTarget: d.toolsAllowExecTarget } : {}
				} : {}
			})
		});
	} catch (e) {
		if (e instanceof CronStreamApprovalEndedError) {
			t(false, void 0, errorShape(ErrorCodes.FORBIDDEN, e.message, {
				details: e.details,
				retryable: false
			}));
			return;
		}
		if (!(e instanceof TypeError) && !(e instanceof RangeError) && !isCronInvalidRequestError(e)) throw e;
		respondInvalidCronParams(t, "cron.add", formatErrorMessage(e));
		return;
	} finally {
		y.disposeInferenceAuthorization?.();
	}
	const C = "job" in S ? S.job : S;
	s.creation?.record(C);
	n.logGateway.info("cron: job added", {
		jobId: C.id,
		declarationKey: C.declarationKey,
		schedule: f.schedule
	});
	t(true, cronAddResultReadView({
		result: S,
		deliveryPreview: "job" in S && !S.created ? await resolveCronDeliveryPreview({
			...b,
			job: C
		}) : x
	}), void 0);
};
//#endregion
//#region src/gateway/server-methods/cron-revision-error.ts
function respondCronJobConfigRevisionConflict(e, t) {
	e(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "cron job definition no longer matches the loaded version; review the latest version before retrying", { details: {
		code: "CRON_JOB_CHANGED",
		expectedConfigRevision: t.expectedConfigRevision,
		actualConfigRevision: t.actualConfigRevision
	} }));
}
//#endregion
//#region src/gateway/server-methods/cron-bind.ts
const BIND_OWNER_TURN_REQUIRED = "cron bind requires an authenticated owner turn in the automation's parent conversation (a Control UI administrator or the configured channel owner).";
const BIND_WRONG_CONVERSATION = "cron bind must run from this automation's parent conversation; this conversation is not its parent.";
const BIND_OTHER_AGENT = "cron bind: this automation runs as a different agent than this conversation, so it cannot use it as its parent.";
/** The caller's own conversation, admitted only for an owner turn holding the management grant. */
function resolveBindCaller(e) {
	const t = e.client?.internal?.agentRuntimeIdentity;
	const n = readCronCallerScope(e.client);
	if (!t || !n?.sessionKey) return { refusal: "cron bind must run from the automation's parent conversation; ask the agent in that conversation to bind it." };
	if (!getCronManagementAuthority(t)) return { refusal: BIND_OWNER_TURN_REQUIRED };
	return { callerScope: {
		...n,
		manageAll: void 0
	} };
}
/** Refusal for a job this conversation cannot bind, or the parent key it binds. */
function resolveBindTarget(e, t, n) {
	const r = resolveCronBindParent(e);
	if ("refusal" in r) return r;
	if (!cronJobMatchesCallerScope({
		job: e,
		callerScope: t,
		defaultAgentId: n
	})) return { refusal: BIND_WRONG_CONVERSATION };
	if (tryResolveCronJobEffectiveAgentId(e, n) !== t.agentId) return { refusal: BIND_OTHER_AGENT };
	return r.parentSessionKey;
}
/**
* `cron.bind`: records the current incarnation of a key-only job's parent conversation as
* its `sourceConversation`, moving it from `unbound-parent` to an exact parent principal.
* The conversation comes from the caller's signed runtime identity, never from params.
*/
const cronBindHandler = defineValidatedGatewayHandler("cron.bind", validateCronBindParams, async (e) => {
	const { params: t, respond: n, context: r, client: i, signal: a } = e;
	const { sessionMutationCommitGuard: o, hasCurrentClientAuthority: s } = e;
	assertActiveAgentRuntimeAuthority(i, r);
	o?.();
	if (s?.() === false) throw new Error("Automation caller authority is no longer active");
	const c = resolveCronJobId(t);
	if (!c) {
		respondMissingCronJobId(n, "cron.bind");
		return;
	}
	const l = resolveBindCaller(e);
	if ("refusal" in l) {
		respondInvalidCronParams(n, "cron.bind", l.refusal);
		return;
	}
	const { callerScope: u } = l;
	const d = r.cron.getDefaultAgentId();
	const f = await r.cron.readJob(c);
	if (!f) {
		respondCronJobNotFound(n, c);
		return;
	}
	const p = resolveBindTarget(f, u, d);
	if (typeof p !== "string") {
		respondInvalidCronParams(n, "cron.bind", p.refusal);
		return;
	}
	const m = r.getRuntimeConfig();
	let h;
	let g;
	try {
		h = await prepareCronCreatorSession({
			context: r,
			client: i,
			callerScope: u,
			sessionMutationCommitGuard: o,
			hasCurrentClientAuthority: s
		});
		g = await captureCronCreatorSession(f, u, {
			client: i,
			context: r,
			signal: a
		}, m, true);
	} catch (e) {
		respondInvalidCronParams(n, "cron.bind", formatErrorMessage(e));
		return;
	}
	const _ = g.sourceConversation;
	const v = h.session;
	if (!_ || !v || _.sessionKey !== p || v.sessionKey !== p) {
		respondInvalidCronParams(n, "cron.bind", BIND_WRONG_CONVERSATION);
		return;
	}
	if (v.entry.sessionId !== _.sessionId || v.entry.lifecycleRevision !== _.lifecycleRevision) {
		respondInvalidCronParams(n, "cron.bind", "Parent conversation changed while binding; retry from the current turn.");
		return;
	}
	if (typeof v.entry.archivedAt === "number") {
		respondInvalidCronParams(n, "cron.bind", "cron bind cannot bind an archived conversation; restore it first.");
		return;
	}
	const y = resolveCronJobConfigRevision(f);
	const b = resolveCronMutationCommitGuard(i, r, void 0, {
		sessionMutationCommitGuard: () => {
			o?.();
			h.assertCurrent();
			g.assertOperatorSourceCurrent?.();
		},
		hasCurrentClientAuthority: s
	});
	let x;
	try {
		x = await r.cron.updateWithPrecondition(c, {}, (e) => {
			if (resolveCronJobConfigRevision(e) !== y) throw new CronJobConfigRevisionConflictError(y, resolveCronJobConfigRevision(e));
		}, {
			bindSourceConversation: _,
			...g.operatorSource ? {
				operatorSource: g.operatorSource,
				operatorSourceExecutionRevision: resolveCronOperatorExecutionRevision({
					...f,
					sourceConversation: _
				})
			} : {},
			sessionEntryCurrent: h.sessionEntryCurrent,
			commitGuard: b
		});
	} catch (e) {
		if (e instanceof CronJobConfigRevisionConflictError) {
			respondCronJobConfigRevisionConflict(n, e);
			return;
		}
		if (!(e instanceof TypeError) && !isCronInvalidRequestError(e)) throw e;
		respondInvalidCronParams(n, "cron.bind", formatErrorMessage(e));
		return;
	}
	r.logGateway.info("cron: job bound to parent conversation", { jobId: c });
	n(true, {
		...cronJobReadView(x),
		bound: { operatorSource: r.cron.getJob(c)?.operatorSource !== void 0 }
	}, void 0);
});
//#endregion
//#region src/gateway/server-methods/cron-history.ts
const MAX_CRON_HISTORY_BYTES = 4194304;
const SAFE_HISTORY_FAILURES = /* @__PURE__ */ new Set([
	"session rows are initializing; reload the conversation",
	"retained transcript is no longer available",
	"retained transcript changed while reading history",
	"retained session changed while reading history",
	"session access changed while reading history",
	"session changed while reading history; reload the conversation",
	"session history is rebuilding; retry shortly",
	"session history window changed; reload the conversation",
	"session history is busy; retry shortly",
	"session history is temporarily unavailable; retry shortly",
	"session history read timed out; retry shortly"
]);
const cronHistoryHandler = async (e) => {
	const { params: t, respond: n, context: r, client: i } = e;
	if (!assertValidParams(t, validateCronHistoryParams, "cron.history", n)) return;
	if (!t.runId && t.runAtMs === void 0) {
		respondError(n, ErrorCodes.INVALID_REQUEST, "cron.history requires an id and exact runId or runAtMs");
		return;
	}
	let a = "run-selection";
	const fail = (e = a) => {
		r.logGateway.debug(`cron.history unavailable: ${e}`);
		respondError(n, ErrorCodes.UNAVAILABLE, "The recorded cron transcript is unavailable. Refresh the run and try again.");
	};
	const o = createCronSessionVisibility(i, r);
	const assertAllowed = (n, a) => {
		assertCronReadCurrent(e);
		const s = readCronCallerScope(i);
		const c = o.resolve();
		const l = r.cron.getJob(t.id);
		const u = r.cron.getDefaultAgentId();
		if ((s || c) && (!l || !cronJobMatchesCallerScope({
			job: l,
			callerScope: s,
			defaultAgentId: u,
			allowCurrentJob: true
		}) || !cronJobIsVisible(l, c, u))) throw new Error("Cron job not found");
		if (n && c && !c(n, a)) throw new Error("Cron transcript not found");
	};
	try {
		await r.cron.readJob(t.id);
		const i = r.cron.getStoreKey?.() ?? cronStoreKey(r.cronStorePath);
		await o.prepare();
		const select = () => readCronRunHistoryBinding(i, t.id, {
			runId: t.runId,
			runAtMs: t.runAtMs
		});
		const s = await select();
		if (!s) {
			fail();
			return;
		}
		const { sessionKey: c, sessionId: l, binding: u } = s;
		const d = parseAgentSessionKey(c)?.agentId ?? s.agentId;
		let f = 0;
		if (t.cursor) {
			const e = JSON.parse(Buffer.from(t.cursor, "base64url").toString("utf8"));
			if (!Array.isArray(e) || e.length !== 2 || e[0] !== u || !Number.isSafeInteger(e[1]) || e[1] < 0) throw new Error("Invalid cron history cursor");
			f = e[1];
		}
		const p = {
			agentId: d,
			sessionId: l,
			storePath: resolveSessionStorePathCore(r.getRuntimeConfig().session?.store, { agentId: d })
		};
		const assertCurrent = (e) => {
			if ((r.cron.getStoreKey?.() ?? cronStoreKey(r.cronStorePath)) !== i || resolveSessionStorePathCore(r.getRuntimeConfig().session?.store, { agentId: d }) !== p.storePath) throw new Error("Cron history store changed");
			assertAllowed(e, d);
		};
		a = "transcript-binding";
		const m = await readSessionHistoryPageInWorker({
			kind: "transcript-binding",
			params: { target: p }
		}, e.signal);
		const { baseSessionKey: h } = parseCronRunScopeSuffix(c);
		if (!m || m.sessionKey !== c && m.sessionKey !== h) {
			fail();
			return;
		}
		a = "retained-history-read";
		const { handleChatHistoryRequest: g } = await import("./chat-history-handler-6XskU_w7.mjs");
		await g({
			...e,
			method: "chat.history",
			retainedTranscript: {
				sessionId: l,
				verifyRetainedState: async () => {
					await r.cron.readJob(t.id);
					return (await select())?.binding === u;
				}
			},
			params: {
				sessionKey: m.sessionKey,
				...d ? { agentId: d } : {},
				limit: t.limit ?? 100,
				offset: f,
				maxBytes: 4177920
			},
			respond: (e, t, r) => {
				if (!e) {
					fail(r?.message && SAFE_HISTORY_FAILURES.has(r.message) ? r.message : a);
					return;
				}
				a = "retained-history-publication";
				const i = asOptionalRecord(t);
				const o = {
					messages: i?.messages,
					...i?.activity ? { activity: i.activity } : {},
					...i?.hasMore === true && typeof i.nextOffset === "number" ? { nextCursor: Buffer.from(JSON.stringify([u, i.nextOffset])).toString("base64url") } : {}
				};
				if (!Value.Check(CronHistoryResultSchema, o) || Buffer.byteLength(JSON.stringify(o)) > MAX_CRON_HISTORY_BYTES) throw new Error("Invalid cron transcript page");
				assertCurrent(m.sessionKey);
				n(true, o);
			}
		});
	} catch {
		fail();
	}
};
//#endregion
//#region src/gateway/server-methods/cron-list-diagnostics.ts
function startCronListDiagnostics(e, t) {
	if (!areDiagnosticsEnabledForProcess()) return;
	let n = performance.now();
	const r = n;
	const i = createStageTimingTracker(() => n);
	const a = getActiveDiagnosticTraceContext();
	let o = "setup";
	let s = n;
	let c = 0;
	let l = 0;
	let u = 0;
	let d = 0;
	let f;
	let p;
	let m = "none";
	let h = false;
	const mark = (e) => {
		if (h) return;
		n = performance.now();
		i.mark(o);
		if (o === "listing") c = n - s;
		o = e;
		s = n;
	};
	return {
		mark,
		setRequestMode(e) {
			p = e;
		},
		setReturnedCount(e) {
			f = e;
		},
		startScopeAttempt() {
			d++;
		},
		startSourcePage() {
			u++;
			const e = performance.now();
			return () => {
				l += performance.now() - e;
			};
		},
		respond: ((...e) => {
			mark("response");
			m = e[0] ? "ok" : "error";
			try {
				return t(...e);
			} catch (e) {
				m = "threw";
				throw e;
			} finally {
				mark("handlerExit");
			}
		}),
		finish(t) {
			if (h) return;
			mark("handlerExit");
			h = true;
			const o = n - r;
			if (o < 1e3 || !areDiagnosticsEnabledForProcess()) return;
			try {
				runWithDiagnosticTraceContext(a, () => e.warn("cron: slow list request", {
					operation: "cron.list",
					elapsedMs: Math.round(o),
					phaseDurationsMs: Object.fromEntries(i.snapshot().stages.map((e) => [e.name, e.durationMs])),
					sourcePageMs: Math.round(l),
					sourcePageCount: u,
					scopeAttemptCount: d,
					...f === void 0 ? {} : { returnedCount: f },
					...p?.scopeApplied ? { scopeProcessingMs: Math.round(c - l) } : {},
					...p,
					handlerOutcome: t,
					responseOutcome: m
				}));
			} catch {}
		}
	};
}
//#endregion
//#region src/gateway/server-methods/cron-list-projection.ts
const projections = /* @__PURE__ */ new WeakMap();
/** Each owner's revision covers the filtered rows; the default agent completes presentation identity. */
function projectCronListJobs(e, t, n) {
	const r = e.getDefaultAgentId();
	const i = JSON.stringify([
		t.snapshotRevision,
		t.offset,
		t.limit
	]);
	const a = n ? "compact" : "full";
	let o = projections.get(e);
	if (!o || o.defaultAgentId !== r) {
		o = {
			defaultAgentId: r,
			rows: /* @__PURE__ */ new WeakMap()
		};
		projections.set(e, o);
	}
	if (o[a]?.key !== i) o[a] = {
		key: i,
		jobs: prepareJobs(t.jobs, o, n)
	};
	return o[a].jobs;
}
function prepareJobs(e, t, n) {
	const r = n ? "compact" : "full";
	const i = e.map((e) => {
		let i = t.rows.get(e);
		if (!i) {
			i = {};
			t.rows.set(e, i);
		}
		return i[r] ??= prepareJob(e, t.defaultAgentId, n);
	});
	return registerSerializedJsonArray(Object.freeze(i.map(({ row: e }) => e)), i.map(({ json: e }) => e));
}
function prepareJob(e, t, n) {
	const r = freezeTrustedJsonSnapshot({
		...n ? compactCronListJob(toPublicCronJob(e)) : cronJobReadView(e),
		effectiveAgentId: tryResolveCronJobEffectiveAgentId(e, t) ?? null
	});
	return {
		row: r,
		json: JSON.stringify(r)
	};
}
function compactCronListJob(e) {
	const t = {
		id: e.id,
		name: e.name,
		agentId: e.agentId,
		updatedAtMs: e.updatedAtMs,
		declarationKey: e.declarationKey || void 0,
		displayName: e.displayName || void 0,
		owner: e.owner,
		enabled: e.enabled,
		nextRunAt: timestampMsToIsoString(e.state.nextRunAtMs) ?? null,
		nextRunAtMs: e.state.nextRunAtMs ?? null,
		scheduleKind: e.schedule.kind,
		...e.streamExecutionHost ? { streamExecutionHost: e.streamExecutionHost } : {},
		...e.schedule.kind === "at" || e.schedule.kind === "every" || e.schedule.kind === "cron" ? { schedule: e.schedule } : {},
		trigger: e.trigger ? true : void 0,
		lastRunAt: timestampMsToIsoString(e.state.lastRunAtMs) ?? null,
		lastRunAtMs: e.state.lastRunAtMs ?? null,
		lastDurationMs: e.state.lastDurationMs,
		lastTriggerEvalAtMs: e.state.lastTriggerEvalAtMs,
		lastMeaningfulResult: e.state.lastMeaningfulResult,
		lastRunStatus: e.state.lastRunStatus ?? e.state.lastStatus ?? null,
		lastRunError: e.state.lastError ?? null,
		runningAtMs: e.state.runningAtMs,
		autoDisabled: e.state.autoDisabled,
		lastDelivered: e.state.lastDelivered,
		lastDeliveryStatus: e.state.lastDeliveryStatus,
		lastDeliveryError: e.state.lastDeliveryError,
		deliverySuppressionReason: e.state.deliverySuppressionReason,
		lastFailureNotificationDelivered: e.state.lastFailureNotificationDelivered,
		lastFailureNotificationDeliveryStatus: e.state.lastFailureNotificationDeliveryStatus,
		lastFailureNotificationDeliveryError: e.state.lastFailureNotificationDeliveryError
	};
	for (const [e, n] of Object.entries(t)) if (n === void 0) Reflect.deleteProperty(t, e);
	return t;
}
//#endregion
//#region src/gateway/server-methods/cron-list.ts
const cronListHandler = createPreparedReadHandler((e) => {
	const { params: t, respond: n, context: r, client: i } = e;
	const a = startCronListDiagnostics(r.logGateway, n);
	const o = a?.respond ?? n;
	const s = createCronSessionVisibility(i, r);
	let c = "returned";
	let l = false;
	try {
		if (!assertValidParams(t, validateCronListParams, "cron.list", o)) return;
		const n = t;
		const c = readCronCallerScope(i);
		const u = c?.manageAll ? void 0 : c;
		const d = n.agentId ? normalizeAgentId(n.agentId) : void 0;
		if (u && d && d !== u.agentId) {
			respondInvalidCronParams(o, "cron.list", "agentId outside caller scope");
			return;
		}
		const release = (e) => {
			a?.finish(e);
		};
		const f = !u && !s.resolve();
		a?.setRequestMode({
			compact: n.compact === true,
			previewsRequested: n.compact !== true && n.includeDeliveryPreviews !== false,
			scopeApplied: !f
		});
		l = true;
		return {
			shareable: f,
			respond: o,
			assertCurrent: () => assertCronReadCurrent(e),
			release,
			run: async (t) => {
				const o = {
					includeDisabled: n.includeDisabled,
					limit: n.limit,
					offset: n.offset,
					query: n.query,
					enabled: n.enabled,
					scheduleKind: n.scheduleKind,
					lastRunStatus: n.lastRunStatus,
					trigger: n.trigger,
					sortBy: n.sortBy,
					sortDir: n.sortDir,
					agentId: u ? void 0 : n.agentId
				};
				const matchesRequestScope = (e) => {
					const t = readCronCallerScope(i);
					const a = t?.manageAll ? void 0 : t;
					const o = r.cron.getDefaultAgentId();
					if (!cronJobMatchesCallerScope({
						job: e,
						callerScope: a,
						defaultAgentId: o,
						allowCurrentJob: true
					})) return false;
					if (!n.sessionKey) return true;
					const s = resolveCronJobSessionBindings(e, {
						cfg: r.getRuntimeConfig(),
						defaultAgentId: o
					}).get(n.sessionKey);
					return s !== void 0 && (parseAgentSessionKey(n.sessionKey) !== null || !n.sessionAgentId || s === normalizeAgentId(n.sessionAgentId));
				};
				await s.prepare();
				const c = s.resolve();
				a?.mark("listing");
				const l = /* @__PURE__ */ new Set();
				const matchesCurrentJob = (e) => matchesRequestScope(e) && cronJobIsVisible(e, s.resolve(), r.cron.getDefaultAgentId());
				const assertPageCurrent = () => {
					assertCronReadCurrent(e);
					const t = readCronCallerScope(i);
					if (Boolean(t && !t.manageAll) !== Boolean(u) || Boolean(s.resolve()) !== Boolean(c)) throw new Error("Cron list visibility changed; refresh the page");
					if (l.size <= 1) {
						for (const e of l) {
							const t = r.cron.getJob(e);
							if (!t || !matchesCurrentJob(t)) throw new Error("Cron list visibility changed; refresh the page");
						}
						return;
					}
					for (const e of r.cron.getLoadedJobs() ?? []) {
						if (!l.delete(e.id)) continue;
						if (!matchesCurrentJob(e)) throw new Error("Cron list visibility changed; refresh the page");
						if (l.size === 0) return;
					}
					throw new Error("Cron list visibility changed; refresh the page");
				};
				let matchesJob;
				if (u || c || n.sessionKey) {
					a?.startScopeAttempt();
					matchesJob = (e) => {
						const t = matchesCurrentJob(e);
						if (t) l.add(e.id);
						return t;
					};
				}
				let d;
				const f = a?.startSourcePage();
				try {
					d = await r.cron.listPage(o, matchesJob);
				} finally {
					f?.();
				}
				a?.setReturnedCount(d.jobs.length);
				a?.mark("projection");
				const p = projectCronListJobs(r.cron, d, n.compact === true);
				if (n.compact === true || n.includeDeliveryPreviews === false) {
					assertPageCurrent();
					t(true, {
						...d,
						jobs: p
					}, void 0);
					return;
				}
				a?.mark("previews");
				const m = await resolveCronDeliveryPreviews({
					cfg: r.getRuntimeConfig(),
					defaultAgentId: r.cron.getDefaultAgentId(),
					jobs: d.jobs
				});
				assertPageCurrent();
				t(true, {
					...d,
					jobs: p,
					deliveryPreviews: m
				}, void 0);
			}
		};
	} catch (e) {
		c = "threw";
		throw e;
	} finally {
		if (!l) a?.finish(c);
	}
});
//#endregion
//#region src/gateway/server-methods/cron-run-log-filters.ts
function filterCronRunLogJobsByAgent(e, t, n) {
	if (!t) return [...e];
	const r = normalizeAgentId(t);
	return e.filter((e) => tryResolveCronJobEffectiveAgentId(e, n) === r);
}
function cronRunLogPageFilters(e) {
	return {
		view: e.view,
		limit: e.limit,
		offset: e.offset,
		statuses: e.statuses,
		status: e.status,
		runId: e.runId,
		deliveryStatuses: e.deliveryStatuses,
		deliveryStatus: e.deliveryStatus,
		query: e.query,
		sortDir: e.sortDir
	};
}
//#endregion
//#region src/gateway/server-methods/cron-runs.ts
const cronRunsHandler = async (e) => {
	const { params: t, respond: n, context: r, client: i } = e;
	if (!assertValidParams(t, validateCronRunsParams, "cron.runs", n)) return;
	const a = t;
	const o = a.id !== void 0 || a.jobId !== void 0;
	const s = resolveCronJobId(a);
	const c = a.scope ?? (o ? "job" : "all");
	const l = createCronSessionVisibility(i, r);
	const assertCurrent = (t) => {
		assertCronReadCurrent(e);
		if ((r.cron.getStoreKey?.() ?? cronStoreKey(r.cronStorePath)) !== t) throw new Error("Cron history store changed; retry the request");
	};
	if (c === "all" && readCronCallerScope(i)) {
		respondInvalidCronParams(n, "cron.runs", "scope all is not allowed by caller scope");
		return;
	}
	if (c !== "all" && !s) {
		respondMissingCronJobId(n, "cron.runs");
		return;
	}
	try {
		const e = c === "all" ? await r.cron.list({ includeDisabled: true }) : [await r.cron.readJob(s)].filter((e) => e !== void 0);
		const t = r.cron.getStoreKey?.() ?? cronStoreKey(r.cronStorePath);
		await l.prepare();
		const resolvePageOptions = () => {
			const o = l.resolve();
			const u = r.cron.getDefaultAgentId();
			const d = readCronCallerScope(i);
			if (c === "all") {
				if (d) throw new Error("Cron history scope changed; retry the request");
				const n = filterCronRunLogJobsByAgent(e.flatMap(({ id: e }) => {
					const t = r.cron.getJob(e);
					return t ? [t] : [];
				}), a.agentId, u).filter((e) => cronJobIsVisible(e, o, u));
				const i = new Set(n.map((e) => e.id));
				return {
					storeKey: t,
					...cronRunLogPageFilters(a),
					agentId: a.agentId,
					jobNameById: Object.fromEntries(n.map((e) => [e.id, e.name])),
					entryFilter: o ? (e) => i.has(e.jobId) && (!e.sessionKey || o(e.sessionKey, a.agentId)) : void 0
				};
			}
			const f = r.cron.getJob(s);
			const p = f && filterCronRunLogJobsByAgent([f], a.agentId, u).length > 0 && cronJobIsVisible(f, o, u) && cronJobMatchesCallerScope({
				job: f,
				callerScope: d,
				defaultAgentId: u,
				allowCurrentJob: true
			}) ? f : void 0;
			if ((d || a.agentId || o) && !p) {
				respondCronJobNotFound(n, s);
				return;
			}
			return {
				storeKey: t,
				jobId: s,
				...cronRunLogPageFilters(a),
				jobNameById: p && typeof p.name === "string" ? { [s]: p.name } : void 0,
				entryFilter: o ? (e) => !e.sessionKey || o(e.sessionKey, p?.agentId) : void 0
			};
		};
		const o = resolvePageOptions();
		if (!o) return;
		const u = await readCronRunHistoryCandidates(t, c === "all" ? void 0 : s, a.query, a.query ? o.jobNameById : void 0);
		const { records: d } = u;
		if (c !== "all" && !r.cron.getJob(s) && projectCronRunHistoryPage(d, {
			storeKey: t,
			jobId: s,
			limit: 1
		}).total === 0) {
			assertCurrent(t);
			respondCronJobNotFound(n, s);
			return;
		}
		const f = u.queryMatches ? new Set(u.queryMatches) : void 0;
		const p = selectCronRunHistoryPage(d, {
			...o,
			queryMatchedTaskIds: f
		});
		const m = await readCronRunHistoryRecords(t, p.records.map((e) => e.id), a.view);
		assertCurrent(t);
		const h = resolvePageOptions();
		if (!h) return;
		const g = new Map(m.map((e) => [e.id, e]));
		const _ = selectCronRunHistoryPage(d.map((e) => g.get(e.id) ?? e), {
			...h,
			queryMatchedTaskIds: f
		});
		const v = new Set(_.records.map((e) => e.id));
		const y = projectCronRunHistoryPage(m.filter((e) => v.has(e.id)), {
			...h,
			offset: 0,
			query: void 0,
			runId: void 0
		}).entries;
		n(true, {
			..._.page,
			entries: y
		}, void 0);
	} catch (e) {
		if (!isInvalidCronRunJobIdError(e)) throw e;
		respondInvalidCronParams(n, "cron.runs", "invalid id");
	}
};
//#endregion
//#region src/gateway/server-methods/cron-scratch.ts
const cronScratchHandlers = {
	"cron.scratch.get": scopedCronJobHandler("cron.scratch.get", validateCronScratchGetParams, async (e, { jobId: t }) => {
		const { respond: n, context: r, client: i } = e;
		const assertCurrent = () => {
			assertCronReadCurrent(e);
			const n = r.cron.getJob(t);
			if (!n || !cronJobMatchesCallerScope({
				job: n,
				callerScope: readCronCallerScope(i),
				defaultAgentId: r.cron.getDefaultAgentId(),
				allowCurrentJob: true
			})) throw new Error("Cron scratch owner changed before reply");
		};
		assertCurrent();
		const a = await r.cron.readScratch(t, {
			assertCurrent,
			signal: e.signal
		});
		assertCurrent();
		n(true, {
			scratch: cronScratchReadView(a.scratch),
			currentRevision: a.currentRevision,
			maxBytes: CRON_JOB_SCRATCH_MAX_BYTES
		}, void 0);
	}, { allowCurrentJob: true }),
	"cron.scratch.set": scopedCronJobHandler("cron.scratch.set", validateCronScratchSetParams, async ({ params: e, respond: t, context: n, client: r, sessionMutationCommitGuard: i, hasCurrentClientAuthority: a }, { jobId: o, callerScope: s, job: c }) => {
		const l = e;
		const u = n.cron.getDefaultAgentId();
		const operatorOnly = (e, t) => Boolean(t && !t.manageAll) && e?.scheduledToolPolicy?.mode === "trusted" && !cronCallerRunsJob(e, t, u);
		const d = "This automation runs with operator access, so only a Gateway owner, an operator or the automation's own run can change its scratch.";
		if (operatorOnly(c, s)) {
			respondInvalidCronParams(t, "cron.scratch.set", d);
			return;
		}
		try {
			const e = resolveCronMutationCommitGuard(r, n, {
				callerScope: s,
				jobId: o,
				allowCurrentJob: true
			}, {
				sessionMutationCommitGuard: i,
				hasCurrentClientAuthority: a
			});
			const commitGuard = () => {
				e?.();
				if (operatorOnly(n.cron.getJob(o), readCronCallerScope(r))) throw new TypeError(d);
			};
			const c = await n.cron.writeScratch(o, {
				content: l.content,
				expectedRevision: l.expectedRevision,
				commitGuard
			});
			if (!c.ok) {
				t(true, c, void 0);
				return;
			}
			t(true, {
				ok: true,
				scratch: cronScratchReadView(c.scratch),
				currentRevision: c.currentRevision,
				maxBytes: CRON_JOB_SCRATCH_MAX_BYTES
			}, void 0);
		} catch (e) {
			respondInvalidCronParams(t, "cron.scratch.set", formatErrorMessage(e));
		}
	}, { allowCurrentJob: true })
};
//#endregion
//#region src/gateway/server-methods/cron-wake.ts
const cronWakeHandler = async ({ params: e, respond: t, context: n, client: r, sessionMutationCommitGuard: i }) => {
	if (!assertValidParams(e, validateWakeParams, "wake", t)) return;
	const a = e;
	const o = a.sessionKey?.trim() || void 0;
	const s = a.agentId?.trim() || void 0;
	const c = readCronCallerScope(r);
	const l = o ? parseAgentSessionKey(o)?.agentId : void 0;
	if (c && s && normalizeAgentId(s) !== c.agentId) {
		respondError(t, ErrorCodes.INVALID_REQUEST, "wake agentId outside caller scope");
		return;
	}
	if (s && l && s.toLowerCase() !== l) {
		respondError(t, ErrorCodes.INVALID_REQUEST, `agent "${s}" does not match session key agent "${l}"`);
		return;
	}
	const u = o ? resolveRequestedSessionAgentId(n.getRuntimeConfig(), o, s ?? c?.agentId) : void 0;
	if (u && !u.ok) {
		t(false, void 0, u.error);
		return;
	}
	if (respondRefusedCronAgent(u?.agentId ?? c?.agentId ?? s ?? tryResolveAmbientOwnerAgentId(n.getRuntimeConfig()), t)) return;
	const d = u?.agentId ?? c?.agentId ?? s;
	if (o && isAgentHarnessSessionKey(o)) {
		const e = await loadGatewaySessionEntryReadOnlyInWorker({
			cfg: n.getRuntimeConfig(),
			key: o,
			...d ? { agentId: d } : {},
			assertActive: i
		});
		const r = e.entry ? resolveAgentHarnessSessionStoreEntryError(e.canonicalKey, e.entry) : AGENT_HARNESS_SESSION_KEY_RESERVED_MESSAGE;
		if (r) {
			respondError(t, ErrorCodes.INVALID_REQUEST, r);
			return;
		}
	}
	if (o && isSubagentSessionKey(o)) {
		respondError(t, ErrorCodes.INVALID_REQUEST, "wake sessionKey cannot target a subagent session");
		return;
	}
	const f = n.getRuntimeConfig();
	if (f.gateway?.roles) {
		const e = d ?? n.cron.getDefaultAgentId();
		const i = e ? {
			ok: true,
			agentId: e
		} : resolveRequestedSessionAgentId(f, o ?? "main");
		if (!i.ok) {
			t(false, void 0, i.error);
			return;
		}
		const a = authorizeGatewaySessionCreation({
			cfg: f,
			client: r,
			agentId: i.agentId
		});
		if (a) {
			t(false, void 0, a);
			return;
		}
	}
	await n.cron.prepareWake?.();
	t(true, await n.cron.wake({
		mode: a.mode,
		text: a.text,
		commitGuard: () => {
			i?.();
			assertActiveAgentRuntimeAuthority(r, n);
		},
		...o ? { sessionKey: o } : {},
		...d ? { agentId: d } : {}
	}), void 0);
};
//#endregion
//#region src/gateway/server-methods/cron.ts
const cronHandlers = {
	wake: cronWakeHandler,
	"cron.list": cronListHandler,
	"cron.status": async ({ params: e, respond: t, context: n }) => {
		if (!assertValidParams(e, validateCronStatusParams, "cron.status", t)) return;
		t(true, await n.cron.status(), void 0);
	},
	"cron.get": scopedCronJobHandler("cron.get", validateCronGetParams, ({ respond: e }, { job: t }) => e(true, cronJobReadView(t), void 0), {
		allowCurrentJob: true,
		checkVisibility: true,
		preserveCronGetWireMessage: true
	}),
	...cronScratchHandlers,
	"cron.add": cronAddHandler,
	"cron.bind": cronBindHandler,
	"cron.update": async ({ params: e, respond: t, context: n, client: r, signal: i, sessionMutationCommitGuard: a, hasCurrentClientAuthority: o }) => {
		assertActiveAgentRuntimeAuthority(r, n);
		a?.();
		if (o?.() === false) throw new Error("Automation caller authority is no longer active");
		let s;
		let c;
		try {
			({candidate: s, normalizedPatch: c} = normalizeCronUpdateRequest(e));
		} catch (e) {
			respondInvalidCronParams(t, "cron.update", formatErrorMessage(e));
			return;
		}
		if (!assertValidParams(s, validateCronUpdateParams, "cron.update", t)) return;
		if (!c) {
			respondInvalidCronParams(t, "cron.update", "patch did not normalize");
			return;
		}
		const l = s;
		const u = readCronCallerScope(r);
		const d = resolveCronJobId(l);
		if (!d) {
			respondMissingCronJobId(t, "cron.update");
			return;
		}
		const f = c;
		const p = n.getRuntimeConfig();
		const m = await n.cron.readJob(d);
		if (!m || !cronJobMatchesCallerScope({
			job: m,
			callerScope: u,
			defaultAgentId: n.cron.getDefaultAgentId()
		})) {
			respondCronJobNotFound(t, d);
			return;
		}
		const h = u?.manageAll && (!u.sessionKey || m.owner?.sessionKey !== u.sessionKey || normalizeAccountId(m.owner?.accountId) !== u.accountId) ? void 0 : u && {
			...u,
			manageAll: void 0
		};
		let g;
		let _;
		let v;
		let y;
		let b;
		let x;
		if (u && !u.manageAll && "agentId" in f) {
			respondInvalidCronParams(t, "cron.update", "agentId cannot be changed by caller scope");
			return;
		}
		if (!cronPatchSessionRefsMatchCaller(f, u)) {
			respondInvalidCronParams(t, "cron.update", "session target outside caller scope");
			return;
		}
		if (("agentId" in f || "sessionTarget" in f || "sessionKey" in f) && respondRefusedCronAgent(tryResolveCronJobEffectiveAgentId({
			...m,
			...f
		}, n.cron.getDefaultAgentId()), t)) return;
		if (f.schedule) {
			const e = validateScheduleTimestamp(f.schedule);
			if (!e.ok) {
				t(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, e.message));
				return;
			}
		}
		const S = f.payload !== void 0 || Object.hasOwn(f, "trigger");
		const C = cronUpdateNarrowsTrustedJob(m, f, u);
		let w;
		const validateUpdate = async (e) => {
			assertCronModelJobAllowed(r, p, e, f);
			const t = await assertValidCronUpdatePatch({
				cfg: p,
				defaultAgentId: n.cron.getDefaultAgentId(),
				currentJob: e,
				patch: f
			});
			if (u?.manageAll && h && f.payload?.toolsAllow?.length && (!g && e.runtimeAuthority !== void 0 || e.owner?.sessionKey !== h.sessionKey || !cronJobMatchesCallerScope({
				job: e,
				callerScope: h
			}) || !cronCreateMatchesCallerScope({
				job: t,
				callerScope: h
			}))) throw new TypeError(`Cannot authorize toolsAllow: ${f.payload?.toolsAllow?.join(", ") ?? ""}. Recreate the automation from a fresh authenticated owner turn to capture app authority.`);
			if (cronUpdateNarrowsTrustedJob(e, f, u) !== C) throw new TypeError("This automation changed while the update was pending. Read it again and retry.");
			if (C) assertTrustedJobNarrowingOwner(e, u);
			const i = S ? resolveCronScopedToolEditRefusal({
				job: e,
				nextJob: t,
				patch: f,
				callerScope: u
			}) : void 0;
			if (i) throw new TypeError(i);
			return t;
		};
		try {
			b = resolveCronStreamExecPolicy(r, cronUpdateRequiresStreamExecAuthority(f, m), n);
			g = resolveCronCreatorAuthorityCapture(h);
			const e = g?.captureRuntimeAuthority();
			g &&= {
				...g,
				captureRuntimeAuthority: () => e
			};
			const t = await validateUpdate(m);
			if (h) {
				y = resolveCronOperatorExecutionRevision(t);
				v = await captureCronCreatorSession(t, h, {
					client: r,
					context: n,
					signal: i
				}, p, true);
			}
			_ = e ? void 0 : await captureCronUpdatedInferenceBinding(t, f, p, {
				client: r,
				context: n,
				signal: i
			});
		} catch (e) {
			respondInvalidCronParams(t, "cron.update", formatErrorMessage(e));
			return;
		}
		const T = resolveCronMutationCommitGuard(r, n, void 0, {
			sessionMutationCommitGuard: () => {
				a?.();
				g?.assertCurrent();
				_?.assertInferenceSelectionCurrent();
				v?.assertOperatorSourceCurrent?.();
			},
			hasCurrentClientAuthority: o,
			modelJobPolicy: {
				config: p,
				jobId: d,
				patch: f
			}
		});
		const E = {
			...v?.operatorSource ? {
				operatorSource: v.operatorSource,
				operatorSourceExecutionRevision: y
			} : {},
			...S || C ? {
				scheduledToolPolicy: u?.manageAll && !g ? null : resolveCronScheduledToolPolicyForCaller(u),
				toolsAllowExecTarget: u?.toolsAllowExecTarget
			} : {},
			..._?.inferenceBinding ? { inferenceBinding: _.inferenceBinding } : {},
			commitGuard: T,
			...g ? { captureRuntimeAuthority: g.captureRuntimeAuthority } : {}
		};
		let D;
		try {
			if (m.streamSandbox && b && !b.sandboxContext) {
				assertActiveAgentRuntimeAuthority(r, n);
				throw new TypeError("Change this sandbox stream from its original sandbox session.");
			}
			if (b) {
				const e = await prepareCronCreatorSession({
					context: n,
					client: r,
					callerScope: u,
					sessionMutationCommitGuard: a,
					hasCurrentClientAuthority: o,
					retainExecutionPolicy: true
				});
				if (!E) throw new TypeError("A stream change requires its current creator authority.");
				if (b.sandboxContext) {
					if (!e.session) throw new TypeError("A sandbox stream requires its current creator session.");
					const t = captureCronStreamSandboxTarget({
						sandbox: b.sandboxContext,
						...e.session
					});
					if (m.streamSandbox && (m.streamSandbox.scopeKey !== t.scopeKey || m.streamSandbox.sessionId !== t.sessionId)) {
						assertActiveAgentRuntimeAuthority(r, n);
						throw new TypeError("Change this sandbox stream from its original sandbox session.");
					}
					E.streamSandbox = t;
				}
				E.sessionEntryCurrent = e.sessionEntryCurrent;
				x = e.session?.entry.sessionId;
				E.commitGuard = () => {
					T?.();
					e.assertCurrent();
					b?.assertCurrentSource?.();
				};
			}
			D = await withCronStreamExecApproval({
				context: n,
				client: r,
				creatorSessionId: x,
				sandboxContext: b?.sandboxContext,
				assertCurrent: () => E?.commitGuard?.(),
				onApprovalCommitted: (e) => b?.onApprovalCommitted?.(e),
				mutate: (e) => {
					if (E && e) E.streamExecApproval = e;
					return n.cron.updateWithPrecondition(d, f, async (e) => {
						if (!cronJobMatchesCallerScope({
							job: e,
							callerScope: u,
							defaultAgentId: n.cron.getDefaultAgentId()
						})) throw new Error(`unknown cron job id: ${d}`);
						if (l.expectedConfigRevision !== void 0) {
							const t = resolveCronJobConfigRevision(e);
							if (t !== l.expectedConfigRevision) throw new CronJobConfigRevisionConflictError(l.expectedConfigRevision, t);
						}
						const t = cronUpdateRequiresStreamExecAuthority(f, e);
						if (t && !b) b = resolveCronStreamExecPolicy(r, true, n);
						const i = t ? b : void 0;
						const a = await validateUpdate(e);
						w = await resolveCronDeliveryFailurePreview({
							cfg: p,
							defaultAgentId: n.cron.getDefaultAgentId(),
							job: a
						});
						if (E) {
							E.execPolicy = i;
							E.toolsAllowProvenance = resolveCronRequesterProvenanceForJob(e, u);
						}
					}, E);
				}
			});
		} catch (e) {
			if (e instanceof CronStreamApprovalEndedError) {
				t(false, void 0, errorShape(ErrorCodes.FORBIDDEN, e.message, {
					details: e.details,
					retryable: false
				}));
				return;
			}
			if (e instanceof CronJobConfigRevisionConflictError) {
				respondCronJobConfigRevisionConflict(t, e);
				return;
			}
			if (!(e instanceof TypeError) && !(e instanceof RangeError) && !isCronInvalidRequestError(e)) throw e;
			respondInvalidCronParams(t, "cron.update", formatErrorMessage(e));
			return;
		} finally {
			_?.disposeInferenceAuthorization();
		}
		n.logGateway.info("cron: job updated", { jobId: d });
		t(true, {
			...cronJobReadView(D),
			...w ? { deliveryPreview: w } : {}
		}, void 0);
	},
	"cron.remove": scopedCronJobHandler("cron.remove", validateCronRemoveParams, async ({ params: e, respond: t, context: n, client: r, sessionMutationCommitGuard: i, hasCurrentClientAuthority: a }, { jobId: o, callerScope: s, job: c }) => {
		const l = n.cron.getDefaultAgentId();
		const u = !cronJobMatchesCallerScope({
			job: c,
			callerScope: s,
			defaultAgentId: l
		});
		const d = u ? resolveCronJobConfigRevision(c) : void 0;
		const f = e.expectedConfigRevision ?? d;
		let p;
		try {
			let e = resolveCronMutationCommitGuard(r, n, {
				callerScope: s,
				jobId: o,
				allowCurrentJob: u,
				expectedConfigRevision: d
			}, {
				sessionMutationCommitGuard: i,
				hasCurrentClientAuthority: a
			});
			const t = r?.internal?.agentRuntimeIdentity;
			const c = n.validateAgentRuntimeApprovalAuthority;
			if (t && c && e && s?.currentJobId === o) e = bindCronSelfRemovalCommitGuard(o, t.operationalRunInstance, e, () => {
				if (!c(t) || readCronCallerScope(r)?.currentJobId !== o) throw new TypeError("cron self-removal authority is no longer active");
			});
			p = e || f !== void 0 ? await n.cron.remove(o, {
				...e ? { commitGuard: e } : {},
				...f !== void 0 ? { expectedConfigRevision: f } : {}
			}) : await n.cron.remove(o);
		} catch (e) {
			if (e instanceof CronJobConfigRevisionConflictError) {
				respondCronJobConfigRevisionConflict(t, e);
				return;
			}
			if (e instanceof TypeError || isCronInvalidRequestError(e)) {
				respondInvalidCronParams(t, "cron.remove", formatErrorMessage(e));
				return;
			}
			throw e;
		}
		if (!p.removed) {
			respondCronJobNotFound(t, o);
			return;
		}
		n.logGateway.info("cron: job removed", { jobId: o });
		t(true, p, void 0);
	}, { allowCurrentJob: true }),
	"cron.run": scopedCronJobHandler("cron.run", validateCronRunParams, async (e, { jobId: t, callerScope: n, job: r }) => {
		const { params: i, respond: a, context: o, client: s, sessionMutationCommitGuard: c, hasCurrentClientAuthority: l } = e;
		if (i.expectedProcessInstanceId && i.expectedProcessInstanceId !== getGatewayProcessInstanceId()) {
			respondInvalidCronParams(a, "cron.run", "Gateway process changed after preflight");
			return;
		}
		let u;
		const d = o.getRuntimeConfig();
		try {
			assertCronModelJobAllowed(s, d, r);
			const e = resolveCronMutationCommitGuard(s, o, {
				callerScope: n,
				jobId: t
			}, {
				sessionMutationCommitGuard: c,
				hasCurrentClientAuthority: l,
				modelJobPolicy: {
					config: d,
					jobId: t
				}
			});
			u = e ? await o.cron.enqueueRun(t, i.mode ?? "force", { commitGuard: e }) : await o.cron.enqueueRun(t, i.mode ?? "force");
		} catch (e) {
			if (e instanceof TypeError) {
				respondInvalidCronParams(a, "cron.run", formatErrorMessage(e));
				return;
			}
			if (isInvalidCronSessionTargetIdError(e)) {
				a(true, {
					ok: true,
					ran: false,
					reason: "invalid-spec"
				}, void 0);
				return;
			}
			if (isCronInvalidRequestError(e)) {
				respondInvalidCronParams(a, "cron.run", formatErrorMessage(e));
				return;
			}
			throw e;
		}
		const f = {
			...u,
			processInstanceId: getGatewayProcessInstanceId()
		};
		const p = i.waitTimeoutMs !== void 0 && "enqueued" in u && await cronRunQueuesBehindCaller({
			job: r,
			cfg: o.getRuntimeConfig(),
			caller: s?.internal?.agentRuntimeIdentity,
			resolveDefaultAgentId: () => o.cron.getDefaultAgentId()
		});
		let m;
		let h = false;
		if (i.waitTimeoutMs !== void 0 && "enqueued" in u && !p) h = await o.cron.waitForManualRun(u.runId, i.waitTimeoutMs, e.signal);
		if (h && "enqueued" in u) try {
			await cronRunsHandler({
				...e,
				params: {
					id: t,
					runId: u.runId,
					limit: 1
				},
				respond: (e, t) => {
					m = e && isRecord(t) && Array.isArray(t.entries) ? t.entries[0] : void 0;
				}
			});
			assertCronReadCurrent(e);
			const n = s?.internal?.agentRuntimeIdentity;
			if (n) getCronManagementAuthority(n)?.();
		} catch {
			m = void 0;
			h = false;
		}
		a(true, m ? {
			...f,
			run: m
		} : h ? {
			...f,
			finished: h
		} : f, void 0);
	}),
	"cron.history": cronHistoryHandler,
	"cron.runs": cronRunsHandler
};
for (const [e, t] of Object.entries(cronHandlers)) {
	const invoke = async (n) => {
		const r = n.client?.internal?.agentRuntimeIdentity;
		if (!r) return await t(n);
		const i = r.cronManagementGrant;
		let a = false;
		const run = async () => {
			assertActiveAgentRuntimeAuthority(n.client, n.context);
			await t({
				...n,
				respond: (...t) => {
					if (e === "cron.list" || e === "cron.get" || e === "cron.runs" || e === "cron.history") {
						assertActiveAgentRuntimeAuthority(n.client, n.context);
						getCronManagementAuthority(r)?.();
					}
					a = t[0];
					n.respond(...t);
				}
			});
		};
		try {
			await (i ? withCronManagementGrant(i, r, e, run) : run());
		} catch (t) {
			if (!(t instanceof TypeError)) throw t;
			respondInvalidCronParams(n.respond, e, t.message);
		} finally {
			if (i) n.context.logGateway.info("cron: admin management", {
				method: e,
				runId: r.operationalRunInstance.runId,
				instanceId: r.operationalRunInstance.instanceId,
				ok: a
			});
		}
	};
	const respondError = (e, n) => {
		if (!(e instanceof CronStoreSelectionRequiredError)) {
			if (t.onReadError) {
				t.onReadError(e, n);
				return;
			}
			throw e;
		}
		assertCronReadCurrent(n);
		n.respond(false, void 0, errorShape(ErrorCodes.UNAVAILABLE, e.message, {
			retryable: false,
			details: {
				code: e.code,
				selection: e.selection
			}
		}));
	};
	const wrapped = async (e) => {
		try {
			await invoke(e);
		} catch (t) {
			respondError(t, e);
		}
	};
	if (t.prepareRead) {
		const e = t.prepareRead;
		wrapped.prepareRead = (t) => t.client?.internal?.agentRuntimeIdentity ? { run: (e) => wrapped({
			...t,
			respond: e
		}) } : e(t);
		wrapped.onReadError = respondError;
	}
	cronHandlers[e] = wrapped;
}
//#endregion
export { cronHandlers };