openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
226 lines (225 loc) • 6.28 kB
JavaScript
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import "./string-coerce-runtime-BwAZZDf5.mjs";
import { a as createDeferred } from "./extension-shared-CJ4teJ7p.mjs";
import { t as createClaudeCliProcessOwner } from "./cli-process-BDDutlIz.mjs";
import { randomUUID } from "node:crypto";
//#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 };