openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
543 lines (542 loc) • 21 kB
JavaScript
import { i as asOptionalObjectRecord } from "./record-coerce-CVPuDqcc.mjs";
import { o as throwSettledAggregate } from "./error-graph-internal-DdjdM90N.mjs";
import { t as getActivePluginGatewayNodePolicyRegistry } from "./runtime-state-DVrhXeqI.mjs";
import { O as validateAgentRunDelegatedAuthority, c as getActiveAgentRunDelegatedAuthority } from "./agent-run-registry-D7vkrqFT.mjs";
import { y as NODE_WORKER_DESKTOP_COMPUTER_COMMAND } from "./node-commands-BfMJIlXP.mjs";
import { r as parseComputerUseCapabilityDescriptor } from "./computer-use-contract-DrB9JL-Y.mjs";
import { t as assertionSucceeds } from "./assertion-BVvbcE3a.mjs";
import { t as GatewayClientRequestError } from "./request-error-C4C6eD0S.mjs";
import { l as isComputerObservationAction } from "./computer-tool-shared-DjAanHYO.mjs";
import { t as parseNodeWorkerComputerInput } from "./node-computer-protocol-BmZIvrGs.mjs";
import { l as resolveNodeCommandAllowlist, o as isNodeCommandAllowed } from "./node-command-policy-DkH-pkTr.mjs";
import { n as WorkerRunnerUnavailableError } from "./tunnel-contract-CtbXolg4.mjs";
import { n as invokeNodeWithReadinessRetry, t as applyPluginNodeInvokePolicy } from "./node-invoke-plugin-policy-DbONp8j_.mjs";
import { t as publishNodePermissionMissing } from "./nodes.permission-missing-D2B4c3Rq.mjs";
import { t as ComputerTakeControlParamsSchema } from "./computer-tool-control-AfOYX5Gr.mjs";
import { randomUUID } from "node:crypto";
import { Value } from "typebox/value";
//#region src/gateway/worker-environments/computer-transport.ts
const COMPUTER_COMMANDS = ["screen.snapshot", "computer.act"];
function payload(e) {
if (!e.ok) throw new Error(e.error?.message ?? "Session desktop command failed");
return e.payloadJSON ? JSON.parse(e.payloadJSON) : e.payload;
}
/** Captures one environment's desktop under its placement or conversation attachment owner. */
function createEnvironmentComputerTransportOwner(e) {
const t = /* @__PURE__ */ new WeakMap();
return async (n) => {
n.assertCurrent();
const r = e.store.get(n.environmentId);
if (!r?.nodeDeviceId || !r.desktop && !r.sharedHost) return;
const i = e.resolveGatewayContext();
const a = e.getNodeTransport();
if (!i || !a) throw new Error("Session desktop Gateway is unavailable");
const o = i.nodeRegistry.get(r.nodeDeviceId);
if (!o) throw new WorkerRunnerUnavailableError();
const environmentIsCurrent = (t) => {
const n = i.nodeRegistry.get(o.nodeId);
return e.resolveGatewayContext() === i && e.getNodeTransport() === a && t?.leaseId === r.leaseId && t?.ownerEpoch === r.ownerEpoch && t?.nodeDeviceId === o.nodeId && n?.connId === o.connId && n?.pairingGeneration === o.pairingGeneration && n.client.invalidated !== true;
};
const sourceIsCurrent = () => {
try {
n.assertCurrent();
} catch {
return false;
}
const t = e.store.get(r.environmentId);
return environmentIsCurrent(t) && t?.ownerEpoch === n.ownerEpoch && [
"ready",
"idle",
"attached"
].includes(t.state) && t.destroyRequestedAtMs === null;
};
const assertPlacement = () => {
if (!sourceIsCurrent()) throw new Error("Session desktop placement authority changed");
};
assertPlacement();
const s = r.sharedHost ? void 0 : await a.getCurrentNode(o.nodeId);
assertPlacement();
if (!r.sharedHost && !s) throw new Error("Session desktop node lacks the current private worker protocol");
let c = o.computerUse;
if (s) {
const t = await a.invoke({
node: s,
command: NODE_WORKER_DESKTOP_COMPUTER_COMMAND,
params: { operation: "capabilities" },
isDispatchAuthorized: sourceIsCurrent
});
assertPlacement();
if (!a.isCurrent(s)) throw new Error("Session desktop private node owner changed");
if (!t.ok) {
e.warn("Session computer control is unavailable; enable the desktop provider and reprovision the worker.");
return;
}
c = parseComputerUseCapabilityDescriptor(payload(t));
} else if (!COMPUTER_COMMANDS.every((e) => o.commands.includes(e))) return;
if (!c) return;
const l = getActivePluginGatewayNodePolicyRegistry();
if (s && !l?.nodeInvokePolicies.some((e) => e.policy.commands.includes("computer.act"))) {
e.warn("Session computer control is unavailable; enable its provider plugin on the Gateway.");
return;
}
const u = COMPUTER_COMMANDS.map((e) => {
const t = l?.nodeInvokePolicies.find((t) => t.policy.commands.includes(e));
const n = t?.policy;
const r = l?.plugins.find((e) => e.id === t?.pluginId);
return () => l?.nodeInvokePolicies.find((t) => t.policy.commands.includes(e)) === t && t?.policy === n && (!r || l?.plugins.includes(r) && r.enabled && r.status === "loaded");
});
const d = {
nodeId: o.nodeId,
computerUse: c
};
const f = c.provider.generation;
let p = false;
let m;
const h = /* @__PURE__ */ new Set();
const resourceBindingIsCurrent = () => environmentIsCurrent(e.store.get(r.environmentId)) && (!s || a.isCurrent(s));
const bindingIsCurrent = () => (!s || a.isCurrent(s)) && getActivePluginGatewayNodePolicyRegistry() === l && u.every((e) => e()) && (s !== void 0 || i.nodeRegistry.get(o.nodeId)?.computerUse?.provider.generation === f);
const commandIsAllowed = (e) => {
const t = i.nodeRegistry.get(o.nodeId);
const n = s ? [...COMPUTER_COMMANDS] : t?.commands ?? [];
return isNodeCommandAllowed({
command: e,
declaredCommands: n,
allowlist: resolveNodeCommandAllowlist(i.getRuntimeConfig(), {
...t,
approvedCommands: n
})
}).ok;
};
const hasController = () => e.desktopRegistry?.hasController(r.environmentId, r.ownerEpoch);
const parseRequest = (e) => {
if (e.nodeId !== o.nodeId) throw new Error("Computer control is bound to this session's desktop");
if (e.command === "computer.act" && Value.Check(ComputerTakeControlParamsSchema, e.commandParams)) return {
operation: "take-control",
executionId: e.commandParams.executionId
};
const t = e.command === "computer.act" && e.commandParams.action === "__close_execution";
const n = parseNodeWorkerComputerInput(JSON.stringify(t ? {
operation: "close",
executionId: e.commandParams.executionId,
reason: e.commandParams.reason
} : {
operation: e.command === "screen.snapshot" ? "snapshot" : "act",
providerGeneration: f,
params: e.commandParams
}));
if (n.operation === "capabilities") throw new Error("Session computer cannot request another capability check");
return n;
};
const send = async (e, t) => {
const isCurrent = () => resourceBindingIsCurrent() && t.isDispatchAuthorized();
if (!resourceBindingIsCurrent()) throw new Error("Session computer authority closed before dispatch");
const r = e.operation === "snapshot" ? "screen.snapshot" : "computer.act";
const c = e.operation === "close" ? {
action: "__close_execution",
executionId: e.executionId,
reason: e.reason
} : e.params;
return s ? await a.invoke({
node: s,
command: NODE_WORKER_DESKTOP_COMPUTER_COMMAND,
params: e,
...t,
isDispatchAuthorized: isCurrent
}) : await invokeNodeWithReadinessRetry(e.operation === "close" ? { invoke: (e) => i.nodeRegistry.invokeLifecycle({
...e,
isDispatchAuthorized: isCurrent
}) } : i.nodeRegistry, {
nodeId: o.nodeId,
expectedConnId: o.connId,
expectedPairingGeneration: o.pairingGeneration,
command: r,
params: c,
sessionKey: n.sessionKey,
...t,
isDispatchAuthorized: isCurrent
});
};
return {
descriptor: d,
bind(a, l) {
const u = n.turnClaim?.owner.kind === "worker";
l?.assertCurrent();
const f = getActiveAgentRunDelegatedAuthority(a);
const m = u ? l?.authority : f;
if (!f || !m || !validateAgentRunDelegatedAuthority(m) || m.operationalRunInstance.instanceId !== a.instanceId || m.operationalRunInstance.runId !== a.runId || a.runId !== n.runId) throw new Error("Session computer requires the exact admitted run");
const g = {
kind: "agentRuntime",
agentId: n.agentId,
sessionKey: n.sessionKey,
operationalRunInstance: a,
delegatedAuthority: n.turnClaim?.owner.kind === "worker" ? {
...m,
kind: "worker",
turnClaim: n.turnClaim
} : {
...m,
kind: "local"
}
};
const permissionError = (e, t) => {
const n = publishNodePermissionMissing({
error: e,
nodeId: o.nodeId,
nodeName: o.displayName,
command: t,
agentRuntimeIdentity: g,
context: i
});
return n ? new GatewayClientRequestError({
code: "UNAVAILABLE",
message: n.message,
details: { permissionMissing: n.permissionMissing }
}) : void 0;
};
let _;
let v;
const y = /* @__PURE__ */ new Set();
const b = /* @__PURE__ */ new Set();
const x = t.get(f) ?? /* @__PURE__ */ new Set();
t.set(f, x);
let S;
let C = false;
let w = 0;
const T = new AbortController();
const assertCurrent = () => {
if (p || T.signal.aborted || !bindingIsCurrent() || !validateAgentRunDelegatedAuthority(m)) throw new Error("Session computer run authority closed");
l?.assertCurrent();
assertPlacement();
};
assertCurrent();
const execute = async (e, t, r) => {
const a = e.operation === "act" && !isComputerObservationAction(e.params.action, e.params.action === "browser_dialog" ? e.params.dialogAction : void 0);
const c = new AbortController();
if (a) b.add(c);
const assertInvocationCurrent = () => {
assertCurrent();
r?.();
if (a && hasController()) throw new Error("Computer input paused while the operator has control; use take_control when asked to resume, or release control in the Desktop panel");
if (a && C) throw new Error("COMPUTER_STALE_OBSERVATION: take a fresh screenshot after desktop control changes");
c.signal.throwIfAborted();
};
const l = e.operation === "snapshot" ? "screen.snapshot" : "computer.act";
const u = e.params;
const isCurrent = () => assertionSucceeds(assertInvocationCurrent);
const d = AbortSignal.any([
T.signal,
c.signal,
...t.signal ? [t.signal] : []
]);
try {
assertInvocationCurrent();
const dispatch = async (t) => {
const n = parseNodeWorkerComputerInput(JSON.stringify({
...e,
params: t.params
}));
if (n.operation === "capabilities" || n.operation === "close" || n.params.executionId !== _?.physicalId) throw new Error("Computer policy cannot replace the session execution owner");
return await send(n, {
timeoutMs: t.timeoutMs,
signal: t.signal,
idempotencyKey: t.idempotencyKey,
...t.authorizeDispatch ? { authorizeDispatch: t.authorizeDispatch } : {},
isDispatchAuthorized: () => isCurrent() && t.isDispatchAuthorized(),
onDispatchReady: t.onDispatchReady
});
};
const r = await applyPluginNodeInvokePolicy({
context: i,
client: null,
agentRuntimeIdentity: g,
nodeSession: o,
command: l,
params: u,
sessionKey: n.sessionKey,
timeoutMs: t.timeoutMs,
idempotencyKey: t.idempotencyKey,
signal: d,
isInvocationCurrent: isCurrent,
isApprovalAuthorityActive: isCurrent,
privateTransport: {
...s ? { commands: COMPUTER_COMMANDS } : {},
isCurrent,
invoke: dispatch
}
});
assertInvocationCurrent();
if (r) {
if (!r.ok) throw permissionError(asOptionalObjectRecord(r.details)?.nodeError, l) ?? new Error(r.message ?? "Session computer action denied");
return r.payloadJSON ? JSON.parse(r.payloadJSON) : r.payload;
}
if (s && l === "computer.act" || !commandIsAllowed(l)) throw new Error("Session computer command has no active policy or permission");
const a = await dispatch({
params: u,
timeoutMs: t.timeoutMs,
signal: d,
idempotencyKey: t.idempotencyKey,
isDispatchAuthorized: () => isCurrent() && commandIsAllowed(l)
});
assertInvocationCurrent();
if (!a.ok) throw permissionError(a.error, l) ?? new Error(a.error?.message ?? "Session desktop command failed");
return payload(a);
} finally {
b.delete(c);
}
};
const E = { close(t) {
if (v) return v;
T.abort();
S?.();
v = (async () => {
await Promise.allSettled(y);
if (!_ || !resourceBindingIsCurrent()) {
h.delete(E);
return { ok: true };
}
const n = await send({
operation: "close",
executionId: _.physicalId,
reason: t.slice(0, 64)
}, {
signal: e.cleanupSignal,
isDispatchAuthorized: resourceBindingIsCurrent
});
if (!resourceBindingIsCurrent()) throw new Error("Session computer cleanup owner changed");
const r = payload(n);
h.delete(E);
return r;
})();
return v;
} };
return {
computerUse: c,
async resolveNode(e, t) {
t?.throwIfAborted();
assertCurrent();
if (e !== void 0 && e !== o.nodeId) throw new Error("Computer control is bound to this session's desktop");
return d;
},
async invoke(t, n) {
const i = parseRequest(t);
const a = i.operation === "close" || i.operation === "take-control" ? i.executionId : i.params.executionId;
if (_ && a !== _.logicalId) throw new Error("Session computer execution owner changed");
if (i.operation === "close") return E.close(i.reason);
assertCurrent();
t.signal?.throwIfAborted();
n?.();
if (i.operation === "take-control") {
if (!r.desktop || !e.desktopRegistry) throw new Error("Agent takeover is unavailable for this session desktop");
if (!commandIsAllowed("computer.act")) throw new Error("Session computer command has no active policy or permission");
if (!t.idempotencyKey) throw new Error("Agent takeover requires an idempotency key");
const i = JSON.stringify([
r.environmentId,
r.ownerEpoch,
t.idempotencyKey
]);
if (!x.has(i)) {
C = true;
w += 1;
e.desktopRegistry.takeControl(r.environmentId, r.ownerEpoch);
x.add(i);
}
assertCurrent();
n?.();
t.signal?.throwIfAborted();
if (hasController()) throw new Error("The operator took control again; observe before requesting another takeover");
return { ok: true };
}
_ ??= {
logicalId: a,
physicalId: randomUUID()
};
h.add(E);
S ??= e.desktopRegistry?.onControlChanged(r.environmentId, r.ownerEpoch, (e) => {
C = true;
w += 1;
if (e) for (const e of b) e.abort(/* @__PURE__ */ new Error("Computer input paused while the operator has control"));
});
i.params.executionId = _.physicalId;
const o = w;
const s = execute(i, t, n).then((e) => {
if (i.operation === "snapshot" && w === o && !hasController()) C = false;
return e;
});
y.add(s);
s.finally(() => y.delete(s)).catch(() => {});
return s;
}
};
},
close(e) {
if (m) return m;
p = true;
m = (async () => {
const t = (await Promise.allSettled([...h].map((t) => t.close(e)))).filter((e) => e.status === "rejected");
if (t.length) throw new AggregateError(t.map((e) => e.reason), "Session computer cleanup failed");
})();
return m;
}
};
};
}
/** Placement admission retains its exact turn claim; attachments use the same transport owner. */
function createWorkerComputerTransportOwner(e) {
const t = createEnvironmentComputerTransportOwner(e);
return async (n) => {
const r = await e.placements.getAsync(n.sessionId);
if (r?.state !== "active" || !e.placements.validateTurnClaim(n)) throw new Error("Session desktop placement is no longer active");
return t({
environmentId: r.environmentId,
ownerEpoch: r.activeOwnerEpoch,
sessionId: n.sessionId,
sessionKey: r.sessionKey,
agentId: r.agentId,
runId: n.runId,
turnClaim: n,
assertCurrent() {
const t = e.placements.get(n.sessionId);
const i = e.store.get(r.environmentId);
if (!e.placements.validateTurnClaim(n) || t?.state !== "active" || t.generation !== n.placementGeneration || t.sessionKey !== r.sessionKey || t.agentId !== r.agentId || t.environmentId !== r.environmentId || t.activeOwnerEpoch !== r.activeOwnerEpoch || i?.state !== "attached" || i.attachedSessionIds.length !== 1 || i.attachedSessionIds[0] !== n.sessionId) throw new Error("Session desktop placement authority changed");
}
});
};
}
//#endregion
//#region src/gateway/worker-environments/computer-service.ts
/** Owns prepared computer lifetimes across conversation, worker-connection, and Gateway closure. */
function createWorkerComputerService(e) {
const t = createWorkerComputerTransportOwner(e);
const n = createEnvironmentComputerTransportOwner(e);
const r = /* @__PURE__ */ new Map();
const i = /* @__PURE__ */ new Map();
const closeOwner = (e, t) => {
if (e.closing) return e.closing;
e.transport = void 0;
e.connection?.signal.removeEventListener("abort", e.connection.abort);
e.closing = (async () => {
try {
await e.prepared;
await e.closeComputer?.(t);
} finally {
if (i.get(e.claimId) === e) i.delete(e.claimId);
}
})();
return e.closing;
};
const a = e.placements.registerTurnClaimClosedHandler((t) => {
const n = i.get(t.claimId);
if (n) closeOwner(n, "turn-closed").catch(() => e.warn("Session computer cleanup failed after turn closure."));
});
let o = false;
return {
prepareAttached: (e) => {
if (o) return Promise.reject(/* @__PURE__ */ new Error("Session computer owner closed"));
const t = n({
...e,
assertCurrent: () => {
if (o) throw new Error("Session computer owner closed");
e.assertCurrent();
}
}).then((e) => e ? {
...e,
close: async (n) => {
await e.close(n);
r.delete(t);
}
} : void 0);
r.set(t, e);
t.then((e) => {
if (!e) r.delete(t);
}, () => r.delete(t));
return t;
},
closeEnvironment: async (e, t) => {
const n = await Promise.allSettled([...r].filter(([, n]) => n.environmentId === e && (t === void 0 || n.ownerEpoch === t)).map(async ([e]) => (await e.catch(() => void 0))?.close("environment-stopped")));
throwSettledAggregate(n, "Attached computer cleanup failed");
},
prepare: (n) => {
if (o || !e.placements.validateTurnClaim(n)) return Promise.reject(/* @__PURE__ */ new Error("Session computer owner closed"));
const r = i.get(n.claimId);
if (r) return r.prepared;
const a = t(n).then((e) => {
if (!e) return;
s.closeComputer = (t) => e.close(t);
const assertOwner = () => {
if (o || s.closing || i.get(n.claimId) !== s) throw new Error("Session computer owner replaced");
};
return {
...e,
bind(t, n) {
assertOwner();
const r = e.bind(t, n);
const i = {
computerUse: r.computerUse,
async resolveNode(e, t) {
assertOwner();
const n = await r.resolveNode(e, t);
assertOwner();
return n;
},
async invoke(e, t) {
assertOwner();
const n = await r.invoke(e, () => {
assertOwner();
t?.();
});
assertOwner();
return n;
}
};
s.transport = i;
return i;
},
close: (e) => closeOwner(s, e)
};
});
const s = {
claimId: n.claimId,
prepared: a
};
i.set(n.claimId, s);
return a;
},
execute: (async ({ identity: t, request: n, signal: r, assertCurrent: a }) => {
a();
const o = t.turnClaim;
const s = o ? i.get(o.claimId) : void 0;
const c = await s?.prepared;
a();
if (!c || !s?.transport || s.closing || i.get(s.claimId) !== s || !r || s.connection && s.connection.signal !== r) throw new Error("Session computer connection is unavailable; start a new turn");
r.throwIfAborted();
if (!s.connection) {
const abort = () => {
closeOwner(s, "worker-disconnect").catch(() => e.warn("Session computer cleanup failed after worker disconnect."));
};
s.connection = {
signal: r,
abort
};
r.addEventListener("abort", abort, { once: true });
}
const l = await s.transport.invoke({
nodeId: c.descriptor.nodeId,
command: n.command,
commandParams: JSON.parse(n.paramsJson),
timeoutMs: n.timeoutMs,
idempotencyKey: n.idempotencyKey,
signal: r
}, a);
a();
return { resultJson: JSON.stringify(l) };
}),
close: async () => {
o = true;
a();
const e = await Promise.allSettled([...[...i.values()].map((e) => closeOwner(e, "gateway-stop")), ...[...r.keys()].map(async (e) => (await e.catch(() => void 0))?.close("gateway-stop"))]);
throwSettledAggregate(e, "Session computer cleanup failed");
}
};
}
//#endregion
export { createWorkerComputerService };