openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
315 lines (314 loc) • 8.84 kB
JavaScript
import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
import { createOwnedStdioProcess } from "openclaw/plugin-sdk/process-runtime";
import { randomUUID } from "node:crypto";
import { createDeferred } from "openclaw/plugin-sdk/extension-shared";
import { attachErrorDiagnostic } from "openclaw/plugin-sdk/error-runtime";
import { redactSensitiveFieldValue, redactSensitiveText } from "openclaw/plugin-sdk/logging-core";
import { sliceUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
import { raceWithTimeout } from "openclaw/plugin-sdk/time-runtime";
//#region extensions/anthropic/cli-process.ts
const STDERR_CAPTURE_CHARS = 8192;
const STDERR_DRAIN_GRACE_MS = 200;
/** Owns process-wide diagnostics and the credentials needed to redact warm turns. */
function createClaudeCliProcessOwner(e, t) {
const assertCurrent = () => {
const t = e();
if (!t) throw new Error("Claude CLI run is no longer active.");
t.assertCurrent?.();
};
assertCurrent();
const n = t?.createData();
let r = {};
let i;
let a = false;
let o = false;
let s = "";
let c = false;
const observeStderr = (e) => {
i = e;
e.onExit(() => {
a = true;
});
e.onStderr((e) => {
let t = e;
if (o) return;
if (c) {
const e = t.indexOf("\n");
if (e < 0) return;
t = t.slice(e + 1);
c = false;
}
s += t;
if (s.length > STDERR_CAPTURE_CHARS) {
const e = sliceUtf16Safe(s, -8192);
const t = e.indexOf("\n");
s = t < 0 ? "" : e.slice(t + 1);
c = t < 0;
}
});
};
return {
[Symbol.dispose]() {
o = true;
n?.fill(0);
r = {};
s = "";
},
spawn: async (e) => {
assertCurrent();
r = e.env;
const n = await createOwnedStdioProcess({
argv: [e.command, ...e.args],
argv0: e.argv0,
cwd: e.cwd,
env: e.env,
exactEnv: true,
abortSignal: e.signal,
assertCurrent,
secretInput: t,
terminateOnHostLoss: true,
stdoutConsumption: "awaited"
});
observeStderr(n);
return n;
},
async withDiagnostics(t) {
const c = e();
if (o || !c || c.abortSignal?.aborted) return t;
if (i && a) await raceWithTimeout(i.wait().catch(() => void 0), STDERR_DRAIN_GRACE_MS, () => void 0);
if (o || e() !== c || c.abortSignal?.aborted) return t;
let l = s;
const u = [r, c.env].flatMap((e) => Object.entries(e).flatMap(([e, t]) => t && redactSensitiveFieldValue(e, t, { mode: "tools" }) !== t ? [t] : []));
if (n) u.push(n.toString("utf8"));
for (const e of u.filter(Boolean)) for (const t of [
e,
encodeURIComponent(e),
JSON.stringify(e).slice(1, -1)
]) l = l.replaceAll(t, "[REDACTED]");
l = sliceUtf16Safe(redactSensitiveText(l, { mode: "tools" }), -2e3).trim();
if (l && t instanceof Error) attachErrorDiagnostic(t, `stderr (process-wide; may include earlier turns): ${l}`);
return t;
}
};
}
//#endregion
//#region extensions/anthropic/cli-transport.ts
const MAX_LINE_CHARS = 8388608;
const CLOSE_GRACE_MS = 500;
const KILL_GRACE_MS = 1e3;
/** One Claude Code subprocess and its bidirectional stream-json control channel. */
async function createClaudeCliTransport(e) {
const t = createClaudeCliProcessOwner(e.currentContext, e.secretInput);
let n;
try {
const r = { ...e.context.env };
delete r.NODE_OPTIONS;
delete r.DEBUG;
n = await t.spawn({
...e.context,
args: e.args,
env: r,
signal: e.context.abortSignal
});
} catch (e) {
t[Symbol.dispose]();
throw e;
}
const r = /* @__PURE__ */ new Map();
const i = randomUUID();
const { promise: a, resolve: o, reject: s } = createDeferred();
a.catch(() => {});
let c = false;
let l = false;
let u = false;
let d = false;
let f;
let p;
let m;
let h;
const { promise: g, resolve: _ } = createDeferred();
const terminate = () => {
u = true;
n.kill("SIGTERM");
h = setTimeout(() => {
n.kill("SIGKILL");
}, KILL_GRACE_MS);
h.unref();
};
const abortRequests = () => {
for (const e of r.values()) e.abort();
r.clear();
};
const beginShutdown = () => {
if (l) return;
l = true;
abortRequests();
if (process.platform === "win32" && !d) {
u = true;
n.kill("SIGKILL");
n.waitForExtinction?.().then(() => n.stdin?.end(), () => {});
} else n.stdin?.end();
if (process.platform !== "win32" && !d) {
m = setTimeout(terminate, CLOSE_GRACE_MS);
m.unref();
}
};
const close = () => {
if (c) return;
c = true;
s(/* @__PURE__ */ new Error("Claude CLI closed before initialization completed."));
abortRequests();
t[Symbol.dispose]();
beginShutdown();
};
const processExitError = () => f ?? /* @__PURE__ */ new Error("Claude CLI live session exited unexpectedly without a terminal result.");
const settleInputError = (r) => {
if (process.platform === "win32" || !isRecord(r) || r.code !== "EPIPE") return;
const i = e.currentContext();
p ??= Promise.resolve().then(async () => {
beginShutdown();
await Promise.race([g, n.waitForExtinction?.() ?? n.wait()]);
const e = i?.abortSignal?.aborted ? i.abortSignal.reason : u ? r : processExitError();
return t.withDiagnostics(e);
}).catch((e) => e).then((e) => i?.abortSignal?.aborted ? i.abortSignal.reason : e);
return p;
};
const fail = async (n) => {
if (c) return;
const r = await (p ?? t.withDiagnostics(n));
if (!c) {
s(r);
e.onError(r);
close();
}
};
const didExit = () => {
if (d) return;
d = true;
clearTimeout(m);
clearTimeout(h);
if (process.platform !== "win32" || !c) n.kill("SIGKILL");
_();
};
n.onExit((e, t) => {
if (e !== 0) f = /* @__PURE__ */ new Error(t ? `Claude Code process exited with signal ${t}` : `Claude Code process exited with code ${e}`);
didExit();
});
const send = (e) => {
if (p) return p.then((e) => {
throw e;
});
if (c || l) return Promise.reject(/* @__PURE__ */ new Error("Claude CLI control channel is closed."));
return new Promise((t, r) => {
n.stdin.write(`${JSON.stringify(e)}\n`, (e) => {
if (e) {
const t = settleInputError(e);
if (t) t.then(r, r);
else r(e);
} else t();
});
});
};
const dispatch = async (t, n) => {
if (r.has(t)) return;
const i = new AbortController();
r.set(t, i);
try {
let response;
try {
const r = await e.onRequest(n, i.signal);
response = () => ({
subtype: "success",
request_id: t,
response: r()
});
} catch {
response = () => ({
subtype: "error",
request_id: t,
error: "OpenClaw could not handle this Claude control request."
});
}
if (!c) await send({
type: "control_response",
response: response()
});
} finally {
if (r.get(t) === i) r.delete(t);
}
};
const acceptLine = async (t) => {
if (p || !t.trim()) return;
let n;
try {
n = JSON.parse(t);
} catch {
return;
}
if (!isRecord(n)) return;
if (n.type === "control_response") {
const e = n.response;
if (isRecord(e) && e.request_id === i) {
if (e.subtype === "success") o(isRecord(e.response) ? e.response : {});
else throw new Error("Claude CLI initialization failed.");
}
} else if (n.type === "control_request") {
if (typeof n.request_id !== "string" || !isRecord(n.request)) throw new Error("Claude CLI sent a malformed control request.");
dispatch(n.request_id, n.request).catch(fail);
} else if (n.type === "control_cancel_request") {
if (typeof n.request_id === "string") r.get(n.request_id)?.abort();
} else if (n.type !== "keep_alive") await e.onMessage(n);
};
const read = async () => {
let e = "";
await n.consumeStdout(async (t) => {
for (let n = 0; n < t.length;) {
const r = t.indexOf("\n", n);
const i = r < 0 ? t.length : r;
if (e.length + i - n > MAX_LINE_CHARS) throw new Error(`Claude CLI JSONL line exceeded ${MAX_LINE_CHARS} characters.`);
e += t.slice(n, i);
n = i + 1;
if (r >= 0) {
const t = e;
e = "";
await acceptLine(t);
}
}
});
if (e) await acceptLine(e);
await g;
if (!c) throw p ? await p : processExitError();
};
const v = read();
n.onError((e, t) => {
if (t === "process") f = e;
const n = t === "stdin" ? settleInputError(e) : void 0;
n ? n.then(fail) : fail(e);
});
v.catch(fail);
return {
close,
waitForExit: async () => {
const e = Promise.all([n.wait().catch(() => void 0), n.waitForExtinction?.()]).then(() => void 0, (e) => {
throw new Error("Claude CLI process cleanup could not be confirmed; retry the message. If it fails again, restart the Gateway.", { cause: e });
});
await Promise.race([g, e]);
await e;
n.dispose();
},
send,
async initialize() {
await send({
type: "control_request",
request_id: i,
request: {
subtype: "initialize",
...e.initialize
}
});
return await a;
}
};
}
//#endregion
export { createClaudeCliTransport as t };