openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
494 lines (493 loc) • 15.5 kB
JavaScript
import { i as isStandaloneRuntimeExecutable, s as resolveOpenClawCliInvocation } from "./cli-invocation-ZSPsKRWa.mjs";
import { l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs";
import { r as signalProcessTree, t as killProcessTree } from "./kill-tree-DlMFq2XA.mjs";
import { n as sanitizeTerminalText } from "./safe-text-C80HAQ2e.mjs";
import { r as isPathInside } from "./path-guards-TIjxtj6H.mjs";
import { t as settlesWithin } from "./settle-within-Bj8A0Tzk.mjs";
import { r as resolveExternalPackageRuntimeEntrypointUrl } from "./runtime-process-url-CoHTemu-.mjs";
import { r as readTrimmedStringAlias } from "./string-readers-BtMVaphq.mjs";
import { a as omitEnvKeysCaseInsensitive, r as listKnownProviderAuthEnvVarNamesCore } from "./provider-env-vars-DPvuIf4v.mjs";
import { r as resolveOpenClawCliEntryPath } from "./openclaw-cli-invocation-CiQvieV9.mjs";
import { t as ensureOpenClawCliOnPath } from "./path-env-BdB9UQFN.mjs";
import { L as isKnownCoreToolId } from "./tool-catalog-C1ALpCJD.mjs";
import { n as isMutatingToolCall } from "./tool-mutation-BBJdXAL6.mjs";
import { a as resolveWindowsSpawnProgram, r as materializeWindowsSpawnProgram } from "./windows-spawn-BcHMKZuG.mjs";
import fs from "node:fs";
import { fileURLToPath } from "node:url";
import path from "node:path";
import { homedir } from "node:os";
import { spawn } from "node:child_process";
import { trySafeFileURLToPath } from "@openclaw/fs-safe/advanced";
import { once } from "node:events";
import { Readable, Writable } from "node:stream";
import * as readline$1 from "node:readline";
import { ClientSideConnection, PROTOCOL_VERSION, ndJsonStream } from "@agentclientprotocol/sdk";
//#region src/acp/approval-classifier.ts
const SAFE_SEARCH_TOOL_IDS = /* @__PURE__ */ new Set([
"search",
"web_search",
"memory_search"
]);
const TRUSTED_SAFE_TOOL_ALIASES = /* @__PURE__ */ new Set(["search"]);
const EXEC_CAPABLE_TOOL_IDS = /* @__PURE__ */ new Set([
"exec",
"spawn",
"shell",
"bash",
"process",
"code_execution",
"nodes"
]);
const CONTROL_PLANE_TOOL_IDS = /* @__PURE__ */ new Set([
"cron",
"gateway",
"sessions_spawn",
"sessions_send",
"session_status"
]);
function readFirstStringValue(e, t) {
return e ? readTrimmedStringAlias(e, t) : void 0;
}
function normalizeToolPolicyName(e) {
const t = normalizeLowercaseStringOrEmpty(e);
if (!t || t.length > 128) return;
return /^[a-z0-9._-]+$/.test(t) ? t : void 0;
}
function resolveToolNameForPermission(e) {
const t = readFirstStringValue(asOptionalRecord(e?.["_meta"]), [
"toolName",
"tool_name",
"name"
]);
const n = readFirstStringValue(asOptionalRecord(e?.rawInput), [
"tool",
"toolName",
"tool_name",
"name"
]);
const r = t ? normalizeToolPolicyName(t) : void 0;
const i = n ? normalizeToolPolicyName(n) : void 0;
const a = e?.title ? normalizeOptionalString(e.title.split(":", 1)[0]) : void 0;
const o = a ? normalizeToolPolicyName(a) : void 0;
if (t && !r || n && !i) return;
if (new Set([
r,
o,
i
].filter(Boolean)).size > 1) return;
return r ?? o ?? i;
}
function extractPathFromToolTitle(e, t) {
if (!e) return;
const n = e.indexOf(":");
if (n < 0) return;
const r = e.slice(n + 1).trim();
if (!r) return;
const i = t === "read" ? r.match(/(?:^|,\s*)(?:path|file_path|filePath)\s*:\s*([^,]+)/) : r.match(/^(?:path|file_path|filePath)\s*:\s*([^,]+)/);
if (i?.[1]) return i[1].trim();
return t === "read" ? r : void 0;
}
function isToolPathScopedToCwd(e, t) {
let n = e.trim();
if (!n) return false;
if (/^file:/i.test(n)) {
n = trySafeFileURLToPath(n) ?? "";
if (!n) return false;
}
if (n === "~") n = homedir();
else if (n.startsWith("~/")) n = path.join(homedir(), n.slice(2));
const r = path.isAbsolute(n) ? path.normalize(n) : path.resolve(t, n);
return isPathInside(path.resolve(t), r);
}
/** Resolves the ACP approval class for one tool call, failing closed on spoofed tool identity. */
function classifyAcpToolApproval(e) {
const t = resolveToolNameForPermission(e.toolCall);
if (!t) return {
toolName: void 0,
approvalClass: "unknown",
autoApprove: false
};
if ((isKnownCoreToolId(t) || TRUSTED_SAFE_TOOL_ALIASES.has(t)) && (t === "read" || SAFE_SEARCH_TOOL_IDS.has(t))) {
const n = t !== "read" && Array.isArray(e.toolCall?.locations) ? e.toolCall.locations : [];
const r = [
"path",
"file_path",
"filePath"
];
const i = [
readFirstStringValue(asOptionalRecord(e.toolCall?.rawInput), r),
extractPathFromToolTitle(e.toolCall?.title ?? void 0, t),
...n.map((e) => readFirstStringValue(asOptionalRecord(e), r))
].filter((e) => e !== void 0);
const a = (t !== "read" || i.length > 0) && i.every((t) => isToolPathScopedToCwd(t, e.cwd));
return {
toolName: t,
approvalClass: a ? t === "read" ? "readonly_scoped" : "readonly_search" : "other",
autoApprove: a
};
}
if (EXEC_CAPABLE_TOOL_IDS.has(t)) return {
toolName: t,
approvalClass: "exec_capable",
autoApprove: false
};
if (CONTROL_PLANE_TOOL_IDS.has(t)) return {
toolName: t,
approvalClass: "control_plane",
autoApprove: false
};
if (isMutatingToolCall(t, e.toolCall?.rawInput)) return {
toolName: t,
approvalClass: "mutating",
autoApprove: false
};
return {
toolName: t,
approvalClass: "other",
autoApprove: false
};
}
//#endregion
//#region src/acp/client.ts
const ACP_SERVER_KILL_GRACE_MS = 1e3;
const ACP_SERVER_FORCE_KILL_TIMEOUT_MS = 1e3;
function hasChildExited(e) {
return e.exitCode !== null || e.signalCode !== null;
}
async function waitForChildExit(e, t) {
if (!hasChildExited(e)) await once(e, "exit", { signal: AbortSignal.timeout(t) }).catch(() => {});
return hasChildExited(e);
}
async function terminateAcpServer(e) {
if (hasChildExited(e)) return;
if (e.pid) killProcessTree(e.pid, {
detached: false,
graceMs: ACP_SERVER_KILL_GRACE_MS
});
else e.kill("SIGTERM");
if (await waitForChildExit(e, 2e3)) return;
if (e.pid) signalProcessTree(e.pid, "SIGKILL", { detached: false });
else e.kill("SIGKILL");
await waitForChildExit(e, ACP_SERVER_FORCE_KILL_TIMEOUT_MS);
}
function resolveSelfEntryPath() {
try {
const e = fileURLToPath(import.meta.url);
const t = path.resolve(path.dirname(e), "..", "..");
const n = fileURLToPath(resolveExternalPackageRuntimeEntrypointUrl("gatewayEntry", t));
if (path.basename(path.dirname(path.dirname(e))) === "dist" && fs.existsSync(n)) return n;
} catch {}
const e = resolveOpenClawCliEntryPath(process.argv[1]);
if (e) return path.isAbsolute(e) ? e : path.resolve(process.cwd(), e);
return null;
}
function printSessionUpdate(e) {
const t = e.update;
switch (t.sessionUpdate) {
case "agent_message_chunk":
if (t.content?.type === "text") process.stdout.write(t.content.text);
return;
case "tool_call":
console.log(`\n[tool] ${t.title} (${t.status})`);
return;
case "tool_call_update":
if (t.status) console.log(`[tool update] ${t.toolCallId}: ${t.status}`);
return;
case "available_commands_update": {
const e = t.availableCommands?.map((e) => `/${e.name}`).join(" ");
if (e) console.log(`\n[commands] ${e}`);
}
}
}
function promptUserPermission(e, t, n) {
if (n?.aborted) return Promise.resolve(false);
if (!process.stdin.isTTY || !process.stderr.isTTY) {
console.error(`[permission denied] ${e ?? "unknown"}: non-interactive terminal`);
return Promise.resolve(false);
}
return new Promise((r) => {
let i = false;
const a = readline$1.createInterface({
input: process.stdin,
output: process.stderr
});
const finish = (e) => {
if (i) return;
i = true;
clearTimeout(o);
n?.removeEventListener("abort", onClose);
a.off("close", onClose);
a.close();
r(e);
};
const onClose = () => finish(false);
a.once("close", onClose);
n?.addEventListener("abort", onClose, { once: true });
const o = setTimeout(() => {
console.error(`\n[permission timeout] denied: ${e ?? "unknown"}`);
finish(false);
}, 3e4);
const s = t ? e ? `${t} (${e})` : t : e ?? "unknown tool";
a.question(`\n[permission] Allow "${s}"? (y/N) `, (t) => {
const n = normalizeLowercaseStringOrEmpty(t) === "y";
console.error(`[permission ${n ? "approved" : "denied"}] ${e ?? "unknown"}`);
finish(n);
});
});
}
async function createAcpClient(e = {}) {
const t = e.cwd ?? process.cwd();
const n = Boolean(e.verbose) ? (e) => console.error(`[acp-client] ${e}`) : () => {};
ensureOpenClawCliOnPath();
const r = ["acp", ...e.serverArgs ?? []];
if (e.serverVerbose && !r.includes("--verbose") && !r.includes("-v")) r.push("--verbose");
const i = isStandaloneRuntimeExecutable();
const a = i ? void 0 : resolveSelfEntryPath();
const o = i || a ? resolveOpenClawCliInvocation({
entryPath: a,
args: r,
execArgv: []
}) : {
command: "openclaw",
args: r
};
const s = o.command;
const c = o.args;
const l = e.serverCommand ?? s;
const u = e.serverCommand ? r : c;
const { getActiveSkillEnvKeysCore: d } = await import("./env-overrides-DgXdgsin.mjs");
const f = normalizeOptionalString(l);
const p = !f || f === normalizeOptionalString(s) && u.length === c.length && u.every((e, t) => e === c[t]);
const m = new Set(d());
if (p) for (const e of listKnownProviderAuthEnvVarNamesCore()) m.add(e);
const h = omitEnvKeysCaseInsensitive(process.env, m);
h.OPENCLAW_SHELL = "acp-client";
const g = resolveWindowsSpawnProgram({
command: l,
platform: process.platform,
env: h,
execPath: process.execPath,
packageName: "openclaw"
});
const _ = materializeWindowsSpawnProgram(g, u);
n(`spawning: ${_.command} ${_.argv.join(" ")}`);
const v = spawn(_.command, _.argv, {
stdio: [
"pipe",
"pipe",
"inherit"
],
cwd: t,
env: h,
shell: _.shell,
windowsHide: _.windowsHide
});
const y = new AbortController();
const b = new Promise((e) => {
v.once("close", () => e());
});
v.on("error", (e) => {
n(`agent error: ${String(e)}`);
});
let x;
let S;
const terminate = () => S ??= terminateAcpServer(v);
const interruptStartup = (e) => {
x ??= e;
y.abort();
terminate().catch(() => {});
};
const onStartupSigint = () => interruptStartup(130);
const onStartupSigterm = () => interruptStartup(143);
process.on("SIGINT", onStartupSigint);
process.on("SIGTERM", onStartupSigterm);
try {
if (!v.stdin || !v.stdout) throw new Error("Failed to create ACP stdio pipes");
const e = Writable.toWeb(v.stdin);
const r = Readable.toWeb(v.stdout);
const i = ndJsonStream(e, r);
const a = new ClientSideConnection(() => ({
sessionUpdate: async (e) => {
printSessionUpdate(e);
},
requestPermission: async (e) => {
if (y.signal.aborted) return { outcome: { outcome: "cancelled" } };
const n = e.options ?? [];
const r = sanitizeTerminalText(e.toolCall?.title ?? "tool");
const i = classifyAcpToolApproval({
toolCall: e.toolCall,
cwd: t
});
const a = i.toolName;
const o = !a && i.approvalClass === "unknown" ? void 0 : i.approvalClass;
if (n.length === 0) {
console.error(`[permission cancelled] ${a ?? "unknown"}: no options available`);
return { outcome: { outcome: "cancelled" } };
}
const s = n.find((e) => e.kind === "allow_once") ?? n.find((e) => e.kind === "allow_always");
const c = n.find((e) => e.kind === "reject_once") ?? n.find((e) => e.kind === "reject_always");
if (i.autoApprove) {
if (!s) {
console.error(`[permission cancelled] ${a ?? "unknown"}: missing allow option`);
return { outcome: { outcome: "cancelled" } };
}
console.error(`[permission auto-approved] ${a} (${o ?? "unknown"})`);
return { outcome: {
outcome: "selected",
optionId: s.optionId
} };
}
console.error(`\n[permission requested] ${r}${a ? ` (${a})` : ""}${o ? ` [${o}]` : ""}`);
const l = await promptUserPermission(a, r, y.signal);
if (y.signal.aborted) return { outcome: { outcome: "cancelled" } };
if (l && s) return { outcome: {
outcome: "selected",
optionId: s.optionId
} };
if (!l && c) return { outcome: {
outcome: "selected",
optionId: c.optionId
} };
console.error(`[permission cancelled] ${a ?? "unknown"}: missing ${l ? "allow" : "reject"} option`);
return { outcome: { outcome: "cancelled" } };
}
}), i);
a.closed.then(() => y.abort());
n("initializing");
await a.initialize({
protocolVersion: PROTOCOL_VERSION,
clientCapabilities: {
fs: {
readTextFile: true,
writeTextFile: true
},
terminal: true
},
clientInfo: {
name: "openclaw-acp-client",
version: "1.0.0"
}
});
if (x !== void 0) y.signal.throwIfAborted();
n("creating session");
const o = await a.newSession({
cwd: t,
mcpServers: []
});
if (x !== void 0) y.signal.throwIfAborted();
return {
client: a,
agent: v,
sessionId: o.sessionId,
closed: b,
cancelPermissions: () => y.abort()
};
} catch (e) {
y.abort();
await terminate();
await b;
if (x !== void 0) return { exitCode: x };
throw e;
} finally {
process.off("SIGINT", onStartupSigint);
process.off("SIGTERM", onStartupSigterm);
}
}
/** Runs until the interactive session and its owned server have closed. */
async function runAcpClientInteractive(e = {}) {
const t = await createAcpClient(e);
if (t.exitCode !== void 0) return t.exitCode;
const { client: n, agent: r, sessionId: i, closed: a, cancelPermissions: o } = t;
const s = readline$1.createInterface({
input: process.stdin,
output: process.stdout
});
let c = false;
let l;
let u;
let d;
const quit = () => {
if (l) return l;
c = true;
l = Promise.resolve().then(async () => {
o();
s.close();
process.stdin.pause();
if (!hasChildExited(r)) {
const e = u;
if (e) {
await settlesWithin(n.cancel({ sessionId: i }).catch(() => {}), ACP_SERVER_KILL_GRACE_MS);
await settlesWithin(e, ACP_SERVER_KILL_GRACE_MS);
}
r.stdin?.end();
if (!await waitForChildExit(r, ACP_SERVER_KILL_GRACE_MS)) await terminateAcpServer(r);
}
await a;
});
return l;
};
const onInputClose = () => {
if (!c) quit();
};
const onSigint = () => {
d = 130;
quit();
};
const onSigterm = () => {
d = 143;
quit();
};
s.once("close", onInputClose);
process.on("SIGINT", onSigint);
process.on("SIGTERM", onSigterm);
const prompt = () => {
if (c || hasChildExited(r)) return;
s.question("> ", (e) => {
const t = e.trim();
if (!t) {
prompt();
return;
}
if (t === "exit" || t === "quit") {
quit();
return;
}
u = (async () => {
try {
const e = await n.prompt({
sessionId: i,
prompt: [{
type: "text",
text: t
}]
});
console.log(`\n[${e.stopReason}]\n`);
} catch (e) {
console.error(`\n[error] ${String(e)}\n`);
}
u = void 0;
prompt();
})();
});
};
try {
console.log("OpenClaw ACP client");
console.log(`Session: ${i}`);
console.log("Type a prompt, or \"exit\" to quit.\n");
prompt();
await a;
const e = r.exitCode ?? (c ? 0 : 1);
console.log(`\nAgent exited with ${r.signalCode ? `signal ${r.signalCode}` : `code ${r.exitCode}`}`);
return e !== 0 ? e : d ?? e;
} finally {
await quit();
await n.closed;
await u;
s.off("close", onInputClose);
process.off("SIGINT", onSigint);
process.off("SIGTERM", onSigterm);
}
}
//#endregion
export { runAcpClientInteractive };