openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
430 lines (429 loc) • 15 kB
JavaScript
import { s as asFiniteNumber } from "../../number-coercion-D6u-4YD8.mjs";
import { t as asNonArrayRecord } from "../../record-coerce-CVPuDqcc.mjs";
import { r as truncateUtf16Safe } from "../../utf16-slice-CuDyEXgS.mjs";
import { n as canAccessSync } from "../../path-existence-Co7-GyVr.mjs";
import { m as tryParseJson, n as clamp } from "../../utils-C8YECn2Q.mjs";
import { n as resolvePreferredOpenClawTmpDir } from "../../tmp-openclaw-dir-Bf0oU1Cn.mjs";
import { Lt as boolean, qn as strictObject } from "../../schemas-Cy6abvsu.mjs";
import { n as runCommandWithTimeout } from "../../exec-runner-Br73vG-X.mjs";
import "../../path-existence-runtime-LOpU--Vt.mjs";
import "../../string-coerce-runtime-BwAZZDf5.mjs";
import "../../text-utility-runtime-Ds8jsG0J.mjs";
import "../../process-runtime-DcBPEA8Y.mjs";
import { n as buildPluginConfigSchema } from "../../config-schema-BjPebUmU.mjs";
import { t as definePluginEntry } from "../../plugin-entry-CiJdaHtx.mjs";
import { n as withTempWorkspace } from "../../fs-safe-compat-Cbx7s6au.mjs";
import "../../temp-path-CW7QMeae.mjs";
import fs from "node:fs";
import path from "node:path";
import fs$1 from "node:fs/promises";
//#region extensions/linux-node/src/config.ts
const CapabilityConfigSchema = strictObject({ enabled: boolean().optional() });
const LinuxNodePluginConfigSchema = strictObject({
notify: CapabilityConfigSchema.optional(),
camera: CapabilityConfigSchema.optional(),
location: CapabilityConfigSchema.optional()
});
function createLinuxNodePluginConfigSchema() {
return buildPluginConfigSchema(LinuxNodePluginConfigSchema);
}
function resolveLinuxNodePluginConfig(e) {
const t = LinuxNodePluginConfigSchema.safeParse(e ?? {});
if (!t.success) throw new Error(`Invalid linux-node plugin config: ${t.error.issues[0]?.message ?? "invalid config"}`);
return {
notify: { enabled: t.data.notify?.enabled ?? true },
camera: { enabled: t.data.camera?.enabled ?? false },
location: { enabled: t.data.location?.enabled ?? false }
};
}
function resolveLinuxNodePluginConfigFromHost(e) {
try {
return resolveLinuxNodePluginConfig(e.plugins?.entries?.["linux-node"]?.config);
} catch {
return null;
}
}
//#endregion
//#region extensions/linux-node/src/executables.ts
function resolveExecutable(e, t, n = []) {
const r = (t.PATH ?? "").split(path.delimiter).filter(Boolean).map((t) => path.join(t, e));
return (path.isAbsolute(e) ? [e] : [...r, ...n]).find((e) => canAccessSync(e, fs.constants.X_OK)) ?? null;
}
//#endregion
//#region extensions/linux-node/src/commands.ts
function parseParams(e) {
return asNonArrayRecord(tryParseJson(e ?? ""));
}
function formatToolError(e) {
const t = e.stderr.trim() || e.stdout.trim();
return t ? truncateUtf16Safe(t.replaceAll(/\s+/gu, " "), 300) : `exit ${e.code ?? "unknown"}`;
}
function assertToolResult(e, t) {
if (e.termination === "timeout" || e.termination === "no-output-timeout") throw new Error(`${t}: command timed out`);
if (e.code !== 0) throw new Error(`${t}: ${formatToolError(e)}`);
}
function isCapabilityEnabledForHost(e, t) {
return resolveLinuxNodePluginConfigFromHost(e.config)?.[t].enabled === true;
}
const GEOCLUE_DEMO_PATHS = ["/usr/libexec/geoclue-2.0/demos/where-am-i", "/usr/lib/geoclue-2.0/demos/where-am-i"];
const GEOCLUE_TIMESTAMP_RESOLUTION_MS = 1e3;
function isLocationDisabledOutput(e) {
return /Geolocation disabled|disallowed, no agent|AccessDenied|not authorized/iu.test(e);
}
function parseLocationOutput(e, t) {
const n = e.split(/\nNew location:\s*\n/gu);
for (const e of n.toReversed()) {
const n = /Latitude:\s*([-+\d.]+)/u.exec(e)?.[1];
const r = /Longitude:\s*([-+\d.]+)/u.exec(e)?.[1];
const i = /Accuracy:\s*([-+\d.]+)/u.exec(e)?.[1];
if (n === void 0 || r === void 0 || i === void 0) continue;
const a = Number(n);
const o = Number(r);
const s = Number(i);
if (!Number.isFinite(a) || !Number.isFinite(o) || !Number.isFinite(s) || a < -90 || a > 90 || o < -180 || o > 180 || s < 0) continue;
const c = /\((\d+)\s+seconds since the Epoch\)/u.exec(e)?.[1];
const l = /Altitude:\s*([-+\d.]+)/u.exec(e)?.[1];
const u = /Speed:\s*([-+\d.]+)/u.exec(e)?.[1];
const d = /Heading:\s*([-+\d.]+)/u.exec(e)?.[1];
const f = c ? (/* @__PURE__ */ new Date(Number(c) * 1e3)).toISOString() : (/* @__PURE__ */ new Date()).toISOString();
const p = Date.now() - Date.parse(f);
if (t !== void 0 && (p < 0 || p >= t + GEOCLUE_TIMESTAMP_RESOLUTION_MS)) continue;
return {
lat: a,
lon: o,
accuracyMeters: s,
...l !== void 0 ? { altitudeMeters: Number(l) } : {},
...u !== void 0 ? { speedMps: Number(u) } : {},
...d !== void 0 ? { headingDeg: Number(d) } : {},
timestamp: f
};
}
return null;
}
const MAX_MEDIA_RAW_BYTES = Math.floor(6537216) * 3;
function encodeMedia(e) {
if (e.byteLength > MAX_MEDIA_RAW_BYTES) throw new Error("PAYLOAD_TOO_LARGE: camera payload exceeds the 25 MB base64 limit");
return e.toString("base64");
}
function readJpegDimensions(e) {
if (e.byteLength < 4 || e[0] !== 255 || e[1] !== 216) return null;
let t = 2;
while (t + 9 < e.byteLength) {
if (e[t] !== 255) {
t += 1;
continue;
}
const n = e[t + 1];
if (n === void 0) return null;
if (n === 255) {
t += 1;
continue;
}
if (n === 217 || n === 218) return null;
const r = e.readUInt16BE(t + 2);
if ((n >= 192 && n <= 195 || n >= 197 && n <= 199 || n >= 201 && n <= 203 || n >= 205 && n <= 207) && r >= 7) return {
height: e.readUInt16BE(t + 5),
width: e.readUInt16BE(t + 7)
};
if (r < 2) return null;
t += r + 2;
}
return null;
}
async function listLinuxVideoDevices(e) {
const t = (await fs$1.readdir("/dev")).filter((e) => /^video\d+$/u.test(e)).toSorted((e, t) => e.localeCompare(t, "en", { numeric: true }));
const n = [];
for (const r of t) {
const t = path.join("/dev", r);
const i = await runCommandWithTimeout([
e,
"-hide_banner",
"-f",
"v4l2",
"-list_formats",
"all",
"-i",
t
], {
timeoutMs: 5e3,
maxOutputBytes: {
stdout: 4096,
stderr: 65536
},
outputCapture: "tail"
});
if (!/\b(?:Raw|Compressed)\s*:/u.test(`${i.stdout}\n${i.stderr}`)) continue;
const a = await fs$1.readFile(path.join("/sys/class/video4linux", r, "name"), "utf8").then((e) => e.trim()).catch(() => r);
n.push({
id: t,
name: a,
position: "unknown",
deviceType: "v4l2"
});
}
return n;
}
async function withTempFile(e, t) {
return await withTempWorkspace({
rootDir: resolvePreferredOpenClawTmpDir(),
prefix: "openclaw-linux-node-"
}, async ({ dir: n }) => await t(path.join(n, `capture${e}`)));
}
function createLinuxNodeCommands(e) {
const t = process.platform;
const n = process.env;
const findWhereAmI = (e = n) => resolveExecutable("where-am-i", e, GEOCLUE_DEMO_PATHS);
const readMedia = async (e) => {
if ((await fs$1.stat(e)).size > MAX_MEDIA_RAW_BYTES) throw new Error("PAYLOAD_TOO_LARGE: camera payload exceeds the 25 MB base64 limit");
return await fs$1.readFile(e);
};
const assertLinuxCapability = (n, r) => {
if (t !== "linux") throw new Error(`${r}: Linux node host required`);
if (!e[n].enabled) throw new Error(`${r}: enable plugins.entries.linux-node.config.${n}.enabled and restart the node service`);
};
const isAvailable = (e, n) => (r) => t === "linux" && isCapabilityEnabledForHost(r, e) && resolveExecutable(n, r.env) !== null;
const resolveTool = (e, t, r, i) => {
assertLinuxCapability(e, r);
const a = resolveExecutable(t, n);
if (!a) throw new Error(`${i}: ${t} not found`);
return a;
};
const selectVideoDevice = async (e, t) => {
const n = await listLinuxVideoDevices(t);
if (typeof e === "string" && e.trim()) {
const t = n.find((t) => t.id === e.trim());
if (!t) throw new Error(`INVALID_REQUEST: camera device not found: ${e.trim()}`);
return t;
}
const r = n[0];
if (!r) throw new Error("CAMERA_UNAVAILABLE: no V4L2 camera devices found");
return r;
};
return [
{
command: "system.notify",
hasActiveWork: () => false,
isAvailable: isAvailable("notify", "notify-send"),
handle: async (e) => {
const t = resolveTool("notify", "notify-send", "NOTIFICATIONS_DISABLED", "NOTIFICATIONS_UNAVAILABLE");
const n = parseParams(e);
const r = typeof n.title === "string" ? n.title.trim() : "";
const i = typeof n.body === "string" ? n.body.trim() : "";
if (!r && !i) throw new Error("INVALID_REQUEST: empty notification");
const a = n.priority === "passive" ? "low" : n.priority === "timeSensitive" ? "critical" : "normal";
assertToolResult(await runCommandWithTimeout([
t,
"--urgency",
a,
"--",
r,
i
], { timeoutMs: 1e4 }), "NOTIFICATIONS_UNAVAILABLE");
return JSON.stringify({ ok: true });
}
},
{
command: "camera.list",
hasActiveWork: () => false,
cap: "camera",
isAvailable: isAvailable("camera", "ffmpeg"),
handle: async () => {
const e = resolveTool("camera", "ffmpeg", "CAMERA_DISABLED", "CAMERA_UNAVAILABLE");
return JSON.stringify({ devices: await listLinuxVideoDevices(e) });
}
},
{
command: "camera.snap",
hasActiveWork: () => false,
cap: "camera",
dangerous: true,
isAvailable: isAvailable("camera", "ffmpeg"),
handle: async (e) => {
const t = resolveTool("camera", "ffmpeg", "CAMERA_DISABLED", "CAMERA_UNAVAILABLE");
const n = parseParams(e);
const r = typeof n.format === "string" ? n.format.toLowerCase() : "jpg";
if (r !== "jpg" && r !== "jpeg") throw new Error(`INVALID_REQUEST: unsupported camera image format: ${r}`);
const i = await selectVideoDevice(n.deviceId, t);
const a = asFiniteNumber(n.maxWidth);
const o = a && a > 0 ? Math.max(2, Math.floor(a)) : 1600;
const s = clamp(asFiniteNumber(n.quality) ?? .9, .05, 1);
const c = clamp(Math.floor(asFiniteNumber(n.delayMs) ?? 2e3), 0, 1e4);
const l = Math.round(31 - s * 29);
return await withTempFile(".jpg", async (e) => {
assertToolResult(await runCommandWithTimeout([
t,
"-hide_banner",
"-loglevel",
"error",
"-y",
"-f",
"v4l2",
"-i",
i.id,
"-ss",
(c / 1e3).toFixed(3),
"-frames:v",
"1",
"-vf",
`scale=min(iw\\,${o}):-2`,
"-q:v",
String(l),
e
], { timeoutMs: c + 2e4 }), "CAMERA_UNAVAILABLE");
const n = await readMedia(e);
const a = readJpegDimensions(n);
if (!a) throw new Error("CAMERA_UNAVAILABLE: FFmpeg returned an invalid JPEG");
return JSON.stringify({
format: r,
base64: encodeMedia(n),
width: a.width,
height: a.height
});
});
}
},
{
command: "camera.clip",
hasActiveWork: () => false,
cap: "camera",
dangerous: true,
isAvailable: isAvailable("camera", "ffmpeg"),
handle: async (e) => {
const t = resolveTool("camera", "ffmpeg", "CAMERA_DISABLED", "CAMERA_UNAVAILABLE");
const n = parseParams(e);
const r = typeof n.format === "string" ? n.format.toLowerCase() : "mp4";
if (r !== "mp4") throw new Error(`INVALID_REQUEST: unsupported camera clip format: ${r}`);
const i = await selectVideoDevice(n.deviceId, t);
const a = clamp(Math.floor(asFiniteNumber(n.durationMs) ?? 3e3), 250, 6e4);
const o = typeof n.includeAudio === "boolean" ? n.includeAudio : true;
return await withTempFile(".mp4", async (e) => {
const n = [
"-f",
"v4l2",
"-i",
i.id
];
if (o) n.push("-f", "pulse", "-i", "default");
const r = o ? [
"-map",
"0:v:0",
"-map",
"1:a:0",
"-c:a",
"aac",
"-b:a",
"128k",
"-shortest"
] : ["-an"];
assertToolResult(await runCommandWithTimeout([
t,
"-hide_banner",
"-loglevel",
"error",
"-y",
...n,
"-t",
(a / 1e3).toFixed(3),
"-c:v",
"libx264",
"-preset",
"veryfast",
"-pix_fmt",
"yuv420p",
...r,
"-movflags",
"+faststart",
e
], { timeoutMs: a + 3e4 }), "CAMERA_UNAVAILABLE");
const s = await readMedia(e);
return JSON.stringify({
format: "mp4",
base64: encodeMedia(s),
durationMs: a,
hasAudio: o
});
});
}
},
{
command: "location.get",
hasActiveWork: () => false,
cap: "location",
isAvailable: (e) => t === "linux" && isCapabilityEnabledForHost(e, "location") && findWhereAmI(e.env) !== null,
handle: async (e) => {
assertLinuxCapability("location", "LOCATION_DISABLED");
const t = findWhereAmI();
if (!t) throw new Error("LOCATION_UNAVAILABLE: where-am-i not found");
const n = parseParams(e);
const r = clamp(Math.floor(asFiniteNumber(n.timeoutMs) ?? 1e4), 1e3, 6e4);
const i = asFiniteNumber(n.maxAgeMs);
const a = i !== void 0 && i >= 0 ? i : void 0;
const o = n.desiredAccuracy === "coarse" ? 4 : n.desiredAccuracy === "precise" ? 8 : 6;
let s = "";
let c = 0;
const l = await runCommandWithTimeout([
t,
"-t",
String(Math.ceil(r / 1e3)),
"-a",
String(o)
], {
timeoutMs: r + 3e3,
maxOutputBytes: {
stdout: 65536,
stderr: 16384
},
outputCapture: "tail",
env: {
LC_ALL: "C",
LANG: "C"
},
onOutputChunk: (e, t) => {
if (t !== "stdout") return true;
s = `${s}${e.toString("utf8")}`.slice(-65536);
if (isLocationDisabledOutput(s)) return false;
const n = [...s.matchAll(/Timestamp:\s*.*seconds since the Epoch\)/gu)].length;
if (n === c) return true;
c = n;
return parseLocationOutput(s, a) === null;
}
});
if (isLocationDisabledOutput(`${l.stdout}\n${l.stderr}\n${s}`)) throw new Error("LOCATION_DISABLED: GeoClue location services are disabled");
const u = parseLocationOutput(`${l.stdout}\n${s}`, a);
if (!u) {
if (l.termination === "timeout" || l.code === 0) throw new Error("LOCATION_TIMEOUT: no fix in time");
throw new Error(`LOCATION_UNAVAILABLE: ${formatToolError(l)}`);
}
return JSON.stringify({
...u,
isPrecise: u.accuracyMeters <= 100,
source: "unknown"
});
}
}
];
}
//#endregion
//#region extensions/linux-node/index.ts
var linux_node_default = definePluginEntry({
id: "linux-node",
name: "Linux Node",
description: "Desktop notifications, camera capture, and location for Linux node hosts.",
configSchema: createLinuxNodePluginConfigSchema,
register(e) {
const t = resolveLinuxNodePluginConfig(e.pluginConfig);
for (const n of createLinuxNodeCommands(t)) e.registerNodeHostCommand(n);
e.registerNodeInvokePolicy({
commands: ["camera.list", "location.get"],
defaultPlatforms: ["linux"],
handle: async (e) => await e.invokeNode()
});
e.registerNodeInvokePolicy({
commands: ["camera.snap", "camera.clip"],
dangerous: true,
handle: async (e) => await e.invokeNode()
});
}
});
//#endregion
export { linux_node_default as default };