openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
498 lines (497 loc) • 18.5 kB
JavaScript
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs";
import { x as isCronSessionKey } from "./session-key-CqAyZeVk.mjs";
import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs";
import { O as tryResolveAmbientOwnerAgentId } from "./agent-scope-config-DmXgFGKP.mjs";
import { n as executeExistingOpenClawStateRead } from "./openclaw-state-db-readonly-B6YHb1oF.mjs";
import { t as GATEWAY_OWNER_PROFILE_ID } from "./user-profile-constants-Bj3FwpfE.mjs";
import { y as resolveModelRefFromString } from "./model-selection-shared-9Kz63Hhm.mjs";
import { n as resolveDefaultModelForAgent } from "./model-selection-config-Bvf5WqHo.mjs";
import { r as resolveCronRunToolsAllow } from "./tools-allow-CYmLDCc7.mjs";
import { t as AUTOMATIONS_TOOL_NAME } from "./automations-tool-name-DNRDs0aJ.mjs";
import { a as isRuntimeToolAllowed } from "./tool-policy-match-DzwVnbV4.mjs";
import { h as resolveOperatorRolePolicyForAssignment } from "./operator-role-policy-DhcqVpmG.mjs";
import { r as resolveAgentMainSessionKey } from "./main-session-BNL3-mRV.mjs";
import { i as readSessionEntryReadOnlyInWorker } from "./session-entry-read-runtime-1Fp1sybj.mjs";
import { t as isCliProvider } from "./model-selection-cli-CkH04Wst.mjs";
import { c as resolveCliRuntimeExecutionProvider } from "./model-runtime-aliases-DZy9Ea2c.mjs";
import { t as isConfiguredCommandOwner } from "./command-auth-CC1Z19Eh.mjs";
import { i as tryResolveCronJobEffectiveAgentId } from "./agent-id-CX8HtxAT.mjs";
import { n as resolveCronRunAdmissionSource } from "./run-authority-CJXQKUzJ.mjs";
import { s as resolveCronSessionTargetSessionKey } from "./session-target-C-4MLah6.mjs";
import { i as resolveScheduledRequester, t as buildScheduledExecutionContext } from "./execution-context-CSnw8-kc.mjs";
import { p as rowToCronJob } from "./row-codec-D4aymQkb.mjs";
import { t as note } from "./note-CnLgHvug.mjs";
import { r as inspectCronJobsForDoctor } from "./store-repair-Dv1WdfLr.mjs";
import { t as countLabel } from "./doctor-state-integrity-format-XVQ-DkEv.mjs";
import { l as resolveScheduledSenderBit } from "./execution-context-registry-DYmFlODi.mjs";
import { i as parentRowFactsFromEntry, n as assembleScheduledAdmissionFacts, o as scheduledParentKeyOf } from "./execution-context-admission-Bjz8Th2Y.mjs";
import { access } from "node:fs/promises";
//#region src/cron/execution-context-projection.ts
/**
* Projects what the existing scheduled-run code decides for a stored job and
* labels where the execution context differs. Pure; shared by the development
* replay script and the fixture tests.
*/
/** The decisions the existing code makes for one occurrence. */
function projectLegacyDecisions(e, t) {
const n = resolveCronSessionTargetSessionKey(e.sessionTarget) !== void 0;
const r = n || e.sessionTarget === "main";
const i = t.resolvedToolsAllow;
const a = isRuntimeToolAllowed(AUTOMATIONS_TOOL_NAME, i);
return {
...t.trigger === "cron" ? { admissionSource: resolveCronRunAdmissionSource(e) } : {},
ownerEmbedded: r ? "session-turn" : "owner",
ownerCli: r ? "session-turn" : "non-owner",
automations: !a ? "none" : "self",
automationsCli: r ? "session-turn" : "none",
requesterYield: isCronSessionKey(t.runSessionKey) ? "refused" : "offered",
board: t.runSessionKey,
eventTarget: n ? t.runSessionKey : t.agentMainSessionKey,
memory: "run-session",
workspace: "run-session",
sandbox: t.agentSandboxMode === "all" || t.agentSandboxMode === "non-main" && t.runSessionKey !== t.agentMainSessionKey || t.creatorRoleSandbox === "required",
parentState: "ready"
};
}
/** The same decisions read from a built context. */
function projectContextDecisions(e, t) {
if (e.status === "pause") return "pause";
if (e.status === "fail") return "fail";
const { facts: n } = e;
return {
...n.authority.admissionSource ? { admissionSource: n.authority.admissionSource } : {},
...projectContextOwner(e, t),
...projectContextAutomations(e, t),
board: n.resources.boardSessionKey,
eventTarget: n.resources.eventTargetSessionKey,
memory: n.resources.memory.source === "parent" ? n.resources.memory.owner ? "parent-owner" : "parent-conversation" : "run-session",
workspace: n.resources.workspace.source,
sandbox: n.resources.sandbox.required,
parentState: t.parentState
};
}
function projectContextOwner(e, t) {
const n = resolveScheduledSenderBit(e);
if (!n) return {
ownerEmbedded: t.ownerEmbedded,
ownerCli: t.ownerCli
};
const r = n.senderIsOwner === false ? "non-owner" : "owner";
return {
ownerEmbedded: r,
ownerCli: r
};
}
function projectContextAutomations(e, t) {
const { facts: n } = e;
const r = n.toolPolicy.automations.scope === "none" ? "none" : "self";
if (n.principal.kind === "ingress") return {
automations: r,
automationsCli: t.automationsCli,
requesterYield: t.requesterYield
};
return {
automations: r,
automationsCli: r,
requesterYield: "refused"
};
}
const AUTOMATIONS_RANK = {
none: 0,
self: 1,
"self-and-parent-wake": 2
};
const INTENDED_GAINS = /* @__PURE__ */ new Set([
"memory",
"workspace",
"automations"
]);
const RETARGETS = /* @__PURE__ */ new Set(["board", "eventTarget"]);
function labelField(e, t, n) {
const r = t[e];
const i = n[e];
if (r === i) return "equal";
if (RETARGETS.has(e)) return "retarget";
if (e === "ownerEmbedded" || e === "ownerCli") {
if (i === "non-owner") return "loss";
return e === "ownerCli" && t.ownerEmbedded === i ? "gain-intended" : "gain-unexpected";
}
if (e === "sandbox") return i ? "loss" : "gain-unexpected";
if (e === "automations") return AUTOMATIONS_RANK[n.automations] > AUTOMATIONS_RANK[t.automations] ? "gain-intended" : "loss";
if (e === "automationsCli") {
if (r === "session-turn" || i === "none") return "loss";
return i === t.automations ? "gain-intended" : "gain-unexpected";
}
if (e === "requesterYield") return i === "refused" ? "loss" : "gain-unexpected";
if (e === "admissionSource") return i === "operator-schedule" ? "gain-unexpected" : "loss";
return INTENDED_GAINS.has(e) ? "gain-intended" : "gain-unexpected";
}
function labelInference(e, t) {
const { inference: n } = e.facts;
if (n.kind !== "bound") return;
const r = n.binding.runtime;
if (r) {
const { models: e } = t;
return {
label: r === t.legacy && (!e || e.legacy === e.context) ? "equal" : "retarget",
legacy: e ? `${t.legacy} ${e.legacy}` : t.legacy,
context: e ? `${r} ${e.context}` : r
};
}
return {
label: "equal",
legacy: t.legacy,
context: t.legacy
};
}
const FIELDS = [
"admissionSource",
"ownerEmbedded",
"ownerCli",
"automations",
"automationsCli",
"requesterYield",
"board",
"eventTarget",
"memory",
"workspace",
"sandbox"
];
/** Labels every decision a built context changes relative to the legacy code. */
function compareScheduledDecisions(e, t, n, r) {
const i = projectLegacyDecisions(e, t);
const a = projectContextDecisions(n, i);
if (a === "pause" || a === "fail") return {
status: a,
labels: a === "pause" ? { parentState: "pause" } : {},
changes: [],
...n.status === "pause" ? { reason: `${n.reason}: ${n.parentSessionKey}` } : n.status === "fail" ? { reason: n.error } : {}
};
const o = {};
const s = [];
for (const e of FIELDS) {
const t = labelField(e, i, a);
o[e] = t;
if (t !== "equal") s.push({
field: e,
legacy: i[e],
context: a[e],
label: t
});
}
const c = n.status === "ready" && r ? labelInference(n, r) : void 0;
if (c) {
o.inference = c.label;
if (c.label !== "equal") s.push({
field: "inference",
...c
});
}
return {
status: "ready",
labels: o,
changes: s
};
}
//#endregion
//#region src/commands/doctor/cron/execution-context-report.ts
function emptyScheduledContextReport() {
return {
losses: [],
pauses: [],
unbound: [],
runtimeOwner: [],
missingChatType: [],
failed: []
};
}
function jobRef(e) {
return {
id: e.id,
name: e.name?.trim() || e.id,
enabled: e.enabled
};
}
/**
* Adds one job's findings to the report. A job can appear in several
* categories, for example a CLI job whose parent has no chat type.
*/
function classifyScheduledJob(e, t) {
const { job: n, facts: r, result: i } = t;
const a = jobRef(n);
const o = n.payload.kind === "command";
const s = Boolean(n.trigger) || !o && n.sessionTarget !== "main";
if (i.status === "pause") {
if (!o) e.pauses.push({
job: a,
parentSessionKey: i.parentSessionKey,
cause: i.reason,
...i.worktreePath ? { worktreePath: i.worktreePath } : {}
});
return;
}
if (!s) return;
if (i.status === "fail") {
e.failed.push({
job: a,
reason: i.error
});
return;
}
const { principal: c, authority: l } = i.facts;
if (c.kind === "unbound-parent") e.unbound.push({
job: a,
parentSessionKey: c.parentSessionKey
});
const u = compareScheduledDecisions(n, r, i).changes.filter((e) => e.label === "loss");
if (u.length > 0) e.losses.push({
job: a,
fields: u,
ownerCheck: t.ownerCheck
});
if (t.cliBackend && l.owner) e.runtimeOwner.push({
job: a,
cliBackend: t.cliBackend
});
const d = t.parentChat;
if (c.kind === "parent" && d && !d.spawned && !d.chatType) e.missingChatType.push({
job: a,
parentSessionKey: c.parent.sessionKey
});
}
function label(e) {
return `${e.name} (${e.id})${e.enabled ? "" : " [disabled]"}`;
}
function describeLostField(e) {
switch (e.field) {
case "ownerEmbedded": return "owner-only tools such as sessions, portal, nodes, gateway and plugins (the creator is not currently an owner)";
case "automations": return `automations tool (${String(e.legacy)} -> ${String(e.context)})`;
case "sandbox": return "unsandboxed execution (the creating conversation requires a sandbox)";
case "admissionSource": return "operator admission";
case "automationsCli": return "unscoped automations tool on CLI backends (now limited to this automation, as on embedded runs)";
case "requesterYield": return "sessions_yield (scheduled runs cannot wait for child sessions; the run must finish its turn)";
default: return e.field;
}
}
const PAUSE_CAUSE = {
removed: "was removed",
archived: "is archived",
"worktree-missing": "has a missing worktree"
};
function section(e, t, n) {
return t.length === 0 ? [] : [
e,
...t,
...n ? [n] : []
];
}
/** Doctor's note text for the report, or null when no job changes. */
function formatScheduledContextReport(e) {
const t = [
...section(`${countLabel(e.losses.length, "automation")} will lose access at the next run:`, e.losses.map((e) => `- ${label(e.job)}: ${e.fields.map(describeLostField).join("; ")}${e.ownerCheck === "unverified" ? " (the creator's owner status is checked at each run; Doctor could not verify it)" : ""}`)),
...section(`${countLabel(e.pauses.length, "automation")} will pause at the next run because the conversation that created ${e.pauses.length === 1 ? "it" : "them"} is unavailable:`, e.pauses.map((e) => `- ${label(e.job)}: \`${e.parentSessionKey}\` ${PAUSE_CAUSE[e.cause]}${e.worktreePath ? ` (\`${e.worktreePath}\`)` : ""}`), ` Restore the conversation and run ${formatCliCommand("openclaw automations enable <id>")} after a pause, or recreate the automation from another conversation.`),
...section(`${countLabel(e.unbound.length, "automation")} ${e.unbound.length === 1 ? "is" : "are"} not bound to the conversation that created ${e.unbound.length === 1 ? "it" : "them"}:`, e.unbound.map((e) => `- ${label(e.job)}: \`${e.parentSessionKey}\` is recorded by key only`), " These keep their current behavior and do not use the conversation's board, memory or workspace. Recreate one from its conversation to bind it."),
...section(`${countLabel(e.runtimeOwner.length, "automation")} ${e.runtimeOwner.length === 1 ? "runs" : "run"} on a CLI backend, where scheduled runs now get the owner-only tools embedded runs already had:`, e.runtimeOwner.map((e) => `- ${label(e.job)}: ${e.cliBackend}`), " Earlier versions gave these scheduled CLI runs no owner-only tools; both runtimes now read the same scheduled-run authority."),
...section(`${countLabel(e.missingChatType.length, "automation")} ${e.missingChatType.length === 1 ? "has" : "have"} a creating conversation with no stored chat type, so ${e.missingChatType.length === 1 ? "its" : "their"} runs get no conversation memory:`, e.missingChatType.map((e) => `- ${label(e.job)}: \`${e.parentSessionKey}\``), " Conversations created by OpenClaw 2026.10.6 or earlier did not record a chat type. A Doctor repair for these conversations is planned; nothing is changed here."),
...section(`${countLabel(e.failed.length, "automation")} could not be evaluated:`, e.failed.map((e) => `- ${label(e.job)}: ${e.reason}`))
];
if (t.length === 0) return null;
return ["Scheduled-run access review (read-only; nothing was changed).", ...t].join("\n");
}
//#endregion
//#region src/commands/doctor/cron/execution-context-check.ts
/** One stored user profile's role facts, read from state without the resident catalog. */
async function readCreatorProfile(e, t) {
try {
let n = await readProfileRow(e, t);
if (n?.merged_into) n = await readProfileRow(e, n.merged_into);
return n ? {
assignedRole: n.role ?? null,
githubLogin: n.githubLogin ?? null
} : "missing";
} catch {
return "unreadable";
}
}
async function readProfileRow(e, t) {
return (await executeExistingOpenClawStateRead({ env: e }, {
type: "userProfiles.reconcile",
profileId: t
}))?.profile;
}
function creatorRoleSandbox(e, t, n) {
const r = t.createdActor;
if (r?.type !== "human" || !r.id) return "none";
const i = typeof n === "object" ? n : void 0;
return resolveOperatorRolePolicyForAssignment(r.id, i?.assignedRole ?? null, e, i?.githubLogin ?? null)?.sandbox === "required" ? "required" : "none";
}
/**
* The requester's current owner status, read without the Gateway. Profile and
* configured channel owners can be read from state and config; linked channel
* operators and operator snapshots need the running Gateway, so they are
* reported as unverified and treated as non-owners.
*/
function checkRequesterOwnerReadOnly(e, t, n) {
switch (t.kind) {
case "unknown": return {
owner: false,
check: "checked"
};
case "profile":
if (n === "unreadable") return {
owner: false,
check: "unverified"
};
return {
owner: typeof n === "object" && (!e.gateway?.roles || t.profileId === "gateway-owner"),
check: "checked"
};
case "channel": {
const { channel: n, accountId: r, senderId: i } = t.requester;
if (isConfiguredCommandOwner(e, {
channel: n,
accountId: r,
senderId: i
})) return {
owner: true,
check: "checked"
};
return {
owner: false,
check: Boolean(e.gateway?.roles || e.gateway?.auth?.identityScopes) ? "unverified" : "checked"
};
}
case "operator-source": return {
owner: false,
check: "unverified"
};
}
return {
owner: false,
check: "unverified"
};
}
function resolveCliBackend(e, t, n) {
if (n.payload.kind !== "agentTurn") return;
const r = {
cfg: e,
agentId: t,
allowManifestNormalization: false,
allowPluginNormalization: false
};
const i = resolveDefaultModelForAgent(r);
const a = n.payload.model ? resolveModelRefFromString({
...r,
raw: n.payload.model,
defaultProvider: i.provider
})?.ref : i;
if (!a) return;
if (isCliProvider(a.provider, e)) return a.provider;
return resolveCliRuntimeExecutionProvider({
cfg: e,
agentId: t,
provider: a.provider,
modelId: a.model
});
}
async function readParentEntry(e, t, n) {
return readSessionEntryReadOnlyInWorker({
agentId: t,
sessionKey: n,
storePath: resolveSessionStorePathCore(e.session?.store, { agentId: t }),
readConsistency: "latest"
});
}
const exists = (e) => access(e).then(() => true, () => false);
/**
* Builds one job's context the way occurrence admission does, from read-only
* inputs, and adds its findings to the report.
*/
async function reviewJob(e, t, n, r) {
const i = tryResolveCronJobEffectiveAgentId(r, tryResolveAmbientOwnerAgentId(t));
if (!i) return;
const a = r.createdActor;
const o = a?.type === "human" && a.id ? await readCreatorProfile(n, a.id) : void 0;
const s = scheduledParentKeyOf(r);
let c;
let l;
let u = {
owner: void 0,
check: "not-needed"
};
if (s) {
c = await readParentEntry(t, i, s);
const e = c?.worktree ? c.spawnedCwd : void 0;
l = parentRowFactsFromEntry(c, e ? await exists(e) : false);
u = checkRequesterOwnerReadOnly(t, resolveScheduledRequester(r), o);
}
const d = r.sessionTarget === "main" ? resolveAgentMainSessionKey({
cfg: t,
agentId: i
}) : resolveCronSessionTargetSessionKey(r.sessionTarget) ?? `agent:${i}:cron:${r.id}:run:doctor`;
const f = assembleScheduledAdmissionFacts({
cfg: t,
job: r,
trigger: "cron",
runId: "doctor",
agentId: i,
runSessionKey: d,
toolsAllow: resolveCronRunToolsAllow(r),
creatorRoleSandbox: creatorRoleSandbox(t, r, o)
}, l, u.owner);
classifyScheduledJob(e, {
job: r,
facts: f,
result: buildScheduledExecutionContext(r, f),
ownerCheck: u.check,
...c?.sessionId ? { parentChat: {
chatType: c.chatType,
spawned: c.spawnedBy !== void 0
} } : {},
...withCliBackend(resolveCliBackend(t, i, r))
});
}
function withCliBackend(e) {
return e ? { cliBackend: e } : {};
}
/** Reviews every valid stored automation; a job that cannot be read is listed, not fatal. */
async function collectScheduledContextReport(e) {
const t = e.env ?? process.env;
const n = emptyScheduledContextReport();
const r = await inspectCronJobsForDoctor({ env: t });
for (const i of r.jobs) {
const r = i.invalidReason || !i.definition ? null : rowToCronJob({
job_id: i.id,
state_json: "{}",
runtime_updated_at_ms: null,
updated_at: 0
}, i.definition);
if (!r) continue;
try {
await reviewJob(n, e.cfg, t, r);
} catch (e) {
n.failed.push({
job: {
id: r.id,
name: r.name?.trim() || r.id,
enabled: r.enabled
},
reason: formatErrorMessage(e)
});
}
}
return n;
}
/** Notes the review under Cron when any automation changes. */
async function noteScheduledContextReport(e) {
let t;
try {
t = formatScheduledContextReport(await collectScheduledContextReport(e));
} catch (e) {
t = `Scheduled-run access review could not read stored automations: ${formatErrorMessage(e)}`;
}
if (t) note(t, "Cron");
}
//#endregion
export { noteScheduledContextReport };