openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
41 lines • 69.7 kB
JavaScript
import{l as normalizeOptionalString}from"./string-coerce-CpTFcSwY.mjs";import{V as timestampMsToIsoString,o as asDateTimestampMs,z as resolveTimestampMsToIsoString}from"./number-coercion-B3CfI447.mjs";import{a as asOptionalRecord,l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{n as freezeTrustedJsonSnapshot}from"./immutable-data-CyaF4H_G.mjs";import"./utils-Dlk0IYAa.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{n as normalizeAgentId}from"./agent-id-cOfqmfln.mjs";import{r as isIncognitoSessionKey}from"./session-key-DYtwLLn1.mjs";import{N as parseAgentSessionKey,T as parseCronRunScopeSuffix,w as isSubagentSessionKey}from"./session-key-BPgKfU2m.mjs";import{n as normalizeAccountId}from"./account-id-3yqrEsRn.mjs";import{i as listAgentIds}from"./agent-roster-4XrgUgPK.mjs";import{l as resolveSessionStorePathCore}from"./paths-CcxgiC3g.mjs";import{O as tryResolveAmbientOwnerAgentId}from"./agent-scope-config-CG9CFpGX.mjs";import{t as areDiagnosticsEnabledForProcess}from"./diagnostic-events-BYBrlAdF.mjs";import{D as runWithDiagnosticTraceContext,x as getActiveDiagnosticTraceContext}from"./diagnostics-timeline-Wd4cnAkV.mjs";import{t as SessionMetadataUnavailableError}from"./session-metadata-unavailable-error-D8TzlAxW.mjs";import{Gd as CronHistoryResultSchema,ai as validateCronAddParams,ci as validateCronHistoryParams,di as validateCronRunParams,fi as validateCronRunsParams,gi as validateCronUpdateParams,hi as validateCronStatusParams,li as validateCronListParams,mi as validateCronScratchSetParams,no as validateWakeParams,oi as validateCronBindParams,pi as validateCronScratchGetParams,si as validateCronGetParams,ui as validateCronRemoveParams}from"./src-BDZMFmKa.mjs";import{t as splitTrailingAuthProfile}from"./model-ref-profile-DFGpvDZX.mjs";import{c as formatExecCommand}from"./shell-wrapper-resolution-NzL5LGuL.mjs";import{t as DEFAULT_EXEC_APPROVAL_TIMEOUT_MS}from"./exec-approvals-core-BZ6-zeZE.mjs";import{c as createAgentDatabaseAdmissionErrorShape,w as readAgentDatabaseAdmissionRefusal}from"./agent-database-admission-DiJx9iIl.mjs";import{r as bindCronSelfRemovalCommitGuard}from"./active-jobs-QNXDOaIz.mjs";import{n as cronJobUsesToolRuntime}from"./tools-allow-Ck_pMB9N.mjs";import{i as ErrorCodes}from"./missing-scope-error-CkgBgh6d.mjs";import{n as GatewayErrorDetailCodes}from"./gateway-error-details-CMG6VuUF.mjs";import{p as errorShape}from"./error-codes-CQNGhXT-.mjs";import{r as authorizeGatewaySessionCreation}from"./operator-role-policy-g-dxw0h4.mjs";import{t as isNamedOperatorRoleEnforcementEnabled}from"./operator-role-enforcement-FsaRvImR.mjs";import{l as withSessionEntryReadOnlyInWorker}from"./session-entry-read-runtime-kAgwDw0B.mjs";import{c as resolveCronSessionTargetSessionKey,i as isInvalidCronSessionTargetIdError,s as resolveCronDeliverySessionKey}from"./session-target-BE2kgjYz.mjs";import{t as captureSessionExecutionPolicy}from"./session-entry-execution-policy-35yMGa0u.mjs";import{r as resolveRequestedSessionAgentId}from"./session-request-agent-DmeXmT1P.mjs";import{a as resolveSessionStoreIdentity}from"./session-store-key-DZXBwthg.mjs";import{a as isAgentHarnessSessionKey,d as resolveAgentHarnessSessionStoreEntryError,r as AGENT_HARNESS_SESSION_KEY_RESERVED_MESSAGE}from"./agent-harness-session-key-B6S2Sx8z.mjs";import{r as requireSessionRowProjection}from"./session-row-projection-access-w2LnU_PB.mjs";import{n as captureSessionEntryCurrentRead}from"./session-entry-current-runtime-m6gNKfuk.mjs";import{r as resolveGatewaySessionStoreTargetInWorker,t as loadGatewaySessionEntryReadOnlyInWorker}from"./session-utils-store-worker-43BDHG7V.mjs";import{o as prepareProjectedSessionSharing}from"./session-sharing-read-Cm-EAfc6.mjs";import"./session-sharing-BmRcWi9h.mjs";import{i as registerSerializedJsonArray}from"./serialized-json-DvvcynCi.mjs";import{t as createPreparedReadHandler}from"./prepared-read-CdNKeONK.mjs";import{i as tryResolveCronJobEffectiveAgentId,t as CRON_AGENT_SELECTION_REQUIRED_MESSAGE}from"./agent-id-DdcCg4fI.mjs";import{n as resolveCronJobSessionBindings}from"./job-session-bindings-pmrPMRs9.mjs";import{t as CronStoreSelectionRequiredError}from"./selection-error-02GQGYJe.mjs";import{i as sanitizeExecApprovalDisplayTextWithStatus,o as sanitizeExecApprovalWarningTextWithStatus}from"./exec-approval-text-sanitize-h0o6Uj2u.mjs";import{r as resolveOperatorSessionCreation}from"./session-creation-provenance-DQXj4E5E.mjs";import{t as respondError}from"./response-BYbuAh7a.mjs";import{n as defineValidatedGatewayHandler,t as assertValidParams}from"./validation-CM41YclJ.mjs";import{_ as withCronManagementGrant,a as getCronManagementAuthority}from"./cron-creator-authority-grant-BO7a_e4B.mjs";import{n as hasExplicitCronDeliveryTarget}from"./delivery-target-validation-C-8re9js.mjs";import{a as hasCanonicalCronDeliveryMode,t as CRON_DELIVERY_REPAIR_REQUIRED_MESSAGE}from"./delivery-codec-rJfKfjDT.mjs";import{r as resolveCronDeliveryDefaultsScope}from"./delivery-defaults-V0xnKB36.mjs";import{t as parseAbsoluteTimeMs}from"./parse-Cijfw9N8.mjs";import{t as CronStreamApprovalEndedError}from"./stream-approval-outcome-q5F39TW1.mjs";import{r as resolveCronJobConfigRevision,t as CronJobConfigRevisionConflictError}from"./config-revision-CgbOgamA.mjs";import{c as cronUpdateRequiresStreamExecAuthority,i as cronCreateRequiresStreamExecAuthority,n as CronStreamExecApprovalRequiredError,o as cronStreamExecApprovalBinding,r as CronStreamPolicyDeniedError}from"./stream-exec-authority-UA5ezVpo.mjs";import{n as readPluginCommandCreation}from"./plugin-command-creation-CqlPrizm.mjs";import{n as captureCronStreamSandboxTarget}from"./stream-context-DVFPnLA8.mjs";import{t as CRON_JOB_SCRATCH_MAX_BYTES}from"./scratch-contract-Bpgs8Aix.mjs";import{t as createStageTimingTracker}from"./stage-timing-BvqDmA-f.mjs";import"./system-run-command-CqhsXGju.mjs";import{u as resolveCronOperatorExecutionRevision}from"./jobs-tool-policy-Dbd5Denq.mjs";import{c as readCronRunHistoryRecords,o as readCronRunHistoryBinding,s as readCronRunHistoryCandidates}from"./read-only-CWdlWw2g.mjs";import{t as readSessionHistoryPageInWorker}from"./session-history-worker-runtime-BMT2ekk0.mjs";import{t as toPublicCronJob}from"./public-job-D_Fy22Cg.mjs";import{t as cronStoreKey}from"./key-DRAshdaF.mjs";import{n as resolveCronBindParent}from"./bind-parent-DxTJHr_s.mjs";import{t as resolveCronDeliveryPlan}from"./delivery-plan-BGmM1emp.mjs";import{i as selectCronRunHistoryPage,r as projectCronRunHistoryPage,t as isInvalidCronRunJobIdError}from"./run-history-BNGeXwOG.mjs";import{t as assertActiveAgentRuntimeAuthority}from"./agent-runtime-authority-Ciwflyog.mjs";import{i as cronScratchReadView,r as cronJobReadView,t as cronAddResultReadView}from"./job-read-view-BpigsXW1.mjs";import{i as resolveDeliveryTarget,n as prepareCronDeliveryTargetContexts,r as requiresExternalCronDelivery,t as prepareCronDeliverySourceGenerations}from"./delivery-target-DxjHglp1.mjs";import{a as isHumanCronJobOwner,c as prepareHumanCronTargetAccess,n as assertHumanCronJobAccess,o as isHumanCronMutation,r as canHumanManageCronJob,s as prepareCronOwnerChange,t as assertHumanCronExecutionAccess}from"./cron-human-owner-BCjtdhv6.mjs";import{t as SLOW_GATEWAY_REQUEST_MS}from"./slow-request-diagnostics--NChrVUx.mjs";import{r as retainCronControlSource}from"./cron-operator-source-C3ffervl.mjs";import{t as bindApprovalRequesterMetadata}from"./approval-shared-D5K52j8A.mjs";import{t as handlePendingApprovalRequestWithDelivery}from"./approval-request-delivery-D7M7U3li.mjs";import{n as assertValidCronCreateDelivery}from"./delivery-channel-validation-MizoyoUd.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-Cj4two6f.mjs";import{a as captureCronUpdatedInferenceBinding,c as normalizeCronUpdateRequest,i as captureCronPromptInference,l as requiresExplicitAgentRuntimeToolsAllow,n as assertValidCronUpdatePatch,o as cronRunQueuesBehindCaller,r as captureCronCreatorSession,s as normalizeCronAddRequest,t as assertCronDoesNotTargetAgentHarness}from"./cron-input-validation-B4PgrqQW.mjs";import{t as getGatewayProcessInstanceId}from"./process-instance-DHZ1eZ7y.mjs";import{randomUUID}from"node:crypto";import{performance}from"node:perf_hooks";import{isDeepStrictEqual}from"node:util";import{Value}from"typebox/value";
//!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,resolveCronDeliveryDefaultsScope(e.cfg.cron,e.job,t));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,r){if(t.preview)return t.preview;const{plan:i,requestedChannel:a,agentId:o,sessionTarget:s,deliverySessionKey:c,sourceConversation:l}=t;let u;try{if(n&&!n.ok)throw n.error;u=await resolveDeliveryTarget(e,o,{...i,sessionTarget:s,sourceConversation:l,sessionKey:c},{dryRun:true,sourceGeneration:r,...n?{sessionContext:n.value}:{}})}catch(e){if(!(e instanceof SessionMetadataUnavailableError))throw e;return{label:`${i.mode} -> ${formatTarget(a,i.to??null)}`,detail:`delivery preview unavailable: ${formatErrorMessage(e)}`}}if(!u.ok){if((s===`current`||l!==void 0)&&i.mode===`announce`&&!u.sourceConversationUnavailable&&!requiresExternalCronDelivery(i,u))return{label:`announce -> ${s===`current`?`current session`:`creating conversation`}`,detail:`commits to this conversation (no external channel route)`};const e=i.mode===`none`?`message tool target unresolved: ${u.error.message}`:`${i.target===`owner`?`owner has no route: `:a===`last`?`last -> no route, will be blocked: `:``}${u.error.message}`;return{label:`${i.mode} -> ${formatTarget(a,i.to??null)}`,detail:i.mode===`none`?e:`${e} Configure a channel and delivery target, or use delivery:{mode:"none"} for no automatic delivery.`,...i.mode!==`none`?{failed:true}:{}}}return{label:`${i.mode} -> ${formatTarget(u.channel,u.to)}`,detail:i.mode===`announce`?`commits to the destination conversation; sends one external notification`:i.target===`owner`?`resolved from configured owner`:a!==`last`?`explicit`:c?`resolved from last, session ${c}`:`resolved from last, main session`}}async function resolveCronDeliveryPreview(e){const{failed:t,...n}=await resolvePreparedCronDeliveryPreview(e.cfg,prepareCronDeliveryPreview(e));return n}async function resolveCronDeliveryFailurePreview(e){const{failed:t,...n}=await resolvePreparedCronDeliveryPreview(e.cfg,prepareCronDeliveryPreview(e));return t?n:void 0}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=t.flatMap((e,t)=>!e.preview&&e.sourceConversation&&!hasExplicitCronDeliveryTarget(e.plan)&&i.get(t)?.ok?[{index:t,agentId:e.agentId,sourceConversation:e.sourceConversation}]:[]);const o=await prepareCronDeliverySourceGenerations(e.cfg,a);const s=new Map(a.map((e,t)=>[e.index,o[t]]));try{const n=await Promise.allSettled(e.jobs.map(async(n,r)=>{const a=i.get(r);const{failed:o,...c}=await resolvePreparedCronDeliveryPreview(e.cfg,t[r],a,s.get(r));return[n.id,c]}));return Object.fromEntries(n.map(e=>{if(e.status===`rejected`)throw e.reason;return e.value}))}finally{for(const e of o)if(e.ok)e.value.release()}}
//!src/cron/validate-timestamp.ts
const ONE_MINUTE_MS=6e4;const TEN_YEARS_MS=315576e6;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}}
//!src/gateway/server-methods/cron-creator-session.ts
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}}
//!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`)}
//!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}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))}
//!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`)}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`]);function cronUpdateNarrowsTrustedJob(e,t,n){return e.scheduledToolPolicy?.mode===`trusted`&&n!==void 0&&!n.manageAll&&Object.keys(t).some(e=>!TRUSTED_LIFECYCLE_PATCH_KEYS.has(e))}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||isHumanCronMutation(e)&&!canHumanManageCronJob(o,p)||r.checkVisibility&&!(e===`cron.get`&&isHumanCronJobOwner(o,p))&&!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})})}
//!src/gateway/server-methods/cron-stream-approval.ts
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-BXA1qDyt.mjs`);return await t({sandbox:e.sandboxContext,target:u})})():await(await import(`./cron-stream-execution-binding-DlGjagIm.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();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,revalidateExecution:f.revalidate,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}}
//!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,hasCurrentClientAuthority:o},p,e!==void 0);await assertCronDoesNotTargetAgentHarness(f,p);await assertValidCronCreateDelivery(p,{...f,createdActor:y.createdActor},n.cron.getDefaultAgentId())}catch(e){y?.disposeOperatorSource?.();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,createdActor:y.createdActor}});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,...f.schedule.kind===`stream`&&!e&&y?.operatorSource?.snapshot.openclawIdPrincipal?{streamOperatorSource:y.operatorSource.snapshot}:{},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.disposeOperatorSource?.();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}),...y?.operatorSourceUnavailable&&!C.operatorSource?{warning:`This automation cannot retain the initiating operator grant. Protected operator actions require an interactive turn; its ingress owner must support principal recovery to run them unattended.`}:{}},void 0)};
//!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}}))}
//!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.`;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}}}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}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,hasCurrentClientAuthority:s},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}finally{g.disposeOperatorSource?.()}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)});
//!src/gateway/server-methods/cron-history.ts
const MAX_CRON_HISTORY_BYTES=4194304;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}const fail=()=>respondError(n,ErrorCodes.UNAVAILABLE,`The chat for this run is unavailable. Refresh the run and try again.`);const a=createCronSessionVisibility(i,r);const assertAllowed=(n,o)=>{assertCronReadCurrent(e);const s=readCronCallerScope(i);const c=a.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,o))throw new Error(`Chat for this run not found`)};try{await r.cron.readJob(t.id);const i=r.cron.getStoreKey?.()??cronStoreKey(r.cronStorePath);await a.prepare();const select=()=>readCronRunHistoryBinding(i,t.id,{runId:t.runId,runAtMs:t.runAtMs});const o=await select();if(!o){fail();return}const{sessionKey:s,sessionId:c,binding:l}=o;const u=parseAgentSessionKey(s)?.agentId??o.agentId;let d=0;if(t.cursor){const e=JSON.parse(Buffer.from(t.cursor,`base64url`).toString(`utf8`));if(!Array.isArray(e)||e.length!==2||e[0]!==l||!Number.isSafeInteger(e[1])||e[1]<0)throw new Error(`Invalid cron history cursor`);d=e[1]}const f={agentId:u,sessionId:c,storePath:resolveSessionStorePathCore(r.getRuntimeConfig().session?.store,{agentId:u})};const assertCurrent=e=>{if((r.cron.getStoreKey?.()??cronStoreKey(r.cronStorePath))!==i||resolveSessionStorePathCore(r.getRuntimeConfig().session?.store,{agentId:u})!==f.storePath)throw new Error(`Cron history store changed`);assertAllowed(e,u)};const p=await readSessionHistoryPageInWorker({kind:`transcript-binding`,params:{target:f}},e.signal);const{baseSessionKey:m}=parseCronRunScopeSuffix(s);if(!p||p.sessionKey!==s&&p.sessionKey!==m){fail();return}const{handleChatHistoryRequest:h}=await import(`./chat-history-handler-ByjpX9OR.mjs`);await h({...e,method:`chat.history`,retainedTranscript:{sessionId:c,verifyRetainedState:async()=>{await r.cron.readJob(t.id);return(await select())?.binding===l}},params:{sessionKey:p.sessionKey,...u?{agentId:u}:{},limit:t.limit??100,offset:d,maxBytes:4177920},respond:(e,t)=>{if(!e){fail();return}const r=asOptionalRecord(t);const i={messages:r?.messages,...r?.activity?{activity:r.activity}:{},...r?.hasMore===true&&typeof r.nextOffset===`number`?{nextCursor:Buffer.from(JSON.stringify([l,r.nextOffset])).toString(`base64url`)}:{}};if(!Value.Check(CronHistoryResultSchema,i)||Buffer.byteLength(JSON.stringify(i))>MAX_CRON_HISTORY_BYTES)throw new Error(`Invalid run chat history page`);assertCurrent(p.sessionKey);n(true,i)}})}catch{fail()}};
//!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{}}}}
//!src/gateway/server-methods/cron-list-projection.ts
const projections=/* @__PURE__ */ new WeakMap;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,...e.cyberAccessProgram!==void 0?{cyberAccessProgram:e.cyberAccessProgram}:{},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,admissionDeferred:e.state.admissionDeferred,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}
//!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)&&(isHumanCronJobOwner(i,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)}});
//!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}}
//!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);const o=readCronCallerScope(i);if(!s||o?.currentJobId!==s)await l.prepare();const resolvePageOptions=(o=readCronCallerScope(i))=>{const u=s&&o?.currentJobId===s?void 0:l.resolve();const d=r.cron.getDefaultAgentId();if(c===`all`){if(o)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,d).filter(e=>cronJobIsVisible(e,u,d));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:u?e=>i.has(e.jobId)&&(!e.sessionKey||u(e.sessionKey,a.agentId)):void 0}}const f=r.cron.getJob(s);const p=f&&filterCronRunLogJobsByAgent([f],a.agentId,d).length>0&&cronJobMatchesCallerScope({job:f,callerScope:o,defaultAgentId:d,allowCurrentJob:true})&&cronJobIsVisible(f,u,d)?f:void 0;if((o||a.agentId||u)&&!p){respondCronJobNotFound(n,s);return}return{storeKey:t,jobId:s,...cronRunLogPageFilters(a),jobNameById:p&&typeof p.name===`string`?{[s]:p.name}:void 0,entryFilter:u?e=>!e.sessionKey||u(e.sessionKey,p?.agentId):void 0}};const u=resolvePageOptions(o);if(!u)return;const d=await readCronRunHistoryCandidates(t,c===`all`?void 0:s,a.query,a.query?u.jobNameById:void 0);const{records:f}=d;if(c!==`all`&&!r.cron.getJob(s)&&projectCronRunHistoryPage(f,{storeKey:t,jobId:s,limit:1}).total===0){assertCurrent(t);respondCronJobNotFound(n,s);return}const p=d.queryMatches?new Set(d.queryMatches):void 0;const m=selectCronRunHistoryPage(f,{...u,queryMatchedTaskIds:p});const h=await readCronRunHistoryRecords(t,m.records.map(e=>e.id),a.view);assertCurrent(t);const g=resolvePageOptions();if(!g)return;const _=new Map(h.map(e=>[e.id,e]));const v=selectCronRunHistoryPage(f.map(e=>_.get(e.id)??e),{...g,queryMatchedTaskIds:p});const y=new Set(v.records.map(e=>e.id));const b=projectCronRunHistoryPage(h.filter(e=>y.has(e.id)),{...g,offset:0,query:void 0,runId:void 0}).entries;n(true,{...v.page,entries:b},void 0)}catch(e){if(!isInvalidCronRunJobIdError(e))throw e;respondInvalidCronParams(n,`cron.runs`,`invalid id`)}};
//!src/gateway/server-methods/cron-run.ts
const cronRunHandler=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)});
//!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})};
//!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(isNamedOperatorRoleEnforcementEnabled(f)){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)};
//!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}if(!canHumanManageCronJob(r,m)){respondCronJobNotFound(t,d);return}const h=m.payload.kind===`systemEvent`&&f.payload?.kind===`agentTurn`&&typeof f.payload.model===`string`&&Object.keys(f).length===1&&Object.keys(f.payload).length===2&&Boolean(m.inferenceBinding||splitTrailingAuthProfile(f.payload.model).profile);const g=m.payload.kind===`systemEvent`&&f.payload?.kind===`agentTurn`&&!h&&!m.inferenceBinding&&!m.runtimeAuthority&&!m.runtimeAuthorityRecoveryRequired&&!m.ownerTransferPending;const _=h?{}:f;const v=l.expectedConfigRevision??(h||g?resolveCronJobConfigRevision(m):void 0);let y;try{y=await prepareCronOwnerChange(r,m,f)}catch(e){respondInvalidCronParams(t,`cron.update`,formatErrorMessage(e));return}const b=u?.manageAll&&(!u.sessionKey||m.owner?.sessionKey!==u.sessionKey||normalizeAccountId(m.owner?.accountId)!==u.accountId)?void 0:u&&{...u,manageAll:void 0};let x;let S;let C;let w;let T;let E;const D=cronUpdateRequiresStreamExecAuthority(f,m);let O;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 k=f.payload!==void 0||Object.hasOwn(f,`trigger`);const A=cronUpdateNarrowsTrustedJob(m,f,u);let j;let M;const validateUpdate=async e=>{assertHumanCronJobAccess(r,e);assertHumanCronExecutionAccess(r,e,f);y?.();assertCronModelJobAllowed(r,p,e,f);const t=await assertValidCronUpdatePatch({cfg:p,defaultAgentId:n.cron.getDefaultAgentId(),currentJob:e,patch:_});M?.release();M=void 0;M=await prepareHumanCronTargetAccess(r,()=>n.getRuntimeConfig(),e,t,n.cron.getDefaultAgentId());if(u?.manageAll&&b&&f.payload?.toolsAllow?.length&&(!x&&e.runtimeAuthority!==void 0||e.owner?.sessionKey!==b.sessionKey||!cronJobMatchesCallerScope({job:e,callerScope:b})||!cronCreateMatchesCallerScope({job:t,callerScope:b})))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)!==A)throw new TypeError(`This automation changed while the update was pending. Read it again and retry.`);if(A)assertTrustedJobNarrowingOwner(e,u);const i=k?resolveCronScopedToolEditRefusal({job:e,nextJob:t,patch:f,callerScope:u}):void 0;if(i)throw new TypeError(i);return t};try{E=resolveCronStreamExecPolicy(r,D,n);x=resolveCronCreatorAuthorityCapture(b);const e=x?.captureRuntimeAuthority();x&&={...x,captureRuntimeAuthority:()=>e};const t=await validateUpdate(m);const a=resolveCronOperatorExecutionRevision(t);const s=m.operatorSource;const c=Boolean(r?.internal?.openclawIdPrincipal||s?.source.kind===`gateway`||s?.source.snapshot.openclawIdPrincipal||m.streamOperatorSource);if(b||!s&&f.enabled===true&&r?.internal?.authenticatedControlUi===true||c&&(D||f.enabled===true||s?.executionRevision!==a||h)){T=a;C=await captureCronCreatorSession(t,b,{client:r,context:n,signal:i,hasCurrentClientAuthority:o},p,true);w=C.operatorSource?.snapshot;C=retainCronControlSource({job:m,patch:f,capture:C,context:n})}if(h&&(e||t.runtimeAuthority||t.runtimeAuthorityRecoveryRequired))throw new TypeError(`This automation’s runtime owns its account; a host account cannot replace it.`);if(!e){const e={client:r,context:n,signal:i};S=g?await captureCronPromptInference(t,p,e,{editingScope:b}):await captureCronUpdatedInferenceBinding(t,f,p,e)}}catch(e){C?.disposeOperatorSource?.();M?.release();respondInvalidCronParams(t,`cron.update`,formatErrorMessage(e));return}const N=resolveCronMutationCommitGuard(r,n,{callerScope:u,jobId:d},{sessionMutationCommitGuard:()=>{a?.();y?.();M?.assertCurrent();x?.assertCurrent();S?.assertInferenceSelectionCurrent();C?.assertOperatorSourceCurrent?.()},hasCurrentClientAuthority:o,modelJobPolicy:{config:p,jobId:d,patch:f}});const P={...C?.operatorSource?{operatorSource:C.operatorSource,operatorSourceExecutionRevision:T}:{},...k&&!h||A?{scheduledToolPolicy:u?.manageAll&&!x?null:resolveCronScheduledToolPolicyForCaller(u),toolsAllowExecTarget:u?.toolsAllowExecTarget}:{},...S?.inferenceBinding!==void 0?{inferenceBinding:S.inferenceBinding}:{},commitGuard:N,...x?{captureRuntimeAuthority:x.captureRuntimeAuthority}:{}};let F;try{if(D&&!m.streamSandbox&&!E?.sandboxContext&&(m.streamOperatorSource||m.operatorSource?.source.snapshot.openclawIdPrincipal||w?.openclawIdPrincipal)){if(!w)throw new TypeError(`Reauthorize this stream from a current authenticated Gateway operator.`);P.streamOperatorSource=w}if(m.streamSandbox&&E&&!E.sandboxContext){assertActiveAgentRuntimeAuthority(r,n);throw new TypeError(`Change this sandbox stream from its original sandbox session.`)}if(E){const e=await prepareCronCreatorSession({context:n,client:r,callerScope:u,sessionMutationCommitGuard:a,hasCurrentClientAuthority:o,retainExecutionPolicy:true});if(!P)throw new TypeError(`A stream change requires its current creator authority.`);if(E.sandboxContext){if(!e.session)throw new TypeError(`A sandbox stream requires its current creator session.`);const t=captureCronStreamSandboxTarget({sandbox:E.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.`)}P.streamSandbox=t}P.sessionEntryCurrent=e.sessionEntryCurrent;O=e.session?.entry.sessionId;P.commitGuard=()=>{N?.();e.assertCurrent();E?.assertCurrentSource?.()}}F=await withCronStreamExecApproval({context:n,client:r,creatorSessionId:O,sandboxContext:E?.sandboxContext,assertCurrent:()=>P?.commitGuard?.(),onApprovalCommitted:e=>E?.onApprovalCommitted?.(e),mutate:e=>{if(P&&e)P.streamExecApproval=e;return n.cron.updateWithPrecondition(d,_,async e=>{if(!cronJobMatchesCallerScope({job:e,callerScope:u,defaultAgentId:n.cron.getDefaultAgentId()}))throw new Error(`unknown cron job id: ${d}`);if(v!==void 0){const t=resolveCronJobConfigRevision(e);if(t!==v)throw new CronJobConfigRevisionConflictError(v,t)}const t=cronUpdateRequiresStreamExecAuthority(f,e);if(t&&!E)E=resolveCronStreamExecPolicy(r,true,n);const i=t?E:void 0;const a=await validateUpdate(e);j=await resolveCronDeliveryFailurePreview({cfg:p,defaultAgentId:n.cron.getDefaultAgentId(),job:a});if(P){P.execPolicy=i;P.toolsAllowProvenance=resolveCronRequesterProvenanceForJob(e,u)}},P)}})}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{C?.disposeOperatorSource?.();M?.release();S?.disposeInferenceAuthorization()}n.logGateway.info(`cron: job updated`,{jobId:d});t(true,{...cronJobReadView(F),...j?{deliveryPreview:j}:{}},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":cronRunHandler,"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}export{cronHandlers};