openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
328 lines (327 loc) • 11.2 kB
JavaScript
import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs";
import { a as sessionChangeScopeAffectsStoredRows, o as sessionChanges } from "./session-row-changes-BA4BqVwF.mjs";
import { T as selectLiveRuntimeConfig } from "./runtime-snapshot-WbwbY5b7.mjs";
import { t as GATEWAY_OWNER_PROFILE_ID } from "./user-profile-constants-Bj3FwpfE.mjs";
import { s as resolveCronScheduledToolPolicy } from "./scheduled-tool-policy-C_pucbBp.mjs";
import { t as captureResidentUserProfileAccess } from "./user-profile-list-D7DDbqt5.mjs";
import { d as resolveCreatorSandbox } from "./operator-role-policy-DhcqVpmG.mjs";
import { r as resolveAgentMainSessionKey } from "./main-session-BNL3-mRV.mjs";
import { d as readSessionEntryInWorker } from "./session-entry-read-runtime-1Fp1sybj.mjs";
import { i as resolveSandboxConfigForAgent } from "./config-WbZbWrF1.mjs";
import { n as resolveScheduledToolPolicyContext } from "./scheduled-tool-policy-CXHVgGTq.mjs";
import { t as decodeGatewayOperatorRecoverySource } from "./operator-run-recovery-source.codec-qx3kHk7N.mjs";
import { r as prepareCommandOwnerAuthority } from "./command-auth-CC1Z19Eh.mjs";
import { s as resolveCronSessionTargetSessionKey } from "./session-target-C-4MLah6.mjs";
import { n as classifyScheduledParent, r as resolveScheduledPrincipal, t as buildScheduledExecutionContext } from "./execution-context-CSnw8-kc.mjs";
import { r as prepareSessionGenerationFacts } from "./session-delivery-generation-CUS9yuZM.mjs";
import { r as resolveIngressWorkspaceOverrideForSessionRun } from "./spawned-context-wZ6NGSBl.mjs";
import { t as bindScheduledExecutionContext } from "./execution-context-registry-DYmFlODi.mjs";
import { n as failedScheduledExecution, r as unadmittedScheduledOccurrence } from "./scheduled-occurrence-DAcfrhfO.mjs";
import { access } from "node:fs/promises";
//#region src/cron/parent-reset-watch.ts
/**
* Watches committed session-row changes that can affect the parent row and
* re-runs the parent's live check on each one. The first failure aborts the
* signal with that failure, so work outside OpenClaw's tool boundary (a CLI
* process and its native tools) stops with the parent. Stopping the watch
* releases the subscription without aborting.
*/
function watchParentReset(e) {
const t = new AbortController();
let n;
const stop = () => {
n?.();
n = void 0;
};
n = sessionChanges.subscribeFacts((n) => {
if (!("all" in n ? sessionChangeScopeAffectsStoredRows(n) : n.sessionKey === e.parentSessionKey)) return;
try {
e.assertCurrent();
} catch (e) {
stop();
t.abort(e);
}
});
return {
signal: t.signal,
stop
};
}
//#endregion
//#region src/cron/execution-context-admission.ts
/**
* Admits one scheduled occurrence: reads the parent row once, runs the
* requester's owner check and holds the parent generation for the whole
* occurrence. Each admitted run then mints its context from those facts. A
* failure here never fails the run.
*/
function ingressFor(e) {
if (e === "gateway.hooks.plugin") return "plugin-hook";
return e === "gateway.hooks.agent" ? "webhook" : "channel-join";
}
const NOT_OWNER = { owner: false };
function ownerCheck(e, t) {
if (!t(e)) return NOT_OWNER;
return {
owner: true,
isOwner: t,
assertCurrent: () => {
if (!t(selectLiveRuntimeConfig(e))) throw new Error("The requester that authorized this automation is no longer an owner.");
}
};
}
/**
* Owner check for requesters the occurrence can verify; operator sources are checked per run.
* Scheduler turns about a job (its repair or notices) take the same check.
*/
async function checkRequesterOwner(e, t) {
switch (t.kind) {
case "channel": {
const { channel: n, accountId: r, senderId: i } = t.requester;
const a = await prepareCommandOwnerAuthority(e, {
channel: n,
accountId: r,
senderId: i
});
return ownerCheck(e, (e) => a.source !== void 0 && a.isCurrent(e));
}
case "profile": {
let n;
try {
n = captureResidentUserProfileAccess(t.profileId);
} catch {
return NOT_OWNER;
}
return ownerCheck(e, (e) => {
try {
n.assertCurrent();
} catch {
return false;
}
return !e.gateway?.roles || t.profileId === "gateway-owner";
});
}
case "unknown": return NOT_OWNER;
}
return NOT_OWNER;
}
/** The stored parent key, with the builder's principal precedence. */
function scheduledParentKeyOf(e) {
if (e.operatorSource) try {
return decodeGatewayOperatorRecoverySource(e.operatorSource.source).sessionKey;
} catch {
return;
}
return e.sourceConversation?.sessionKey;
}
async function readParent(e, t) {
const n = await readSessionEntryInWorker({
sessionKey: e,
storePath: t,
readConsistency: "latest",
projection: "list"
});
const r = n?.worktree ? n.spawnedCwd : void 0;
return {
entry: n,
row: parentRowFactsFromEntry(n, r ? await access(r).then(() => true, () => false) : false)
};
}
/** Builder facts for a parent session row; shared with the development replay. */
function parentRowFactsFromEntry(e, t) {
if (!e?.sessionId) return { missing: true };
const n = e.worktree ? e.spawnedCwd : void 0;
const r = resolveIngressWorkspaceOverrideForSessionRun({
spawnedBy: e.spawnedBy,
workspaceDir: e.spawnedWorkspaceDir,
cwd: e.spawnedCwd
});
return {
sessionId: e.sessionId,
...e.lifecycleRevision ? { lifecycleRevision: e.lifecycleRevision } : {},
archived: typeof e.archivedAt === "number",
...r ? { workspaceDir: r } : {},
...e.spawnedCwd ? { cwd: e.spawnedCwd } : {},
...n ? { worktree: {
path: n,
exists: t
} } : {},
sandboxRequired: e.sandbox === "required"
};
}
/** Admission facts from already-read inputs; shared with the development replay. */
function assembleScheduledAdmissionFacts(e, t, n) {
return {
trigger: e.trigger,
...e.trigger === "event" ? { ingress: ingressFor(e.ingressBoundary) } : {},
occurrence: {
runId: e.runId,
executionRevision: e.job.operatorSource?.executionRevision ?? ""
},
agentId: e.agentId,
runSessionKey: e.runSessionKey,
agentMainSessionKey: resolveAgentMainSessionKey({
cfg: e.cfg,
agentId: e.agentId
}),
agentSandboxMode: resolveSandboxConfigForAgent(e.cfg, e.agentId).mode,
...(e.creatorRoleSandbox ?? resolveCreatorSandbox(e.cfg, { actor: e.job.createdActor })) === "required" ? { creatorRoleSandbox: "required" } : {},
...e.toolsAllow ? { resolvedToolsAllow: e.toolsAllow } : {},
...t ? { parentRow: t } : {},
...n !== void 0 ? { requesterCheck: { owner: n } } : {}
};
}
/**
* Admits one occurrence. The single call site for stored jobs is the cron
* service's `executeJobCore`; hook and join-intro turns admit with
* `trigger: "event"`. Errors become `fail` results for every run it mints.
*/
async function admitScheduledOccurrence(e) {
const { job: t } = e;
const n = resolveScheduledPrincipal(t, {
trigger: e.trigger,
...e.trigger === "event" ? { ingress: ingressFor(e.ingressBoundary) } : {},
agentId: e.agentId
});
let r;
let i;
let a;
let o;
let s;
let c;
try {
if (!("error" in n) && n.kind === "parent") {
const l = resolveSessionStorePathCore(e.cfg.session?.store, { agentId: e.agentId });
const u = await readParent(n.parent.sessionKey, l);
r = u.row;
if (n.requester.kind !== "operator-source") i = await checkRequesterOwner(e.cfg, n.requester);
const d = classifyScheduledParent(r);
const f = n.parent.sessionKey;
if (typeof d === "string") o = {
reason: d,
parentSessionKey: f
};
else if (d.worktree && !d.worktree.exists) o = {
reason: "worktree-missing",
parentSessionKey: f,
worktreePath: d.worktree.path
};
const p = t.sessionTarget !== "main" && !resolveCronSessionTargetSessionKey(t.sessionTarget);
if (typeof d !== "string" && !o && p && u.entry) {
const e = u.entry;
s = {
...Boolean(typeof d !== "string" && (d.workspaceDir || d.cwd || d.worktree)) ? { binding: {
sessionKey: f,
entry: e
} } : {},
...e.sandbox === "required" ? { sandbox: "required" } : {},
assertCurrent: () => {
if (!a) throw new Error("Scheduled occurrence has settled");
a.assertCurrent();
}
};
}
if (typeof d !== "string") a = await prepareSessionGenerationFacts({
agentId: e.agentId,
storePath: l,
sessionKey: f,
sessionId: d.sessionId,
lifecycleRevision: d.lifecycleRevision ?? null
});
if (s?.binding && a) {
c = watchParentReset({
parentSessionKey: n.parent.sessionKey,
assertCurrent: s.assertCurrent
});
s = {
...s,
signal: c.signal
};
}
}
} catch (e) {
c?.stop();
a?.release();
return unadmittedScheduledOccurrence(e instanceof Error ? e.message : String(e));
}
const l = !("error" in n) && n.kind === "parent" && n.requester.kind === "operator-source";
return {
...o ? { pause: o } : {},
...s ? { childParent: s } : {},
mint(n) {
let o;
try {
const a = assembleScheduledAdmissionFacts({
cfg: n.cfg,
job: t,
trigger: e.trigger,
ingressBoundary: e.ingressBoundary,
runId: n.runId,
agentId: n.agentId,
runSessionKey: n.runSessionKey,
toolsAllow: n.toolsAllow
}, r, l ? n.operatorAuthority !== void 0 : i?.isOwner?.(selectLiveRuntimeConfig(n.cfg)) ?? i?.owner);
o = buildScheduledExecutionContext(t, a);
} catch (e) {
return failedScheduledExecution(e instanceof Error ? e.message : String(e));
}
const s = a;
const c = n.operatorAuthority;
const u = o.status !== "ready" || !o.facts.authority.owner || o.facts.authority.basis === "legacy" || o.facts.authority.basis === "trusted-policy" ? void 0 : l ? c && (() => c.assertCurrent()) : i?.assertCurrent;
const d = o.status === "ready" && o.facts.principal.kind === "parent" && s ? () => s.assertCurrent() : () => {};
let f;
let unbind = () => {};
return {
result: o,
bind(e, t) {
if (o.status !== "ready") return;
let n = false;
f = {
...o.facts,
assertCurrent: () => {
if (n) throw new Error("Scheduled occurrence has settled");
t();
d();
},
...u ? { assertOwnerCurrent: () => {
if (n) throw new Error("Scheduled occurrence has settled");
u();
} } : {}
};
const r = bindScheduledExecutionContext(e, f);
unbind = () => {
n = true;
r();
};
},
current: () => f,
release() {
unbind();
unbind = () => {};
f = void 0;
}
};
},
release() {
c?.stop();
c = void 0;
a?.release();
a = void 0;
}
};
}
/** The prompt executor's scheduled tool policy, from the job's stored authority fields. */
function resolveCronJobToolPolicyContext(e, t) {
return resolveScheduledToolPolicyContext({
toolsAllow: t,
scheduledToolPolicy: resolveCronScheduledToolPolicy({
toolsAllow: t,
scheduledToolPolicy: e.scheduledToolPolicy,
owner: e.owner
}),
callerOrigin: e.toolsAllowProvenance?.callerOrigin,
execTarget: e.toolsAllowExecTarget
});
}
//#endregion
export { resolveCronJobToolPolicyContext as a, parentRowFactsFromEntry as i, assembleScheduledAdmissionFacts as n, scheduledParentKeyOf as o, checkRequesterOwner as r, admitScheduledOccurrence as t };