openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
452 lines (451 loc) • 17 kB
JavaScript
import { l as isRecord } from "../../record-coerce-CVPuDqcc.mjs";
import { p as toErrorObject } from "../../error-coercion-hDrHOSGy.mjs";
import "../../string-coerce-runtime-BwAZZDf5.mjs";
import { a as createDeferred } from "../../extension-shared-CJ4teJ7p.mjs";
import "../../error-runtime-BM740gJj.mjs";
import { n as hasClaudeRawToolInvocation } from "../../cli-output-5KUUOa7i.mjs";
import { t as createClaudeCliTransport } from "../../cli-transport-Dkvuc_UC.mjs";
import { t as prepareClaudeCliTransportArgs } from "../../cli-runtime-args-HI1_Bnnm.mjs";
import { n as promptContextHookSlot, r as promptContextHookValue, t as PROMPT_CONTEXT_HOOK_IDS } from "../../cli-runtime-prompt-context-B88sTLIe.mjs";
import { t as createClaudeTurnStatus } from "../../cli-runtime-status-98qohGri.mjs";
import { n as recordRunningDescendants, r as recordTaskOwnership, t as readReplayedTaskId } from "../../cli-runtime-tasks-B7HvDLUy.mjs";
import { t as createClaudeCliUserInputAuthorizer } from "../../cli-user-input-D2zxrhUJ.mjs";
import { randomUUID } from "node:crypto";
import { once } from "node:events";
import { PassThrough } from "node:stream";
//#region extensions/anthropic/cli.runtime.ts
const IDLE_TIMEOUT_MS = 6e5;
const sessions = /* @__PURE__ */ new WeakMap();
function activeTurn(e) {
const t = e.currentTurn;
if (!t || t.interrupted || t.controller.signal.aborted || t.context.abortSignal?.aborted) return;
if (e.hasInputLifecycle && !t.inputStarted) return;
try {
t.context.assertCurrent?.();
return t;
} catch {
return;
}
}
function privateInputHolds(e) {
try {
e.context.assertPrivateInputCurrent?.();
return true;
} catch {
return false;
}
}
function carriesTurnContext(e, t) {
return promptContextHookSlot(e.callback_id) >= 0 && isRecord(t) && isRecord(t.hookSpecificOutput) && t.hookSpecificOutput.additionalContext !== void 0;
}
async function authorizeTool(e, t, n) {
const r = activeTurn(e);
const { input: i, tool_name: a } = t;
if (!r || n.aborted || typeof a !== "string" || !isRecord(i)) return {
behavior: "deny",
message: "The OpenClaw run or native tool input is no longer valid."
};
const o = typeof t.tool_use_id === "string" ? t.tool_use_id : void 0;
const s = AbortSignal.any([n, r.controller.signal]);
try {
const n = a === "AskUserQuestion" ? await r.userInput.authorize({
input: i,
signal: s,
toolUseId: o
}) : await r.context.requestToolPermission({
toolName: a,
toolInput: i,
cwd: typeof t.cwd === "string" ? t.cwd : void 0,
toolCallId: o,
abortSignal: s
});
if (activeTurn(e) !== r || s.aborted) return {
behavior: "deny",
message: "The OpenClaw run is no longer active."
};
if (n.behavior === "allow" && a === "Bash" && o && n.updatedInput.run_in_background !== true) r.foregroundBashToolUseIds.add(o);
return n;
} catch {
return {
behavior: "deny",
message: "OpenClaw could not authorize this tool call."
};
}
}
function resolvePromptContext(e, t) {
if (e.promptInputUuid !== e.inputUuid) return e.injectedInputs.get(e.promptInputUuid)?.promptContext;
const n = [...e.injectedInputs].find(([, e]) => e.text === t);
if (!n) return e.context.promptContext;
e.promptInputUuid = n[0];
return n[1].promptContext;
}
async function handleRequest(e, t, n) {
if (t.subtype === "can_use_tool") return {
...await authorizeTool(e, t, n),
toolUseID: t.tool_use_id
};
if (t.subtype !== "hook_callback" || !isRecord(t.input)) throw new Error("Unsupported Claude CLI control request.");
const r = t.input;
const i = activeTurn(e);
const a = promptContextHookSlot(t.callback_id);
if (a >= 0 && r.hook_event_name === "UserPromptSubmit") {
if (!i || n.aborted) return {};
i.promptSubmitted = true;
const e = resolvePromptContext(i, r.prompt);
const t = promptContextHookValue(e, a);
return t ? { hookSpecificOutput: {
hookEventName: "UserPromptSubmit",
additionalContext: t
} } : {};
}
if (t.callback_id === "PreToolUse" && r.hook_event_name === "PreToolUse") {
if (i && !n.aborted && typeof r.tool_name === "string" && r.tool_name.startsWith("mcp__openclaw__")) return { continue: true };
const a = await authorizeTool(e, {
tool_name: r.tool_name,
input: r.tool_input,
cwd: r.cwd,
tool_use_id: t.tool_use_id ?? r.tool_use_id
}, n);
return { hookSpecificOutput: {
hookEventName: "PreToolUse",
permissionDecision: a.behavior,
...a.behavior === "allow" ? { updatedInput: a.updatedInput } : { permissionDecisionReason: a.message }
} };
}
throw new Error("Unknown Claude CLI hook callback.");
}
function createUserInput(e, t, n, r = false) {
return {
type: "user",
message: {
role: "user",
content: t
},
parent_tool_use_id: null,
uuid: n,
...r ? { isSynthetic: true } : {},
...e.sessionId ? { session_id: e.sessionId } : {}
};
}
function rejectInjectedInputs(e, t) {
for (const n of e.injectedInputs.values()) n.started.reject(t);
}
function canInjectInput(e, t) {
return e.hasInputLifecycle && t.promptSubmitted && activeTurn(e) === t;
}
async function injectInput(e, t, n, r, i) {
const a = randomUUID();
const o = createDeferred();
o.promise.catch(() => {});
let s;
await r(() => {
if (!e.transport || !canInjectInput(e, t)) throw new Error("The Claude CLI turn cannot accept more input.");
t.injectedInputs.set(a, {
text: n,
started: o,
promptContext: i?.promptContext
});
t.submittedInputUuids.add(a);
s = e.transport.send(createUserInput(t.context, n, a, i?.promptOrigin === "host"));
s.catch(() => {});
});
if (!s) throw new Error("The host did not admit Claude CLI input.");
try {
await s;
} catch (e) {
t.injectedInputs.delete(a);
throw e;
}
await o.promise;
}
function closeSession(e, t) {
if (e.closed) return;
e.closed = true;
clearTimeout(e.idleTimer);
e.capability?.remove(e.handle);
const n = e.currentTurn;
e.currentTurn = void 0;
if (n) {
n.error = toErrorObject(t, "Claude CLI live session closed.");
rejectInjectedInputs(n, n.error);
n.controller.abort();
n.events.end();
}
e.transport?.close();
}
function completeTurn(e, t) {
const n = t.pendingBackgroundTaskIds.size > 0 || e.runningDescendants.size > 0;
e.currentTurn = void 0;
const r = t.injectedInputs.size > 0;
rejectInjectedInputs(t, /* @__PURE__ */ new Error("Claude CLI turn ended before its injected input completed."));
t.controller.abort();
t.events.end();
if (!e.capability || n || r) e.handle.close(n || r ? "abort" : "idle");
else {
e.idleTimer = setTimeout(() => e.handle.close("idle"), IDLE_TIMEOUT_MS);
e.idleTimer.unref();
}
}
async function emitHeldInterimResult(e) {
const t = e.heldResult;
if (!t) return;
e.heldResult = void 0;
if (!e.events.write({
...t,
openclaw_interim_result: true
})) await once(e.events, "drain", { signal: e.controller.signal });
}
async function acceptMessage(e, t) {
if (t.type === "system" && t.subtype === "init") {
const n = Array.isArray(t.mcp_servers) ? t.mcp_servers.find((e) => isRecord(e) && e.name === "openclaw") : void 0;
if (n && n.status !== "connected") {
closeSession(e, /* @__PURE__ */ new Error(`Claude Code started without the OpenClaw MCP server (status ${String(n.status)}). The CLI process was retired; retry the request to start a fresh process.`));
return;
}
e.hasInputLifecycle = Array.isArray(t.capabilities) && t.capabilities.includes("msg_lifecycle_v1");
}
const n = e.currentTurn;
let r;
let i = false;
if (t.type === "system") {
i = recordRunningDescendants(e.runningDescendants, t);
const a = n && (!e.hasInputLifecycle || n.inputStarted) ? n : void 0;
const o = a?.inputUuid ?? "";
if (t.subtype === "background_tasks_changed") {
if (Array.isArray(t.tasks)) for (const n of t.tasks) {
if (!isRecord(n)) continue;
const t = recordTaskOwnership(e, n, o);
const r = t ? e.runningDescendants.get(t) : void 0;
if (t && a && !a.interrupted && e.taskOwners.get(t) === a.inputUuid && (r === void 0 || a.pendingBackgroundTaskIds.has(r) || a.pendingBackgroundTaskIds.has(t)) && (n.task_type === "local_agent" || n.task_type === "local_workflow" || n.task_type === "local_bash" && a.foregroundTaskIds.has(t))) a.pendingBackgroundTaskIds.add(t);
}
} else r = recordTaskOwnership(e, t, o);
}
if (!n) return;
if (n.interrupted) return;
if (t.type === "command_lifecycle") {
if (t.state === "started" && t.command_uuid === n.inputUuid) n.inputStarted = true;
const r = typeof t.command_uuid === "string" ? t.command_uuid : void 0;
const i = r ? n.injectedInputs.get(r) : void 0;
if (i && r && t.state === "started") {
n.promptInputUuid = r;
i.started.resolve();
await emitHeldInterimResult(n);
} else if (i && r && (t.state === "completed" || t.state === "cancelled" || t.state === "discarded" || t.state === "refused")) {
if (t.state === "completed") i.started.resolve();
else i.started.reject(/* @__PURE__ */ new Error(`Claude CLI ${t.state} the injected input.`));
n.injectedInputs.delete(r);
if (n.promptInputUuid === r) n.promptInputUuid = n.inputUuid;
const a = n.heldResult;
if (a && n.injectedInputs.size === 0 && n.pendingBackgroundTaskIds.size === 0) {
n.heldResult = void 0;
if (!n.events.write(a)) await once(n.events, "drain", { signal: n.controller.signal });
completeTurn(e, n);
}
}
return;
}
if (e.hasInputLifecycle && !n.inputStarted && !(t.type === "system" && t.subtype === "init")) return;
if (t.type === "system" && t.subtype === "task_started" && r && e.taskOwners.get(r) === n.inputUuid) {
if (t.is_backgrounded === false) n.foregroundTaskIds.add(r);
if (typeof t.tool_use_id === "string" && n.foregroundBashToolUseIds.delete(t.tool_use_id) && t.is_backgrounded === true) n.pendingBackgroundTaskIds.add(r);
}
const a = readReplayedTaskId(t, n.submittedInputUuids);
if (a) {
n.pendingBackgroundTaskIds.delete(a);
n.foregroundTaskIds.delete(a);
n.taskNotifications.set(a, "replayed");
}
if (t.type === "system" && t.subtype === "task_notification" && r) {
if (t.status === "stopped" || i) {
n.pendingBackgroundTaskIds.delete(r);
n.foregroundTaskIds.delete(r);
n.taskNotifications.delete(r);
} else if (n.foregroundTaskIds.has(r) && !n.pendingBackgroundTaskIds.has(r)) n.foregroundTaskIds.delete(r);
else n.taskNotifications.set(r, "queued");
}
let o = false;
let s = false;
if (t.type === "result") {
const r = t.is_error === true || typeof t.subtype === "string" && t.subtype.startsWith("error") || typeof t.result === "string" && hasClaudeRawToolInvocation(t.result);
const i = isRecord(t.origin) ? t.origin : void 0;
const a = i?.kind === "task-notification" && i.subkind === void 0;
const c = a && typeof i?.runId === "string" ? e.taskRuns.get(i.runId) : void 0;
const l = a ? c ?? n.taskNotifications.keys().next().value : void 0;
const u = l !== void 0 && e.taskOwners.get(l) !== n.inputUuid && (!r || c !== void 0);
if (a && t.subtype === "success" && !r && l) {
n.taskNotifications.delete(l);
n.pendingBackgroundTaskIds.delete(l);
n.foregroundTaskIds.delete(l);
}
const d = n.sawTerminalResult && a && t.num_turns === 0 && t.result === "" && t.stop_reason === null && t.terminal_reason === void 0;
if (!u) {
await emitHeldInterimResult(n);
for (const [e, t] of n.taskNotifications) if (t === "replayed") n.taskNotifications.delete(e);
n.sawTerminalResult = true;
o = n.pendingBackgroundTaskIds.size === 0 && !d || r;
s = o && !r && n.injectedInputs.size > 0;
}
}
if (s) {
n.heldResult = t;
return;
}
const c = t.type === "result" && !o ? {
...t,
openclaw_interim_result: true
} : t;
if (!n.events.write(c)) await once(n.events, "drain", { signal: n.controller.signal });
if (o) completeTurn(e, n);
}
function createSession(e) {
const t = {
capability: e,
hasInputLifecycle: false,
closed: false,
taskOwners: /* @__PURE__ */ new Map(),
taskRuns: /* @__PURE__ */ new Map(),
runningDescendants: /* @__PURE__ */ new Map(),
handle: {
generation: randomUUID(),
fingerprint: e?.fingerprint ?? randomUUID(),
isIdle: () => !t.closed && !t.currentTurn,
close: (e, n) => closeSession(t, n),
waitForExit: async () => {
await (t.transport ?? await t.transportStartup)?.waitForExit();
}
}
};
sessions.set(t.handle, t);
e?.register(t.handle);
return t;
}
async function* executeClaudeCli(e, t) {
e.assertCurrent?.();
e.abortSignal?.throwIfAborted();
const n = e.liveSession;
const r = n?.current();
const i = r && r.fingerprint === n?.fingerprint ? sessions.get(r) : void 0;
if (!i && n) await n.restart();
e.assertCurrent?.();
const a = i ?? createSession(n);
a.capability = n;
if (a.closed || a.currentTurn) throw new Error("Claude CLI live session is closed or already handling another turn.");
clearTimeout(a.idleTimer);
const o = randomUUID();
const s = {
context: e,
controller: new AbortController(),
userInput: createClaudeCliUserInputAuthorizer(e),
events: new PassThrough({ objectMode: true }),
inputUuid: o,
submittedInputUuids: /* @__PURE__ */ new Set([o]),
inputStarted: false,
promptSubmitted: false,
promptInputUuid: o,
sawTerminalResult: false,
interrupted: false,
foregroundTaskIds: /* @__PURE__ */ new Set(),
foregroundBashToolUseIds: /* @__PURE__ */ new Set(),
pendingBackgroundTaskIds: /* @__PURE__ */ new Set(),
injectedInputs: /* @__PURE__ */ new Map(),
taskNotifications: /* @__PURE__ */ new Map()
};
a.currentTurn = s;
const abort = () => a.handle.close("abort", e.abortSignal?.reason);
e.abortSignal?.addEventListener("abort", abort, { once: true });
let c;
try {
c = (async () => {
e.abortSignal?.throwIfAborted();
n?.activate(a.handle);
let r = a.transport;
if (!r) {
const { args: n, excludeDynamicSections: i } = prepareClaudeCliTransportArgs(e);
a.transportStartup = createClaudeCliTransport({
context: e,
args: n,
secretInput: t,
currentContext: () => a.currentTurn?.context,
initialize: {
systemPrompt: e.systemPrompt,
systemPromptSnapshot: false,
excludeDynamicSections: i,
hooks: {
UserPromptSubmit: [{ hookCallbackIds: PROMPT_CONTEXT_HOOK_IDS }],
PreToolUse: [{ hookCallbackIds: ["PreToolUse"] }]
}
},
onMessage: (e) => acceptMessage(a, e),
onRequest: async (e, t) => {
if (e.subtype === "elicitation") return () => ({ action: "decline" });
const n = activeTurn(a);
const r = await handleRequest(a, e, t);
return () => {
if (n && activeTurn(a) === n && !t.aborted) return carriesTurnContext(e, r) && !privateInputHolds(n) ? {} : r;
const i = "The OpenClaw run is no longer active.";
if (e.subtype === "can_use_tool") return {
behavior: "deny",
message: i,
toolUseID: e.tool_use_id
};
return e.callback_id === "PreToolUse" ? { hookSpecificOutput: {
hookEventName: "PreToolUse",
permissionDecision: "deny",
permissionDecisionReason: i
} } : {};
};
},
onError: (e) => a.handle.close("abort", e)
}).then((e) => {
a.transport = e;
if (a.closed) e.close();
return e;
});
r = await a.transportStartup;
if (a.closed) throw s.error ?? /* @__PURE__ */ new Error("Claude CLI closed during startup.");
await r.initialize();
}
e.assertCurrent?.();
e.assertPrivateInputCurrent?.();
if (a.closed || a.currentTurn !== s) throw s.error ?? /* @__PURE__ */ new Error("Claude CLI closed before its prompt was accepted.");
e.registerTurnStatus?.(createClaudeTurnStatus(e, a, s));
e.registerTurnInterrupt?.({ async interrupt() {
e.assertCurrent?.();
if (a.currentTurn !== s && s.sawTerminalResult) return;
if (a.closed || a.currentTurn !== s || s.controller.signal.aborted) throw new Error("The Claude CLI turn is no longer active.");
s.interrupted = true;
s.sawTerminalResult = true;
if (!s.events.write({
type: "result",
subtype: "success",
is_error: false,
result: ""
})) await once(s.events, "drain", { signal: s.controller.signal });
completeTurn(a, s);
a.handle.close("idle");
await a.handle.waitForExit();
} });
const i = e.promptOrigin === "host";
await r.send(createUserInput(e, e.prompt, s.inputUuid, i));
e.registerMessageInjection?.({
isAvailable: () => canInjectInput(a, s),
queueMessage: (e, t, n) => injectInput(a, s, e, t, n)
});
})().catch((e) => a.handle.close("abort", e));
for await (const e of s.events) yield e;
await c;
if (s.error) throw s.error;
if (!s.sawTerminalResult) throw new Error("Claude CLI exited without a terminal result.");
} catch (e) {
a.handle.close("abort", e);
throw s.error ?? e;
} finally {
s.controller.abort();
e.abortSignal?.removeEventListener("abort", abort);
if (a.currentTurn === s) a.handle.close("abort");
await c;
if (a.closed) await a.handle.waitForExit();
}
}
//#endregion
export { executeClaudeCli };