openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
410 lines (409 loc) • 15.5 kB
JavaScript
import { j as parseAgentSessionKey } from "./session-key-CqAyZeVk.mjs";
import { i as listAgentIds } from "./agent-roster-t1ooUdXp.mjs";
import { f as resolveAgentWorkspaceDir } from "./agent-scope-config-DmXgFGKP.mjs";
import { i as getGatewayPluginMetadataSnapshot } from "./current-plugin-metadata-state-BmYo9Q7A.mjs";
import { o as sessionChanges } from "./session-row-changes-BA4BqVwF.mjs";
import { c as onUserProfilesChanged } from "./user-profile-events-BhLFevt9.mjs";
import { s as createAdmittedRunOperatorAuthority } from "./admitted-run-context-D3Jvk_f_.mjs";
import { o as roleScopesAllow } from "./operator-scope-compat-CpFHu-FC.mjs";
import { s as resolveCronScheduledToolPolicy } from "./scheduled-tool-policy-C_pucbBp.mjs";
import { l as prepareUserProfileIdentity } from "./user-profile-list-D7DDbqt5.mjs";
import { h as resolveOperatorRolePolicyForAssignment, o as onOperatorRolePolicyChanged } from "./operator-role-policy-DhcqVpmG.mjs";
import { t as applyExecPolicyLayer } from "./exec-policy-B0KOmSWr.mjs";
import { r as projectEffectiveExecPolicy } from "./session-permission-exec-mode-vqqWNPSg.mjs";
import { r as onSessionIdentityMutation } from "./session-lifecycle-events-DWKmeEvQ.mjs";
import { $ as hasOnlySessionMutationKindActive, tt as isSessionMutationActive } from "./session-controller.lifecycle-C_Z3sybN.mjs";
import { i as authorizePreparedSessionMutation } from "./session-sharing-policy-3TAaxC-R.mjs";
import { t as prepareSessionMutationFacts } from "./session-sharing-preparation-vuYznHON.mjs";
import { i as resolveSandboxConfigForAgent, n as captureSandboxConfig } from "./config-WbZbWrF1.mjs";
import { r as resolveSandboxRuntimeStatus } from "./runtime-status-C5ZOG7YR.mjs";
import { n as resolveScheduledToolPolicyContext } from "./scheduled-tool-policy-CXHVgGTq.mjs";
import { i as resolveConversationCapabilityProfile } from "./conversation-capability-profile-Be5DqCww.mjs";
import { n as isConversationToolAllowed } from "./conversation-tool-policy-pipeline-DIjQjgsq.mjs";
import { t as createSyntheticPluginRuntimeClient } from "./server-plugin-runtime-client-DE2ydcEw.mjs";
import { t as resolveSessionSelectedModelRef } from "./session-utils-model-selection-BGYqZws_.mjs";
import { i as sourceRolePolicy } from "./operator-role-source-policy-CRYRV_Bv.mjs";
import { s as resumeGatewayOperatorAccessGrant } from "./operator-access-policy-BWvd6twL.mjs";
import { n as resolveExecConfigState, t as prepareExecDefaults } from "./exec-defaults-BaVI-sJD.mjs";
import { l as parseCronStreamSandboxTarget, r as cronStreamScheduleKey } from "./stream-schedule-BFX6oe0X.mjs";
import { n as captureCronStreamSandboxTarget } from "./stream-context-CUn0Kkey.mjs";
import { i as resolveSandboxContextForPersistentExecution } from "./context-DNnE7m_d.mjs";
import { t as cronStoreKey } from "./key-BNWVX7Bb.mjs";
import { t as createSandboxPersistentExecOwner } from "./persistent-exec-DTcZFmkg.mjs";
import { t as resolveCronSkillsSnapshot } from "./cron-snapshot-VV6k-dQC.mjs";
import { isDeepStrictEqual } from "node:util";
//#region src/gateway/cron-stream-sandbox-authority.ts
var PolicySessionReadRequired = class extends Error {
constructor(e) {
super("Sandbox stream policy requires current related session facts.");
this.sessionKey = e;
}
};
/** Restore the recorded sandbox and original access dependency for one live stream owner. */
async function prepareCronStreamSandboxAuthority(e) {
const t = parseCronStreamSandboxTarget(e.job.streamSandbox);
if (!t || e.job.schedule.kind !== "stream") throw new Error("Persistent sandbox stream target is unavailable; recreate this automation.");
const n = structuredClone(e.job.skillLibrarySelections);
const r = e.getRuntimeConfig();
const i = captureSandboxConfig(resolveSandboxConfigForAgent(r, t.agentId));
const a = resolveAgentWorkspaceDir(r, t.agentId);
const o = t.operator;
const s = o ? structuredClone(sourceRolePolicy(resolveOperatorRolePolicyForAssignment(o.profileId, o.assignedRole, r, o.githubLogin))) : void 0;
const c = o ? createSyntheticPluginRuntimeClient({
operatorRoleActor: {
kind: "operator",
profileId: o.profileId
},
scopes: [...o.scopes]
}) : void 0;
const l = new AbortController();
const u = [];
let d;
let f;
let p;
const m = /* @__PURE__ */ new Map();
let h = false;
let g;
let _;
let v = 1;
let y = false;
let b;
const unavailable = () => /* @__PURE__ */ new Error("Sandbox stream authority changed; recreate this automation from the current session.");
const revoke = (e) => l.abort(e);
const dropReference = () => {
if (--v === 0) {
for (const e of u.splice(0).toReversed()) e();
p?.release();
for (const e of m.values()) e.release();
d?.release();
}
};
const release = () => {
if (!y) {
y = true;
revoke(unavailable());
dropReference();
b?.();
}
};
const assertExecutionPolicy = (n, r, i) => {
const a = {
cfg: n,
agentId: t.agentId,
sessionKey: t.sessionKey,
sessionEntry: r,
sandboxAvailable: true
};
const o = prepareExecDefaults(a, i);
const { globalExec: s, agentExec: c } = resolveExecConfigState(a);
const l = projectEffectiveExecPolicy({
base: applyExecPolicyLayer(s ?? {}, c),
permissionPolicy: r.permissionMode ? { mode: r.permissionMode } : void 0
});
if (o.kind !== "resolved" || o.defaults.effectiveHost !== "sandbox" || l.mode === "deny" || l.security === "deny") throw unavailable();
if (r.modelSelectionLocked) throw unavailable();
const readEntry = (e) => {
if (e === t.sessionKey) return r;
const i = m.get(e);
if (!i) throw new PolicySessionReadRequired(e);
return i.readCurrent(n).target?.entry;
};
const u = getGatewayPluginMetadataSnapshot();
const d = resolveSessionSelectedModelRef({
cfg: n,
agentId: t.agentId,
sessionKey: t.sessionKey,
source: {
entry: r,
readSourceEntry: readEntry
},
manifestPlugins: u ?? []
});
const f = resolveScheduledToolPolicyContext({
toolsAllow: e.job.payload.toolsAllow,
scheduledToolPolicy: resolveCronScheduledToolPolicy({
toolsAllow: e.job.payload.toolsAllow,
scheduledToolPolicy: e.job.scheduledToolPolicy,
owner: e.job.owner
}),
callerOrigin: e.job.toolsAllowProvenance?.callerOrigin
});
const p = resolveConversationCapabilityProfile({
config: n,
agentId: t.agentId,
sessionKey: t.sessionKey,
sessionId: r.sessionId,
spawnedBy: r.spawnedBy,
preparedSessionEntry: {
sessionKey: t.sessionKey,
entry: r
},
preparedSessionCapabilityStore: {
authoritative: true,
get: readEntry,
getById: () => void 0
},
modelProvider: d.provider,
modelId: d.model,
pluginMetadataSnapshot: u,
sandboxToolPolicy: i.toolPolicy,
scheduledToolPolicy: f
});
if (!isConversationToolAllowed(p, "exec")) throw unavailable();
};
const assertPreparedCurrent = () => {
l.signal.throwIfAborted();
e.signal?.throwIfAborted();
e.assertCurrent();
const r = e.getRuntimeConfig();
if (!listAgentIds(r).includes(t.agentId) || !isDeepStrictEqual(resolveSandboxConfigForAgent(r, t.agentId), i) || resolveAgentWorkspaceDir(r, t.agentId) !== a) throw unavailable();
const u = d?.readCurrentFacts(f);
const m = o ? resolveOperatorRolePolicyForAssignment(o.profileId, o.assignedRole, r, u ? u.profile.githubLogin ?? null : o.githubLogin) : void 0;
if (o) {
if (d && (u?.profile.profileId !== o.profileId || u.profile.assignedRole !== o.assignedRole || (u.profile.githubLogin ?? null) !== o.githubLogin) || !isDeepStrictEqual(sourceRolePolicy(m), s) || m && !roleScopesAllow({
role: "operator",
requestedScopes: o.scopes,
allowedScopes: m.scopes
})) throw unavailable();
}
const g = p?.readCurrent(r);
const v = g?.target.entry;
if (p && isSessionMutationActive(p.storageTarget.storePath, [t.sessionKey, t.sessionId]) && !hasOnlySessionMutationKindActive(p.storageTarget.storePath, [t.sessionKey, t.sessionId], "compaction") && !hasOnlySessionMutationKindActive(p.storageTarget.storePath, [t.sessionKey, t.sessionId], "read-marker") && !hasOnlySessionMutationKindActive(p.storageTarget.storePath, [t.sessionKey, t.sessionId], "background-result")) throw unavailable();
if (p && (!v || v.archivedAt !== void 0 || g?.target.agentId !== t.agentId || g.target.canonicalKey !== t.sessionKey || v.sessionId !== t.sessionId || v.lifecycleRevision !== t.lifecycleRevision || !isDeepStrictEqual(v.skillLibrarySelections, n))) throw unavailable();
if (g && c && u && authorizePreparedSessionMutation({
cfg: r,
client: c,
agentId: t.agentId,
sessionKey: t.sessionKey
}, g, {
policy: m,
aliases: u.aliases
})) throw unavailable();
if (v) {
const e = resolveSandboxRuntimeStatus({
cfg: r,
agentId: t.agentId,
sessionKey: t.sessionKey,
preparedSessionEntry: v
});
if (!e.sandboxed || _ && !isDeepStrictEqual(e, _)) throw unavailable();
if (h) assertExecutionPolicy(r, v, e);
}
return {
currentConfig: r,
identity: u,
entry: v
};
};
const assertAuthorityCurrent = () => {
try {
const e = assertPreparedCurrent();
g?.signal.throwIfAborted();
g?.assertCurrent();
if (o && e.identity) resumeGatewayOperatorAccessGrant(e.identity.profile, e.currentConfig, o.gatewayAccessGrant);
assertPreparedCurrent();
} catch (e) {
revoke(e);
throw e;
}
};
const recheck = () => {
try {
assertPreparedCurrent();
g?.signal.throwIfAborted();
g?.assertCurrent();
} catch (e) {
revoke(e);
}
};
const sourceAborted = () => revoke(e.signal?.reason ?? unavailable());
u.push(onUserProfilesChanged(recheck), onOperatorRolePolicyChanged((e) => {
if (e.kind === "assignment" && e.profileId === o?.profileId) revoke(unavailable());
else if (e.kind === "config") recheck();
}), sessionChanges.subscribe((e) => {
if ("sessionKey" in e && e.scope === "runtime" || "all" in e && e.scope === "agent-runs") return;
if ("all" in e || m.has(e.sessionKey) || e.sessionKey === t.sessionKey && (!e.agentId || e.agentId === t.agentId)) recheck();
}), onSessionIdentityMutation((e) => {
if (e.agentId === t.agentId && e.previous.sessionKeys.includes(t.sessionKey)) revoke(unavailable());
}));
e.signal?.addEventListener("abort", sourceAborted, { once: true });
u.push(() => e.signal?.removeEventListener("abort", sourceAborted));
try {
assertAuthorityCurrent();
if (o) {
d = await prepareUserProfileIdentity(o.profileId);
f = d.emailBindingIds;
assertAuthorityCurrent();
}
p = await prepareSessionMutationFacts({
cfg: r,
agentId: t.agentId,
sessionKey: t.sessionKey
});
const e = assertPreparedCurrent();
if (!e.entry) throw unavailable();
if (o && e.identity) {
g = resumeGatewayOperatorAccessGrant(e.identity.profile, e.currentConfig, o.gatewayAccessGrant);
const t = g;
const accessAborted = () => revoke(t?.signal.reason ?? unavailable());
g?.signal.addEventListener("abort", accessAborted, { once: true });
u.push(() => t?.signal.removeEventListener("abort", accessAborted));
}
assertAuthorityCurrent();
_ = resolveSandboxRuntimeStatus({
cfg: e.currentConfig,
agentId: t.agentId,
sessionKey: t.sessionKey,
preparedSessionEntry: e.entry
});
for (;;) {
const e = assertPreparedCurrent();
if (!e.entry) throw unavailable();
try {
assertExecutionPolicy(e.currentConfig, e.entry, _);
h = true;
break;
} catch (n) {
if (!(n instanceof PolicySessionReadRequired) || m.size >= 32) throw n;
const r = await prepareSessionMutationFacts({
cfg: e.currentConfig,
agentId: parseAgentSessionKey(n.sessionKey)?.agentId ?? t.agentId,
sessionKey: n.sessionKey,
allowMissing: true
});
m.set(n.sessionKey, r);
assertAuthorityCurrent();
}
}
const i = o ? createAdmittedRunOperatorAuthority({
profileId: o.profileId,
scopes: o.scopes,
gatewayAccessGrant: o.gatewayAccessGrant,
assertCurrent: assertAuthorityCurrent,
signal: l.signal,
readCurrentRoleFacts: () => ({
assignedRole: o.assignedRole,
githubLogin: o.githubLogin
}),
...s ? { rolePolicy: {
sessionAccessCap: s.sessions.others,
sandboxRequired: s.sandbox === "required",
agents: s.agents,
accessPrograms: s.accessPrograms
} } : {},
retain: () => {
assertAuthorityCurrent();
v += 1;
let e = false;
return () => {
if (!e) {
e = true;
dropReference();
}
};
}
}) : void 0;
const a = await resolveCronSkillsSnapshot({
workspaceDir: t.agentWorkspaceDir,
config: e.currentConfig,
agentId: t.agentId,
librarySelections: n,
isFastTestEnv: false
});
assertAuthorityCurrent();
const c = await resolveSandboxContextForPersistentExecution({
config: e.currentConfig,
agentId: t.agentId,
sessionKey: t.sessionKey,
...t.workspaceSource !== "managed-worktree" ? { workspaceDir: t.agentWorkspaceDir } : {},
skillsSnapshot: a,
preparedRuntimeStatus: _,
requireCurrentConfig: true,
assertCurrent: assertAuthorityCurrent
}, i);
b = c?.[Symbol.dispose]?.bind(c);
assertAuthorityCurrent();
if (!c) throw unavailable();
const assertCurrent = () => {
try {
assertAuthorityCurrent();
const e = assertPreparedCurrent();
if (!e.entry || !isDeepStrictEqual(captureCronStreamSandboxTarget({
sandbox: c,
agentId: t.agentId,
sessionKey: t.sessionKey,
entry: e.entry
}), t)) throw unavailable();
assertAuthorityCurrent();
} catch (e) {
revoke(e);
throw e;
}
};
assertCurrent();
return {
sandbox: c,
assertCurrent,
signal: l.signal,
release
};
} catch (e) {
release();
throw e;
}
}
//#endregion
//#region src/gateway/cron-stream-sandbox.ts
/** Adapts the cron source owner to the sandbox's persistent-process custody owner. */
function createCronStreamSandboxExecutor(e) {
const t = e.storeKey ?? cronStoreKey(e.storePath);
const n = createSandboxPersistentExecOwner({ scheduler: e.scheduler });
const spawn = async (r) => {
const { job: i } = r;
const a = i.state.streamSourceIdentity;
if (!i.streamSandbox || !a) throw new Error("Sandbox stream is missing its saved target or source identity.");
const o = cronStreamScheduleKey(i.schedule, i.streamSandbox);
const assertCurrent = () => {
e.assertCurrent();
r.assertCurrent();
const t = e.getJob(i.id);
if (!t?.enabled || t.schedule.kind !== "stream" || t.state.streamRestartExhausted || t.state.streamSourceIdentity !== a || cronStreamScheduleKey(t.schedule, t.streamSandbox) !== o) throw new Error("Sandbox stream source changed before execution.");
};
const s = await prepareCronStreamSandboxAuthority({
job: i,
getRuntimeConfig: e.getRuntimeConfig,
assertCurrent,
signal: r.signal
});
try {
s.assertCurrent();
const e = s.sandbox.backend;
if (!e) throw new Error("The admitted sandbox has no execution backend.");
return await n.start({
ownerKey: `cron:${t}:${i.id}`,
source: {
storeKey: t,
jobId: i.id,
scheduleKey: o,
sourceIdentity: a
},
backend: e,
argv: i.schedule.command,
cwd: i.schedule.cwd ?? s.sandbox.containerWorkdir,
assertCurrent: s.assertCurrent,
signal: s.signal,
onOutput: r.onOutput,
releaseAuthority: s.release
});
} catch (e) {
s.release();
throw e;
}
};
return {
spawn,
recover: n.recover
};
}
//#endregion
export { createCronStreamSandboxExecutor };