openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
420 lines (419 loc) • 17.6 kB
JavaScript
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs";
import { i as collectNestedErrorCandidates } from "./error-coercion-hDrHOSGy.mjs";
import { n as prepareGatewayContextBindingOwner } from "./gateway-context-binding-owner-BGZ2bJF4.mjs";
import { t as freezeJsonSnapshot } from "./immutable-data-Y7xVjZoy.mjs";
import { O as validateAgentRunDelegatedAuthority, a as claimAgentRunDelegatedAuthority, h as readAgentRunDelegatedAuthorityFailure, n as captureAgentRunDelegatedSourceAssertion, x as releaseAgentRunDelegatedAuthority } from "./agent-run-registry-D7vkrqFT.mjs";
import { d as runWithSessionSourceScope, l as prepareSessionSourceScope, o as composeSessionSourceAssertion } from "./session-source-authority-TlTpfRVE.mjs";
import { r as getAgentRunLifecycleGeneration } from "./agent-run-registry-state-BFfw9a4W.mjs";
import { n as isExecutionIdentityCollectionEnabled } from "./audit-config-DjeE3VAP.mjs";
import { n as createExecutionIdentityAdmissionToken, r as enqueueExecutionIdentityContextAtAdmission, s as executionIdentitySpawnAdmission } from "./execution-identity-admission-EuMO_R29.mjs";
import { randomUUID } from "node:crypto";
//#region src/gateway/operator-access-errors.ts
var GatewayOperatorAccessUnavailableError = class extends Error {
constructor() {
super("Gateway access policy is unavailable; retry after its plugin is ready.");
this.name = "GatewayOperatorAccessUnavailableError";
}
};
/** Temporary policy loading failures must not revoke retained execution authority. */
function isGatewayOperatorAccessUnavailable(e) {
return collectNestedErrorCandidates(e).some((e) => e instanceof GatewayOperatorAccessUnavailableError);
}
//#endregion
//#region src/agents/operational-run-instance.ts
function createOperationalRunInstanceRef(e) {
return Object.freeze({
instanceId: randomUUID(),
runId: e
});
}
//#endregion
//#region src/agents/operator-access-program.ts
/** Named roles grant each program explicitly; standalone/System behavior is unchanged. */
function isOperatorAccessProgramAllowed(e, t) {
if (!e || !t || t === "standard") return true;
return e.accessPrograms?.cyber.includes(t) === true;
}
/** Native dispatch must retain exact policy checks for model or Access restrictions. */
function requiresOperatorModelExecutionPolicy(e) {
return e?.modelPolicy !== void 0 || !isOperatorAccessProgramAllowed(e?.rolePolicy, "daybreak_blue") || !isOperatorAccessProgramAllowed(e?.rolePolicy, "daybreak_red");
}
//#endregion
//#region src/agents/admitted-run-context.ts
const operatorAuthorityIssuers = resolveGlobalSingleton(Symbol.for("openclaw.admittedRunOperatorAuthority.issuers"), () => /* @__PURE__ */ new WeakSet());
/** Host-only construction; public reply options cannot manufacture a source capability. */
function createAdmittedRunOperatorAuthority(e) {
const t = e.assertCurrent;
const n = e.signal;
let r = false;
let i;
const a = composeSessionSourceAssertion([t], (e) => {
if (r) throw i;
try {
n?.throwIfAborted();
e();
} catch (e) {
if (!isGatewayOperatorAccessUnavailable(e)) {
r = true;
i = e;
}
throw e;
}
});
const o = e.readCurrentRoleFacts;
const s = Object.freeze({
profileId: e.profileId,
recoverySnapshot: e.recoverySnapshot ? freezeJsonSnapshot(structuredClone(e.recoverySnapshot)) : void 0,
channelRecoverySource: e.channelRecoverySource ? Object.freeze({
reference: Object.freeze({ ...e.channelRecoverySource.reference }),
modelPolicy: e.channelRecoverySource.modelPolicy
}) : void 0,
scopes: Object.freeze([...e.scopes]),
gatewayAccessGrant: e.gatewayAccessGrant ? Object.freeze({ ...e.gatewayAccessGrant }) : e.gatewayAccessGrant,
source: e.source ?? {},
signal: n,
retain: e.retain,
onModelPolicyChanged: e.onModelPolicyChanged,
get modelPolicy() {
return e.modelPolicy;
},
assertCurrent: a,
readCurrentRoleFacts: o ? () => {
a();
return o();
} : void 0,
rolePolicy: e.rolePolicy ? Object.freeze({
...e.rolePolicy,
...e.rolePolicy.accessPrograms ? { accessPrograms: Object.freeze({ cyber: Object.freeze([...new Set(e.rolePolicy.accessPrograms.cyber)].toSorted()) }) } : {},
agents: e.rolePolicy.agents === "*" ? "*" : Object.freeze([...new Set(e.rolePolicy.agents)].toSorted())
}) : void 0
});
operatorAuthorityIssuers.add(s);
return s;
}
function assertAdmittedRunOperatorAuthority(e) {
if (!e || typeof e !== "object" || !operatorAuthorityIssuers.has(e)) throw new Error("operator run authority must be issued by the host");
}
/** Selection never grants authority; callers must pass the original host-issued source. */
function assertOperatorModelAllowed(e, t) {
createOperatorModelSelectionAssertion(e, t)();
}
/** Carry the operator's source checks into writes without rereading its store on the host. */
function createOperatorModelSelectionAssertion(e, t) {
return composeSessionSourceAssertion([e?.assertCurrent], (n) => {
if (!e) return;
assertAdmittedRunOperatorAuthority(e);
n();
const r = e.modelPolicy;
if (r && (!t || !r.allows(t))) throw new Error("Your operator role cannot use this model. Choose an allowed model or ask a gateway administrator to update your role's model policy.");
assertOperatorAccessProgramAllowed(e, t?.cyberAccessProgram);
});
}
/** Clearing a stale Access selection must not require permission to its old model. */
function assertOperatorAccessProgramAllowed(e, t) {
if (!e) return;
assertAdmittedRunOperatorAuthority(e);
e.assertCurrent();
if (!isOperatorAccessProgramAllowed(e.rolePolicy, t)) throw new Error("Your operator role cannot use this Access level. Choose Standard or ask a gateway administrator to grant this Access level to your role.");
}
/** Keeps one selected model current without revoking other work from the same source. */
function bindOperatorModelExecution(e, t, n) {
if (!e) return;
const r = createOperatorModelSelectionAssertion(e, t ? { ...t } : void 0);
const mapError = (e) => n?.(e) ?? e;
let i;
try {
r();
i = e.retain?.();
} catch (e) {
throw mapError(e);
}
const a = new AbortController();
let o = false;
const assertCurrent = () => {
if (o) throw mapError(/* @__PURE__ */ new Error("operator model execution authority is no longer active"));
a.signal.throwIfAborted();
try {
r();
} catch (e) {
const t = mapError(e);
a.abort(t);
throw t;
}
};
const recheck = () => {
try {
assertCurrent();
} catch {}
};
const onSourceAbort = () => a.abort(mapError(e.signal?.reason));
e.signal?.addEventListener("abort", onSourceAbort, { once: true });
const s = e.onModelPolicyChanged?.(recheck);
recheck();
return {
signal: a.signal,
assertCurrent,
release: () => {
if (!o) {
o = true;
s?.();
e.signal?.removeEventListener("abort", onSourceAbort);
i?.();
}
}
};
}
/** Prepared and admitted paths share the same source throughout retries and detached work. */
function readRunOperatorAuthority(e) {
return readAdmittedRunOperatorAuthority(e.admittedRunContext) ?? readPreparedRunOperatorAuthority(e.preparedRunAdmission);
}
const delegatedAuthorityLeases = /* @__PURE__ */ new WeakMap();
const admittedContextsByAuthority = /* @__PURE__ */ new WeakMap();
const activeNativeHookRecoveryLeases = /* @__PURE__ */ new Map();
/** Reprepare source predicates after the caller establishes an exact transcript fence. */
function runWithPreparedRunSourceScope(e, t) {
let n = e.preparedRunAdmission?.assertSourceCurrent;
if (e.admittedRunContext) {
const t = delegatedAuthorityLeases.get(e.admittedRunContext);
const r = t && captureAdmittedRunActiveAssertion(e.admittedRunContext, t.authority);
if (!r) return Promise.reject(/* @__PURE__ */ new Error("admitted run authority is no longer active"));
n = r;
}
return runWithSessionSourceScope(n, t, { checkAfter: false });
}
function bindAdmittedRunDelegatedAuthority(e, t, n) {
const r = claimAgentRunDelegatedAuthority(e.operationalRunInstance, t);
const i = activeNativeHookRecoveryLeases.get(e.operationalRunInstance.runId);
activeNativeHookRecoveryLeases.delete(e.operationalRunInstance.runId);
i?.releaseOperatorAuthority?.();
const a = {
authority: r,
foregroundClosed: false,
assertSourceCurrent: t,
operatorAuthority: n
};
delegatedAuthorityLeases.set(e, a);
if (!admittedContextsByAuthority.has(r)) admittedContextsByAuthority.set(r, e);
}
/** Reads the immutable outer-run authority without reviving a closed claim. */
function getAdmittedRunDelegatedAuthority(e) {
const t = delegatedAuthorityLeases.get(e);
return t && !t.foregroundClosed && validateAgentRunDelegatedAuthority(t.authority) ? t.authority : void 0;
}
/** Captures the operator's source lifetime from a live run, including for detached children. */
function readAdmittedRunOperatorAuthority(e) {
if (!e) return;
const t = delegatedAuthorityLeases.get(e)?.operatorAuthority;
if (!t) return;
if (!getAdmittedRunDelegatedAuthority(e)) throw new Error("admitted run operator authority is no longer active");
return t;
}
/** Reads the same source ceiling used by admission without minting run authority. */
function readPreparedRunOperatorAuthority(e) {
const t = e?.readOperatorAuthority?.();
if (t !== void 0) assertAdmittedRunOperatorAuthority(t);
return t;
}
/** Reads the original admission source only through its exact live authority. */
function getAdmittedRunSource(e) {
const t = e && admittedContextsByAuthority.get(e);
return t && getAdmittedRunDelegatedAuthority(t) === e ? t.admissionSource : void 0;
}
/** Captures an exact admitted-run assertion for work that may cross an await boundary. */
function resolveAdmittedRunActiveAssertion(e, t) {
const n = getAdmittedRunDelegatedAuthority(e);
return n ? captureAdmittedRunActiveAssertion(e, n, t) : void 0;
}
/** Capture an already-resolved authority without repeating its source reads. */
function captureAdmittedRunActiveAssertion(e, t, n) {
const r = e.operationalRunInstance;
const i = delegatedAuthorityLeases.get(e);
const refuse = () => {
throw new Error("admitted run authority is no longer active", readAgentRunDelegatedAuthorityFailure(t));
};
const a = captureAgentRunDelegatedSourceAssertion(t, refuse);
if (!i || i.foregroundClosed || i.authority !== t || !a) return;
const assertLocalCurrent = (t) => {
if (n?.aborted || e.operationalRunInstance !== r || delegatedAuthorityLeases.get(e) !== i || i.foregroundClosed) refuse();
t();
};
return Object.assign(composeSessionSourceAssertion([a.assertCurrent], assertLocalCurrent), { assertScopeCurrent: () => assertLocalCurrent(a.assertBinding) });
}
/** Idempotently compare-releases the authority captured by this admission. */
function closeAdmittedRunDelegatedAuthority(e) {
const t = delegatedAuthorityLeases.get(e);
if (!t || t.foregroundClosed) return false;
t.foregroundClosed = true;
releaseAgentRunDelegatedAuthority(t.authority);
return true;
}
/** Recovery-only lease for the already-created native pre-tool policy callback. */
function retainAdmittedRunBeforeToolCallRecovery(e) {
const t = delegatedAuthorityLeases.get(e);
const n = e.operationalRunInstance.runId;
if (!t || t.foregroundClosed || activeNativeHookRecoveryLeases.has(n) || !validateAgentRunDelegatedAuthority(t.authority)) return;
const r = {
lease: t,
releaseOperatorAuthority: t.operatorAuthority?.retain?.()
};
activeNativeHookRecoveryLeases.set(n, r);
const assertActive = () => {
t.assertSourceCurrent?.();
if (getAgentRunLifecycleGeneration() !== t.authority.lifecycleGeneration || activeNativeHookRecoveryLeases.get(n) !== r) throw new Error("admitted run native hook recovery is no longer active");
};
return {
assertActive,
release: () => {
if (activeNativeHookRecoveryLeases.get(n) === r) {
activeNativeHookRecoveryLeases.delete(n);
r.releaseOperatorAuthority?.();
}
}
};
}
/** Prepares a system-owned run without selecting its eventual execution runtime early. */
function prepareSystemAgentRunAdmission(e, t, n, r, i, a) {
return prepareAgentRunAdmission({
cfg: e,
operationalRunInstance: createOperationalRunInstanceRef(t),
assertSourceCurrent: i,
operatorAuthority: a,
facts: {
runId: t,
agentId: n,
ingress: {
kind: "system",
boundary: r,
state: "present"
}
}
});
}
/**
* Freezes ingress facts before preparation while deferring allocation/capture until the
* authoritative runtime owner is selected immediately before execution.
*/
function prepareAgentRunAdmission(e) {
const t = e.operationalRunInstance;
if (t.runId !== e.facts.runId) throw new Error("operational run instance disagrees with prepared admission");
const n = e.assertSourceCurrent;
const r = e.operatorAuthority;
if (r !== void 0) assertAdmittedRunOperatorAuthority(r);
const i = r?.assertCurrent;
const a = r?.retain?.();
let o;
const s = (n || i) && composeSessionSourceAssertion([n, i], (e) => {
if (o) throw o;
try {
e();
} catch (e) {
o = new Error("source execution authority is no longer active", { cause: e });
throw e;
}
});
let c;
let l;
let u;
let d;
let f = false;
const assertPreparationOpen = () => {
if (f) throw new Error("prepared execution context is already closed");
};
const p = composeSessionSourceAssertion([s], (e) => {
assertPreparationOpen();
e();
});
return Object.freeze({
operationalRunInstance: t,
assertSourceCurrent: Object.assign(composeSessionSourceAssertion([s]), {
assertScopeCurrent: assertPreparationOpen,
prepareSessionSourceScope: () => {
assertPreparationOpen();
return prepareSessionSourceScope(p);
}
}),
readOperatorAuthority: () => {
if (r) {
if (f) throw new Error("prepared operator authority is no longer active");
r.assertCurrent();
}
return r;
},
close: () => {
if (f) return;
f = true;
if (d) closeAdmittedRunDelegatedAuthority(d);
else u?.then(closeAdmittedRunDelegatedAuthority).catch(() => void 0);
a?.();
},
admit: (n, i) => {
if (f) return Promise.reject(/* @__PURE__ */ new Error("prepared execution context is already closed"));
const a = c ??= n;
l ??= i?.trim() || void 0;
u ??= runWithSessionSourceScope(s, async () => {
s?.();
const n = executionIdentitySpawnAdmission({
operation: "attach",
value: {
...e.facts,
runtime: { kind: a }
},
extra: executionIdentitySpawnAdmission({
operation: "read",
value: e.facts
})
});
const i = admitPreparedAgentRun({
cfg: e.cfg,
admissionSource: e.admissionSource,
facts: n,
operationalRunInstance: t,
runtimeInstanceId: l
});
bindAdmittedRunDelegatedAuthority(i, s, r);
d = i;
try {
await e.onAdmitted?.(i);
if (f || !getAdmittedRunDelegatedAuthority(i)) throw new Error("prepared execution authority closed during admission");
return i;
} catch (e) {
closeAdmittedRunDelegatedAuthority(i);
throw e;
}
}, { checkAfter: false });
return u;
}
});
}
/** Resolves a host-only continuation or validates an already-admitted internal caller. */
async function resolvePreparedRunAdmission(e) {
if (e.admittedRunContext && e.preparedRunAdmission) throw new Error("run cannot carry both prepared and admitted execution contexts");
const t = e.preparedRunAdmission ? await e.preparedRunAdmission.admit(e.runtimeKind, e.runtimeInstanceId) : e.admittedRunContext;
if (!t || t.operationalRunInstance.runId !== e.runId) throw new Error("prepared execution context is unavailable or disagrees with the run");
if (delegatedAuthorityLeases.get(t) && !getAdmittedRunDelegatedAuthority(t)) throw new Error("prepared execution authority is no longer active");
return t;
}
/**
* Owns the single post-prepare allocation/adoption/capture decision for an execution.
* Queue loss remains audit loss only; the admitted execution keeps its exact token object.
*/
function admitPreparedAgentRun(e) {
if (e.operationalRunInstance.runId !== e.facts.runId) throw new Error("operational run instance disagrees with prepared admission");
const t = {
operationalRunInstance: e.operationalRunInstance,
...e.admissionSource ? { admissionSource: e.admissionSource } : {}
};
if (!isExecutionIdentityCollectionEnabled(e.cfg)) return Object.freeze(prepareGatewayContextBindingOwner(t));
const n = createExecutionIdentityAdmissionToken(e.facts.runId);
enqueueExecutionIdentityContextAtAdmission(e.facts, {
enabled: true,
token: n,
runtimeInstanceId: e.runtimeInstanceId
});
return Object.freeze(prepareGatewayContextBindingOwner({
...t,
executionIdentityToken: n
}));
}
//#endregion
export { GatewayOperatorAccessUnavailableError as C, createOperationalRunInstanceRef as S, resolvePreparedRunAdmission as _, captureAdmittedRunActiveAssertion as a, isOperatorAccessProgramAllowed as b, createOperatorModelSelectionAssertion as c, prepareAgentRunAdmission as d, prepareSystemAgentRunAdmission as f, resolveAdmittedRunActiveAssertion as g, readRunOperatorAuthority as h, bindOperatorModelExecution as i, getAdmittedRunDelegatedAuthority as l, readPreparedRunOperatorAuthority as m, assertOperatorAccessProgramAllowed as n, closeAdmittedRunDelegatedAuthority as o, readAdmittedRunOperatorAuthority as p, assertOperatorModelAllowed as r, createAdmittedRunOperatorAuthority as s, assertAdmittedRunOperatorAuthority as t, getAdmittedRunSource as u, retainAdmittedRunBeforeToolCallRecovery as v, isGatewayOperatorAccessUnavailable as w, requiresOperatorModelExecutionPolicy as x, runWithPreparedRunSourceScope as y };