openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
750 lines (749 loc) • 26.6 kB
JavaScript
import { t as createClaudeCliTransport } from "./cli-transport-JXX3vbiu.mjs";
import { n as hasClaudeRawToolInvocation } from "./cli-output-CjgZis4O.mjs";
import { isRecord, truncateUtf16Safe } from "openclaw/plugin-sdk/string-coerce-runtime";
import { once } from "node:events";
import { randomUUID } from "node:crypto";
import { createDeferred } from "openclaw/plugin-sdk/extension-shared";
import { toErrorObject } from "openclaw/plugin-sdk/error-runtime";
import { PassThrough } from "node:stream";
//#region extensions/anthropic/cli-runtime-args.ts
const PROTOCOL_FLAGS = /* @__PURE__ */ new Set([
"-p",
"--print",
"--verbose",
"--include-partial-messages",
"--replay-user-messages",
"--dangerously-skip-permissions",
"--allow-dangerously-skip-permissions"
]);
const PROTOCOL_VALUE_FLAGS = /* @__PURE__ */ new Set([
"--output-format",
"--input-format",
"--permission-prompt-tool",
"--permission-mode",
"--model",
"--session-id",
"--resume",
"-r",
"--append-system-prompt-file",
"--append-system-prompt",
"--system-prompt-file",
"--system-prompt"
]);
const TOOL_FLAGS = /* @__PURE__ */ new Set([
"--tools",
"--allowedTools",
"--allowed-tools"
]);
/** Keep prepared CLI arguments, replacing only transport and admission-owned policy. */
function prepareClaudeCliTransportArgs(e) {
const t = [];
const n = [];
let r;
let i = "user";
let a = false;
for (let o = 0; o < e.args.length; o += 1) {
const s = e.args[o];
const c = s.indexOf("=");
const l = c < 0 ? s : s.slice(0, c);
if (PROTOCOL_FLAGS.has(l)) continue;
if (l === "--exclude-dynamic-system-prompt-sections") {
a = true;
continue;
}
if (!PROTOCOL_VALUE_FLAGS.has(l) && !TOOL_FLAGS.has(l) && l !== "--setting-sources") {
t.push(s);
continue;
}
const u = c < 0 ? e.args[++o] : s.slice(c + 1);
if (u === void 0) throw new Error(`Claude CLI cannot preserve ${l} without its value.`);
if (PROTOCOL_VALUE_FLAGS.has(l)) continue;
if (l === "--setting-sources") {
if (u !== "" && u !== "user") throw new Error("Claude CLI settings must be limited to user settings.");
i = u;
continue;
}
const d = [u];
if (c < 0) while (o + 1 < e.args.length && !e.args[o + 1]?.startsWith("-")) d.push(e.args[++o]);
const f = d.flatMap((e) => e.split(",").map((e) => e.trim()).filter(Boolean));
if (l === "--tools") r = f;
else n.push(...f.filter((e) => e.startsWith("mcp__openclaw__")));
}
let o = [...new Set(n)];
if (e.toolAvailability) {
r = [...e.toolAvailability.native, ...e.toolAvailability.discovery ?? []];
o = e.toolAvailability.openClaw.map((e) => `mcp__openclaw__${e}`).filter((e) => n.includes(e) || n.includes("mcp__openclaw__*"));
}
t.push("--print", "--input-format", "stream-json", "--output-format", "stream-json", "--verbose", "--include-partial-messages", "--replay-user-messages", "--permission-prompt-tool", "stdio", "--permission-mode", "default", "--setting-sources", i, "--model", e.modelId);
if (r) t.push("--tools", r.join(","));
if (o.length) t.push("--allowedTools", o.join(","));
if (e.sessionId) t.push(e.useResume ? "--resume" : "--session-id", e.sessionId);
return {
args: t,
excludeDynamicSections: a
};
}
//#endregion
//#region extensions/anthropic/cli-runtime-prompt-context.ts
const HOOK_CONTEXT_MAX_CHARS = 1e4;
const PROMPT_CONTEXT_HOOK_IDS = Array.from({ length: 128 }, (e, t) => t === 0 ? "UserPromptSubmit" : `UserPromptSubmit:${t}`);
/** The prompt-context segment a UserPromptSubmit callback carries, or -1 for other callbacks. */
function promptContextHookSlot(e) {
return typeof e === "string" ? PROMPT_CONTEXT_HOOK_IDS.indexOf(e) : -1;
}
/** One callback's part of the turn's private context; empty when the context is shorter. */
function promptContextHookValue(e, t) {
const n = [e?.prependContext, e?.appendContext].filter(Boolean).join("\n\n");
if (n.length <= HOOK_CONTEXT_MAX_CHARS) return t === 0 ? n : "";
const r = JSON.stringify(n).slice(1, -1).replaceAll("<", "\\u003c");
for (let e = 0, n = 0;; e++) {
if (n === r.length) return "";
const i = `OpenClaw private context segment ${e + 1} (JSON string; concatenate decoded segments in order without separators, preserving original instruction/data labels):\n`;
let a = e === PROMPT_CONTEXT_HOOK_IDS.length - 1 ? r.length : Math.min(n + HOOK_CONTEXT_MAX_CHARS - i.length - 2, r.length);
const o = r.lastIndexOf("\\", a - 1);
if (o >= n && o >= a - 5) {
let e = o;
while (e > n && r[e - 1] === "\\") e--;
if ((o - e) % 2 === 0 && (o === a - 1 || r[o + 1] === "u" && o + 6 > a)) a = o;
}
const s = r.charCodeAt(a - 1);
if (a < r.length && s >= 55296 && s <= 56319) a--;
if (e === t) return `${i}"${r.slice(n, a)}"`;
n = a;
}
}
//#endregion
//#region extensions/anthropic/cli-runtime-status.ts
/** Local facts only: this adapter never writes to the native transport. */
function createClaudeTurnStatus(e, t, n) {
return { capture() {
const r = t.handle.generation;
const i = n.promptInputUuid;
const a = n.submittedInputUuids.size;
const o = n.inputStarted;
const isCurrent = () => {
e.assertCurrent?.();
return !e.abortSignal?.aborted && !n.interrupted && t.handle.generation === r && n.promptInputUuid === i && n.submittedInputUuids.size === a && n.inputStarted === o && (t.currentTurn === n || t.closed && n.error !== void 0);
};
if (!isCurrent()) return;
return {
isCurrent,
async assess({ signal: e }) {
e.throwIfAborted();
if (!isCurrent()) return {
state: "unknown",
basis: "status_unsupported"
};
if (t.closed) return {
state: "closed",
basis: "transport_closed"
};
return {
state: "unknown",
basis: t.hasInputLifecycle && !o ? "status_unsupported" : "process_present"
};
}
};
} };
}
//#endregion
//#region extensions/anthropic/cli-runtime-tasks.ts
function readReplayedTaskId(e, t) {
if (e.type !== "user" || e.isReplay !== true || e.parent_tool_use_id !== null || typeof e.uuid === "string" && t.has(e.uuid) || !isRecord(e.message)) return;
if (e.origin !== void 0 && (!isRecord(e.origin) || e.origin.kind !== "task-notification" || e.origin.subkind !== void 0)) return;
const n = e.message.content;
const r = Array.isArray(n) ? n[0] : void 0;
const i = typeof n === "string" ? n : isRecord(r) && r.type === "text" && typeof r.text === "string" ? r.text : "";
return /^<task-notification>\s*<task-id>([^<]+)<\/task-id>/u.exec(i)?.[1];
}
function recordTaskOwnership(e, t, n) {
const r = t.task_id;
if (typeof r !== "string" || !r) return;
const i = e.taskOwners.get(r);
const a = t.owned_by_subagent === true ? false : i ?? n;
if (a !== i) e.taskOwners.set(r, a);
if (typeof t.run_id === "string" && t.run_id) e.taskRuns.set(t.run_id, r);
return a === false ? void 0 : r;
}
/** Agents and workflows make their own tool calls; subagent-owned work can resume its Agent. */
function isDescendantTask(e) {
return e.task_type === "local_agent" || e.task_type === "local_workflow" || e.owned_by_subagent === true || typeof e.parent_task_id === "string";
}
function recordRunningDescendants(e, t) {
const n = t.subtype === "task_started" ? [t] : t.subtype === "background_tasks_changed" && Array.isArray(t.tasks) ? t.tasks.filter(isRecord) : [];
for (const t of n) if (typeof t.task_id === "string" && isDescendantTask(t)) e.set(t.task_id, typeof t.parent_task_id === "string" ? t.parent_task_id : e.get(t.task_id));
if (t.subtype === "task_notification" && typeof t.task_id === "string") {
const n = e.get(t.task_id);
e.delete(t.task_id);
return n !== void 0 && e.has(n);
}
return false;
}
//#endregion
//#region extensions/anthropic/cli-user-input.ts
function createClaudeCliUserInputAuthorizer(e) {
const t = /* @__PURE__ */ new Map();
return { authorize(n) {
const r = n.toolUseId ? t.get(n.toolUseId) : void 0;
if (r) return r;
const i = runClaudeUserInput(e, n);
if (n.toolUseId) t.set(n.toolUseId, i);
return i;
} };
}
async function runClaudeUserInput(e, t) {
const n = readClaudeUserInputQuestions(t.input);
if (!n.ok) return {
behavior: "deny",
message: `OpenClaw rejected malformed Claude user questions: ${n.failure}. Correct the invalid field and retry AskUserQuestion.`
};
const r = n.questions;
const i = await e.requestUserInput({
toolName: "AskUserQuestion",
questions: r,
intro: "Claude needs input:",
...t.toolUseId ? { toolCallId: t.toolUseId } : {},
abortSignal: t.signal
});
if (i.status !== "answered") return {
behavior: "deny",
message: `${i.message} Continue with your best judgment.`
};
const a = {};
r.forEach((e) => {
a[e.question] = (i.answers[e.id] ?? []).join(", ");
});
return {
behavior: "allow",
updatedInput: {
...t.input,
answers: a
}
};
}
function readClaudeUserInputQuestions(e) {
const t = e.questions;
if (!Array.isArray(t) || t.length < 1 || t.length > 4) return {
ok: false,
failure: "questions must be an array of 1 to 4 questions"
};
const n = [];
for (const [e, r] of t.entries()) {
const t = `questions[${e}]`;
if (!isRecord(r)) return {
ok: false,
failure: `${t} must be an object`
};
const i = readBoundedText(r.question, 4096);
if (!i.ok) return {
ok: false,
failure: `${t}.question ${i.failure}`
};
const a = readBoundedText(r.header, 12);
if (!a.ok) return {
ok: false,
failure: `${t}.header ${a.failure}`
};
const o = r.options;
if (!Array.isArray(o) || o.length < 2 || o.length > 4) return {
ok: false,
failure: `${t}.options must be an array of 2 to 4 options`
};
if (typeof r.multiSelect !== "boolean") return {
ok: false,
failure: `${t}.multiSelect must be a boolean`
};
const s = [];
for (const [e, n] of o.entries()) {
const r = `${t}.options[${e}]`;
if (!isRecord(n)) return {
ok: false,
failure: `${r} must be an object`
};
const i = readBoundedText(n.label, 256);
if (!i.ok) return {
ok: false,
failure: `${r}.label ${i.failure}`
};
const a = readBoundedText(n.description, 1024, { shorten: true });
if (!a.ok) return {
ok: false,
failure: `${r}.description ${a.failure}`
};
s.push({
label: i.text,
description: a.text
});
}
n.push({
id: `question_${e + 1}`,
header: a.text,
question: i.text,
multiSelect: r.multiSelect,
isOther: true,
options: s
});
}
return {
ok: true,
questions: n
};
}
function readBoundedText(e, t, n = {}) {
if (typeof e !== "string") return {
ok: false,
failure: "must be a string"
};
if (e.length === 0) return {
ok: false,
failure: "must not be empty"
};
if (e.length > t) return n.shorten ? {
ok: true,
text: `${truncateUtf16Safe(e, t - 1)}\u2026`
} : {
ok: false,
failure: `must be at most ${t} characters`
};
return {
ok: true,
text: e
};
}
//#endregion
//#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 };