UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,973 lines • 69.7 kB
import { o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { d as asPositiveFiniteNumber } from "./number-coercion-D6u-4YD8.mjs";
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { p as toErrorObject } from "./error-coercion-hDrHOSGy.mjs";
import { r as extractBalancedJsonFragments } from "./src-H3RMXyFL.mjs";
import { n as safeParseJsonRecord } from "./json-coercion-CaJLaav-.mjs";
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { o as racePromiseWithAbortSignal } from "./src-BPmQBLJp.mjs";
import { t as isAbortError } from "./abort-signal-D4Q6SEw7.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { d as normalizeUsage } from "./usage-CHLnzpJG.mjs";
import { r as readTrimmedStringAlias } from "./string-readers-BtMVaphq.mjs";
import { n as sha256Hex } from "./node-crypto-B6yuTjmm.mjs";
import "./crypto-digest-B2m8wIBj.mjs";
import { c as readHostFreeMemoryBytes } from "./worker-pool-sizing-BAFxhrtU.mjs";
import { n as estimateBase64DecodedBytes } from "./base64-CnKpkbff.mjs";
import { t as applyPluginTextReplacements } from "./plugin-text-transforms-CMotGmZ0.mjs";
import { i as FailoverError, n as CLI_LIVE_SESSION_HOST_MEMORY_ERROR_CODE, u as isFailoverError } from "./error-BCRqSFIY.mjs";
import { r as isInsideCode } from "./code-ranges-2XaqsF-S.mjs";
import "./code-regions-CfNY0afj.mjs";
import { n as findMarkdownCodeRegions, s as scanReasoningTags, t as createReasoningTagTextPartitioner } from "./reasoning-tags-DL3sP_9k.mjs";
import { n as recordModelFallbackStop } from "./model-fallback-stop-BN_k3Te_.mjs";
import { p as resolveFailoverStatus, r as coerceToFailoverError } from "./failover-error-CbIiC30n.mjs";
import { i as runOwnedAgentCleanup } from "./run-cleanup-timeout-Bk3vN1Oh.mjs";
import { n as cliBackendLog } from "./log-C54MYINf.mjs";
import { n as createCliRunCurrentAssertion } from "./execution-target-whyiKvuS.mjs";
import { t as hasAcceptedSessionSpawn } from "./accepted-session-spawn-DXCz6IHR.mjs";
import { n as updateLiveEditDiffProgressFromInput } from "./embedded-agent-live-edit-diff-CXQyk4M9.mjs";
//#region src/agents/cli-runner/cleanup.ts
/** Release in order even after failure, preserving the last cleanup error. */
function sequenceCliCleanups(...e) {
	return e.reduceRight((e, t) => {
		if (!t) return e;
		return async () => {
			try {
				await t();
			} finally {
				await e?.();
			}
		};
	}, void 0);
}
/** Join CLI cleanup; replacement requires closure before any provider can proceed. */
async function runCliCleanup(e, t, n, r) {
	try {
		await runOwnedAgentCleanup({
			...e,
			step: t,
			cleanup: n,
			settlement: r,
			log: cliBackendLog
		});
	} catch (e) {
		if (r !== "required") throw e;
		const t = toErrorObject(e, "CLI resource cleanup failed");
		recordModelFallbackStop(t);
		throw t;
	}
}
//#endregion
//#region src/agents/cli-output-records.ts
function isClaudeCliProvider(e) {
	return normalizeLowercaseStringOrEmpty(e) === "claude-cli";
}
function isGeminiStreamJsonDialect(e) {
	return e.backend.jsonlDialect === "gemini-stream-json" || normalizeLowercaseStringOrEmpty(e.providerId) === "google-gemini-cli";
}
function isClaudeStreamJsonDialect(e) {
	if (e.backend.jsonlDialect) return e.backend.jsonlDialect === "claude-stream-json";
	return isClaudeCliProvider(e.providerId);
}
function supportsCliJsonlToolEvents(e) {
	return e.backend.jsonlDialect === "claude-stream-json" || isClaudeCliProvider(e.providerId) || isGeminiStreamJsonDialect(e);
}
function isClaudeSyntheticNoResponse(e) {
	if (e.type !== "assistant" || !isRecord(e.message)) return false;
	const t = e.message;
	return t.model === "<synthetic>" && Array.isArray(t.content) && t.content.length === 1 && isRecord(t.content[0]) && t.content[0].type === "text" && t.content[0].text === "No response requested.";
}
function decodeCliRecords(e) {
	const t = e.trim();
	if (!t) return [];
	const n = safeParseJsonRecord(t);
	if (n) return [n];
	const r = [];
	for (const { json: e } of extractBalancedJsonFragments(t, {
		openers: ["{"],
		skipQuotedOpeners: true
	})) {
		const t = safeParseJsonRecord(e);
		if (t) r.push(t);
	}
	return r;
}
function readNestedErrorMessage(e) {
	if (isRecord(e.error)) {
		const t = readNestedErrorMessage(e.error);
		if (t) return t;
	}
	for (const t of [e.message, e.error]) {
		const e = typeof t === "string" ? t.trim() : "";
		if (e) return e;
	}
}
function unwrapCliErrorText(e) {
	const t = e.trim();
	if (!t) return "";
	for (const e of decodeCliRecords(t)) {
		const t = readNestedErrorMessage(e);
		if (t) return t;
	}
	return t;
}
function normalizeCliUsageRecord(e) {
	if (!isRecord(e)) return;
	const t = e;
	const n = normalizeUsage(t);
	if (!n) return;
	const r = [
		t.inputTokens,
		t.input_tokens,
		t.promptTokens,
		t.prompt_tokens
	].some((e) => typeof e === "number" && e > 0);
	const i = {
		input: n.input === 0 && r && Boolean(n.cacheRead || n.cacheWrite) ? 0 : n.input || void 0,
		output: n.output || void 0,
		cacheRead: n.cacheRead || void 0,
		cacheWrite: n.cacheWrite || void 0,
		cacheWrite1h: n.cacheWrite1h || void 0,
		total: n.total || void 0
	};
	return Object.values(i).some((e) => (e ?? 0) > 0) ? i : void 0;
}
function readCliUsage(e) {
	return normalizeCliUsageRecord(isRecord(e.message) ? e.message.usage : void 0) ?? normalizeCliUsageRecord(e.usage) ?? normalizeCliUsageRecord(e.stats);
}
function collectCliText(e) {
	if (typeof e === "string") return e;
	if (Array.isArray(e)) return e.map((e) => collectCliText(e)).join("");
	if (!isRecord(e)) return "";
	for (const t of [
		"response",
		"text",
		"result",
		"content"
	]) if (typeof e[t] === "string") return e[t];
	if (Array.isArray(e.content)) return e.content.map((e) => collectCliText(e)).join("");
	if (isRecord(e.message)) return collectCliText(e.message);
	return "";
}
function unwrapNestedCliResultText(e) {
	let t = e;
	for (let e = 0; e < 8; e += 1) {
		const e = safeParseJsonRecord(t.trim());
		if (!e || e.type !== "result" || typeof e.result !== "string") return t;
		t = e.result;
	}
	return t;
}
function collectExplicitCliErrorText(e) {
	const t = typeof e.subtype === "string" ? e.subtype.trim() : "";
	const n = e.is_error === true || e.type === "result" && (t.startsWith("error_") || e.status === "error");
	if (n) {
		const t = readClaudeResultErrorsText(e) || collectCliText(e.result) || collectCliText(e.message) || collectCliText(e.content);
		if (t) return unwrapCliErrorText(t);
	}
	const r = readNestedErrorMessage(e);
	if (r) return unwrapCliErrorText(r);
	if (n) return t ? `Claude CLI result subtype ${t}.` : "CLI result was marked as an error.";
	if (e.type === "assistant") {
		const t = collectCliText(e.message);
		if (/^\s*API Error:/i.test(t)) return unwrapCliErrorText(t);
	}
	if (e.type === "error") return unwrapCliErrorText(collectCliText(e.message) || collectCliText(e.content) || collectCliText(e.result) || collectCliText(e));
	return "";
}
const CLI_TERMINAL_REASON_MAX_CHARS = 64;
function normalizeCliTerminalReason(e) {
	return truncateUtf16Safe(e.replace(/[\p{Cc}\p{Cf}\s]+/gu, " ").trim(), CLI_TERMINAL_REASON_MAX_CHARS);
}
function describeClaudeTurnStop(e) {
	const t = e.stopReason ? `, stop_reason: ${e.stopReason}` : "";
	return `Claude CLI ended the turn without a reply (terminal_reason: ${e.terminalReason}${t}).`;
}
const CLAUDE_TURN_STOP_REASONS = /* @__PURE__ */ new Set([
	"hook_stopped",
	"stop_hook_prevented",
	"aborted_tools",
	"aborted_streaming",
	"budget_exhausted"
]);
function readClaudeTerminalFailure(e) {
	const t = typeof e.subtype === "string" ? e.subtype.trim() : "";
	const n = typeof e.terminal_reason === "string" ? e.terminal_reason.trim() : "";
	if (t !== "error_max_turns" && n !== "max_turns") {
		const t = typeof e.terminal_reason === "string" ? normalizeCliTerminalReason(e.terminal_reason) : "";
		if (e.type !== "result" || !CLAUDE_TURN_STOP_REASONS.has(t) || unwrapNestedCliResultText(collectCliText(e.result)).trim() || collectExplicitCliErrorText(e)) return;
		const n = typeof e.stop_reason === "string" ? normalizeCliTerminalReason(e.stop_reason) : "";
		return {
			reason: "turn_stopped",
			terminalReason: t,
			...n ? { stopReason: n } : {}
		};
	}
	const r = Array.isArray(e.errors) ? e.errors : [];
	for (const e of r) {
		if (typeof e !== "string") continue;
		const t = e.match(/maximum number of turns\s*\((\d+)\)/i);
		if (t) {
			const e = Number.parseInt(t[1] ?? "", 10);
			if (Number.isSafeInteger(e) && e > 0) return {
				reason: "max_turns",
				limit: e
			};
		}
	}
	return { reason: "max_turns" };
}
function readClaudeResultErrorsText(e) {
	if (!Array.isArray(e.errors)) return;
	for (const t of e.errors) {
		const e = typeof t === "string" ? t.trim() : "";
		if (e && !e.startsWith("[ede_diagnostic]")) return e;
	}
}
function resolveCliTerminalErrorText(e, t) {
	const n = collectExplicitCliErrorText(e);
	if (n || !t) return n;
	return t.reason === "turn_stopped" ? describeClaudeTurnStop(t) : "Reached maximum number of turns.";
}
function pickCliSessionId(e, t) {
	const n = t.sessionIdFields ?? [
		"session_id",
		"sessionId",
		"conversation_id",
		"conversationId"
	];
	return readTrimmedStringAlias(e, n);
}
function isClaudeSubagentRecord(e) {
	return e.parent_tool_use_id != null;
}
function isClaudeStopHookFeedbackRecord(e) {
	return e.type === "system" && e.subtype === "notification" && e.key === "stop-hook-error";
}
const CLAUDE_FOREGROUND_AGENT_TOOL_NAMES = /* @__PURE__ */ new Set(["Agent", "Task"]);
function isClaudeForegroundAgentToolName(e) {
	return CLAUDE_FOREGROUND_AGENT_TOOL_NAMES.has(e);
}
function isClaudeToolUseBlockType(e) {
	return e === "tool_use" || e === "server_tool_use" || e === "mcp_tool_use";
}
function isClaudeToolResultBlockType(e) {
	return typeof e === "string" && (e === "tool_result" || e.endsWith("_tool_result"));
}
function messageHasToolResult(e) {
	if (!isRecord(e) || !Array.isArray(e.content)) return false;
	return e.content.some((e) => isRecord(e) && isClaudeToolResultBlockType(e.type));
}
function isClaudeSemanticSubagentProgressRecord(e) {
	if (e.type === "assistant" && isRecord(e.message) && Array.isArray(e.message.content) && e.message.content.length > 0) return true;
	if (e.type === "user" && messageHasToolResult(e.message)) return true;
	if (e.type !== "stream_event" || !isRecord(e.event)) return false;
	const t = e.event;
	if (t.type !== "content_block_start" || !isRecord(t.content_block)) return false;
	const n = t.content_block.type;
	return isClaudeToolUseBlockType(n) || isClaudeToolResultBlockType(n);
}
/** Parent id of a semantic subagent record. Partial deltas and system chatter stay out. */
function readClaudeAttributedSubagentProgressId(e) {
	if (typeof e.parent_tool_use_id !== "string") return;
	const t = e.parent_tool_use_id.trim();
	if (!t || !isClaudeSemanticSubagentProgressRecord(e)) return;
	return t;
}
function pickCliResumeCheckpointId(e) {
	if (!isClaudeStreamJsonDialect(e) || e.parsed.type !== "assistant" || isClaudeSubagentRecord(e.parsed)) return;
	return (typeof e.parsed.uuid === "string" ? e.parsed.uuid.trim() : "") || void 0;
}
function parseCliJson(e, t, n) {
	const r = decodeCliRecords(e);
	const i = isClaudeStreamJsonDialect({
		backend: t,
		providerId: n ?? ""
	});
	const a = Boolean(n && isClaudeCliProvider(n));
	let o;
	let s;
	let c = "";
	let l = false;
	for (const e of r) {
		o = pickCliSessionId(e, t) ?? o;
		s = readCliUsage(e) ?? s;
		const n = i ? readClaudeTerminalFailure(e) : void 0;
		if (n && !(n.reason === "turn_stopped" && c.trim())) return {
			text: "",
			sessionId: o,
			usage: s,
			errorText: resolveCliTerminalErrorText(e, n),
			terminalFailure: n
		};
		const r = typeof e.subtype === "string" ? e.subtype.trim() : "";
		const u = e.is_error === true || e.type === "error" || e.type === "result" && (r.startsWith("error_") || e.status === "error" || (typeof e.error === "string" ? Boolean(e.error.trim()) : isRecord(e.error) && Boolean(readNestedErrorMessage(e.error)))) ? collectExplicitCliErrorText(e) : "";
		if (u) return {
			text: "",
			sessionId: o,
			usage: s,
			errorText: u
		};
		const d = collectCliText(e.message) || collectCliText(e.content) || collectCliText(e.result) || collectCliText(e.response) || collectCliText(e);
		const f = (a && (!Object.hasOwn(e, "type") || e.type === "result") ? unwrapNestedCliResultText(d) : d).trim();
		if (f) {
			c = f;
			l = true;
			continue;
		}
		if (o || s) l = true;
	}
	if (!c && !l) return null;
	return {
		text: c,
		sessionId: o,
		usage: s
	};
}
function parseClaudeCliJsonlResult(e) {
	if (!supportsCliJsonlToolEvents(e) || e.parsed.type !== "result") return null;
	const t = isClaudeStreamJsonDialect(e) ? readClaudeTerminalFailure(e.parsed) : void 0;
	const n = resolveCliTerminalErrorText(e.parsed, t);
	let r = "";
	if (!n) {
		if (typeof e.parsed.result !== "string") return null;
		r = unwrapNestedCliResultText(e.parsed.result).trim();
	}
	return {
		text: r,
		sessionId: e.sessionId,
		usage: e.usage,
		...n ? {
			errorText: n,
			...t ? { terminalFailure: t } : {}
		} : {}
	};
}
function preferStreamedClaudeTextOverResult(e) {
	return Boolean(e.resultText) && e.streamedText !== e.resultText && e.finalMessageText === e.resultText;
}
function missingMessageBoundarySeparator(e, t) {
	if (!e) return "";
	const n = e.slice(-2).match(/\n*$/u)?.[0].length ?? 0;
	const r = t.slice(0, 2).match(/^\n*/u)?.[0].length ?? 0;
	return "\n".repeat(Math.max(0, 2 - n - r));
}
function parseClaudeCliStreamingDelta(e) {
	if (!supportsCliJsonlToolEvents(e)) return null;
	if (e.parsed.type === "stream_event" && isRecord(e.parsed.event)) {
		const t = e.parsed.event;
		if (t.type !== "content_block_delta" || !isRecord(t.delta)) return null;
		const n = t.delta;
		return n.type === "text_delta" && typeof n.text === "string" && n.text ? n.text : null;
	}
	if (!isClaudeStreamJsonDialect(e) || e.parsed.type !== "assistant" || isClaudeSubagentRecord(e.parsed) || !isRecord(e.parsed.message) || e.parsed.message.stop_reason !== null) return null;
	const t = (Array.isArray(e.parsed.message.content) ? e.parsed.message.content : []).map((e) => isRecord(e) && e.type === "text" && typeof e.text === "string" ? e.text : "").join("");
	return t.startsWith(e.previousText) ? t.slice(e.previousText.length) || null : null;
}
const GEMINI_CLI_ERROR_EVENT_FALLBACK = "Gemini CLI emitted an error event.";
const GEMINI_CLI_RESULT_ERROR_FALLBACK = "Gemini CLI result status was error.";
function isFallbackGeminiCliStreamJsonError(e) {
	return e === GEMINI_CLI_ERROR_EVENT_FALLBACK || e === GEMINI_CLI_RESULT_ERROR_FALLBACK;
}
function preferGeminiCliStreamJsonError(e, t) {
	if (!e) return t;
	if (isFallbackGeminiCliStreamJsonError(e) && !isFallbackGeminiCliStreamJsonError(t)) return t;
	return e;
}
function readGeminiCliStreamJsonError(e) {
	if (e.type === "error" && e.severity === "error") return collectExplicitCliErrorText(e) || GEMINI_CLI_ERROR_EVENT_FALLBACK;
	if (e.type === "result" && e.status === "error") return collectExplicitCliErrorText(e) || GEMINI_CLI_RESULT_ERROR_FALLBACK;
}
//#endregion
//#region src/agents/cli-output-events.ts
function createToolUseTracker() {
	return {
		pendingByIndex: /* @__PURE__ */ new Map(),
		inputProgressById: /* @__PURE__ */ new Map(),
		nameById: /* @__PURE__ */ new Map(),
		startedIds: /* @__PURE__ */ new Set(),
		resultDeliveredIds: /* @__PURE__ */ new Set()
	};
}
function emitToolStartOnce(e, t, n, r, i, a) {
	e.inputProgressById.delete(t);
	if (e.startedIds.has(t)) return;
	e.startedIds.add(t);
	e.nameById.set(t, n);
	a?.({
		toolCallId: t,
		name: n,
		kind: r,
		args: i
	});
}
function emitToolResultOnce(e, t, n, r, i) {
	if (e.resultDeliveredIds.has(t)) return;
	e.resultDeliveredIds.add(t);
	i?.({
		toolCallId: t,
		name: e.nameById.get(t) ?? "",
		isError: n,
		result: r
	});
}
function projectCliBackendEvent(e) {
	const { event: t, state: n } = e;
	if (n.output?.errorText && t.kind !== "sessionId" && t.kind !== "result") return;
	n.sawCustomJsonlEvent = true;
	const observeSessionId = (t) => {
		if (t && t !== n.sessionId) {
			n.sessionId = t;
			e.onSessionId?.(t);
		}
	};
	if (t.kind === "sessionId") {
		observeSessionId(t.sessionId.trim());
		if (n.output) n.output = {
			...n.output,
			sessionId: n.sessionId
		};
		return;
	}
	if (t.kind === "text") {
		if (!t.text) return;
		n.assistantText += t.text;
		e.onAssistantDelta({
			text: n.assistantText,
			delta: t.text,
			sessionId: n.sessionId,
			usage: n.usage
		});
		return;
	}
	if (t.kind === "thinking") {
		if (!t.text || !e.onThinkingDelta) return;
		n.customThinkingText += t.text;
		e.onThinkingDelta({
			text: n.customThinkingText,
			delta: t.text,
			isReasoningSnapshot: true,
			modelProgress: true
		});
		return;
	}
	if (t.kind === "toolStart") {
		emitToolStartOnce(e.toolTracker, t.toolCallId, t.name, "tool_use", t.args ?? {}, e.onDisplayToolUseStart ?? e.onToolUseStart);
		return;
	}
	if (t.kind === "toolResult") {
		if (t.name) e.toolTracker.nameById.set(t.toolCallId, t.name);
		emitToolResultOnce(e.toolTracker, t.toolCallId, t.isError === true, t.result, e.onDisplayToolResult ?? e.onToolResult);
		return;
	}
	observeSessionId(t.sessionId?.trim());
	if (t.usage) {
		n.usage = t.usage;
		e.onUsage?.(t.usage, true);
	}
	const r = n.output?.errorText;
	const i = !r && t.text?.trim() || n.output?.text.trim() || e.texts.join("\n").trim() || n.assistantText.trim();
	const a = r || t.errorText;
	n.output = {
		...n.output,
		text: i,
		sessionId: n.sessionId,
		usage: n.usage,
		...a ? { errorText: a } : {}
	};
}
function projectCliTaggedReasoning(e) {
	let t = e.currentText;
	for (const n of e.deltas) {
		if (n.kind === "text") {
			e.onVisibleText(n.text);
			continue;
		}
		t += n.text;
		if (!e.hasNativeThinking) e.onThinkingDelta?.({
			text: t,
			delta: n.text,
			isReasoningSnapshot: true,
			modelProgress: true
		});
	}
	return t;
}
function isClaudeAssistantToolResultBlockType(e) {
	return isClaudeToolResultBlockType(e) && e !== "tool_result";
}
function isClaudeToolResultError(e) {
	return isRecord(e) && typeof e.type === "string" && e.type.endsWith("_error");
}
function emitClaudeToolResultBlock(e, t, n) {
	const r = typeof t.tool_use_id === "string" ? t.tool_use_id.trim() : "";
	if (r) emitToolResultOnce(e, r, t.is_error === true || t.type !== "tool_result" && isClaudeToolResultError(t.content), t.content, n);
}
function dispatchClaudeCliStreamingToolEvent(e) {
	if (!supportsCliJsonlToolEvents(e) || isClaudeSubagentRecord(e.parsed)) return;
	const t = e.tracker;
	if (e.parsed.type === "stream_event" && isRecord(e.parsed.event)) {
		const n = e.parsed.event;
		if (n.type === "content_block_start" && typeof n.index === "number" && isRecord(n.content_block)) {
			const r = n.content_block;
			const i = t.pendingByIndex.get(n.index);
			t.pendingByIndex.delete(n.index);
			const a = typeof r.id === "string" ? r.id.trim() : "";
			if (i && i.toolCallId !== a) t.inputProgressById.delete(i.toolCallId);
			if (isClaudeToolUseBlockType(r.type)) {
				const e = typeof r.id === "string" ? r.id.trim() : "";
				const i = typeof r.name === "string" ? r.name.trim() : "";
				if (e && i) t.pendingByIndex.set(n.index, {
					toolCallId: e,
					name: i,
					kind: r.type,
					inputJsonParts: [],
					inputJsonLength: 0,
					...isRecord(r.input) ? { blockInput: r.input } : {}
				});
			} else if (isClaudeAssistantToolResultBlockType(r.type)) emitClaudeToolResultBlock(t, r, e.onToolResult);
			return;
		}
		if (n.type === "content_block_delta" && typeof n.index === "number" && isRecord(n.delta)) {
			if (n.delta.type === "input_json_delta" && typeof n.delta.partial_json === "string") {
				const r = t.pendingByIndex.get(n.index);
				if (r) {
					r.inputJsonParts.push(n.delta.partial_json);
					r.inputJsonLength += n.delta.partial_json.length;
					if (e.onToolInputDelta && !t.startedIds.has(r.toolCallId)) {
						const n = updateLiveEditDiffProgressFromInput(t.inputProgressById, {
							toolCallId: r.toolCallId,
							name: r.name,
							partialJsonLength: r.inputJsonLength,
							readPartialJson: () => r.inputJsonParts.join("")
						});
						if (n) e.onToolInputDelta(n);
					}
				}
			}
			return;
		}
		if (n.type === "content_block_stop" && typeof n.index === "number") {
			const r = t.pendingByIndex.get(n.index);
			t.pendingByIndex.delete(n.index);
			if (r) {
				const n = r.inputJsonParts.length > 0 ? safeParseJsonRecord(r.inputJsonParts.join("")) ?? {} : r.blockInput ?? {};
				emitToolStartOnce(t, r.toolCallId, r.name, r.kind, n, e.onToolUseStart);
			}
			return;
		}
		return;
	}
	const n = e.parsed.type === "assistant";
	if ((n || e.parsed.type === "user") && isRecord(e.parsed.message)) {
		const r = e.parsed.message;
		const i = Array.isArray(r.content) ? r.content : [];
		for (const r of i) {
			if (!isRecord(r)) continue;
			if (n && isClaudeToolUseBlockType(r.type)) {
				const n = typeof r.id === "string" ? r.id.trim() : "";
				const i = typeof r.name === "string" ? r.name.trim() : "";
				if (n && i) {
					const a = isRecord(r.input) ? r.input : {};
					emitToolStartOnce(t, n, i, r.type, a, e.onToolUseStart);
				}
			} else if (n ? isClaudeAssistantToolResultBlockType(r.type) : r.type === "tool_result") emitClaudeToolResultBlock(t, r, e.onToolResult);
		}
	}
}
function resetThinkingTrackerForMessage(e, t) {
	if (t && t === e.currentMessageId) return;
	if (t && e.currentMessageId === void 0) {
		e.currentMessageId = t;
		return;
	}
	e.streamedByIndex.clear();
	e.highestStreamedIndex = Number.NEGATIVE_INFINITY;
	e.emittedText = "";
	e.currentSyntheticBlockIndex = void 0;
	e.nextSyntheticBlockIndex = 0;
	e.progressTokens = 0;
	e.currentMessageId = t;
}
function resolveClaudeContentBlockIndex(e, t) {
	if (typeof t === "number") {
		e.nextSyntheticBlockIndex = Math.max(e.nextSyntheticBlockIndex, t + 1);
		return t;
	}
	if (t !== void 0) return null;
	return e.currentSyntheticBlockIndex ?? null;
}
function assembleThinkingTextByIndex(e) {
	return [...e.entries()].toSorted(([e], [t]) => e - t).map(([, e]) => e).join("");
}
function dispatchClaudeCliThinking(e) {
	if (!supportsCliJsonlToolEvents(e) || isClaudeSubagentRecord(e.parsed)) return;
	const t = e.tracker;
	if (e.parsed.type === "stream_event" && isRecord(e.parsed.event)) {
		const n = e.parsed.event;
		if (n.type === "message_start") {
			const e = isRecord(n.message) ? n.message : void 0;
			resetThinkingTrackerForMessage(t, typeof e?.id === "string" ? e.id : void 0);
			return;
		}
		if (n.type === "content_block_start") {
			const e = n.index;
			t.currentSyntheticBlockIndex = e === void 0 ? t.nextSyntheticBlockIndex++ : resolveClaudeContentBlockIndex(t, e) ?? void 0;
			return;
		}
		if (n.type === "content_block_stop") {
			t.currentSyntheticBlockIndex = void 0;
			return;
		}
		if (n.type !== "content_block_delta" || !isRecord(n.delta)) return;
		const r = resolveClaudeContentBlockIndex(t, n.index);
		if (r === null) return;
		const i = n.delta;
		const a = i.type === "thinking_delta" && i.thinking === "" ? asPositiveFiniteNumber(i.estimated_tokens) : void 0;
		const o = e.onThinkingProgress;
		if (a !== void 0 && o) {
			t.progressTokens += a;
			o({
				progressTokens: t.progressTokens,
				modelProgress: true
			});
			return;
		}
		if (n.delta.type !== "thinking_delta" || typeof n.delta.thinking !== "string") return;
		if (!n.delta.thinking || !e.onThinkingDelta) return;
		const s = t.streamedByIndex.get(r) ?? "";
		const c = n.delta.thinking;
		const l = e.onThinkingDelta;
		const u = r >= t.highestStreamedIndex;
		t.streamedByIndex.set(r, `${s}${c}`);
		t.highestStreamedIndex = Math.max(t.highestStreamedIndex, r);
		t.emittedText = u ? `${t.emittedText}${c}` : assembleThinkingTextByIndex(t.streamedByIndex);
		l({
			text: t.emittedText,
			delta: c,
			isReasoningSnapshot: true,
			modelProgress: true
		});
		return;
	}
	if (e.parsed.type === "assistant" && isRecord(e.parsed.message)) {
		resetThinkingTrackerForMessage(t, typeof e.parsed.message.id === "string" ? e.parsed.message.id : void 0);
		const n = Array.isArray(e.parsed.message.content) ? e.parsed.message.content : [];
		for (const [r, i] of n.entries()) {
			if (!isRecord(i) || i.type !== "thinking" || typeof i.thinking !== "string") continue;
			if (!e.onThinkingDelta) continue;
			if ((t.streamedByIndex.get(r) ?? "").startsWith(i.thinking)) continue;
			t.streamedByIndex.set(r, i.thinking);
			t.highestStreamedIndex = Math.max(t.highestStreamedIndex, r);
			const n = assembleThinkingTextByIndex(t.streamedByIndex);
			if (n === t.emittedText) continue;
			t.emittedText = n;
			e.onThinkingDelta({
				text: n,
				delta: i.thinking,
				isReasoningSnapshot: true,
				modelProgress: true
			});
		}
	}
}
function dispatchGeminiCliStreamingToolEvent(e) {
	if (!isGeminiStreamJsonDialect(e)) return;
	if (e.parsed.type === "tool_use") {
		const t = typeof e.parsed.tool_id === "string" ? e.parsed.tool_id.trim() : "";
		const n = typeof e.parsed.tool_name === "string" ? e.parsed.tool_name.trim() : "";
		if (!t || !n) return;
		const r = isRecord(e.parsed.parameters) ? e.parsed.parameters : {};
		emitToolStartOnce(e.tracker, t, n, "tool_use", r, e.onToolUseStart);
		return;
	}
	if (e.parsed.type === "tool_result") {
		const t = typeof e.parsed.tool_id === "string" ? e.parsed.tool_id.trim() : "";
		if (!t) return;
		const n = e.parsed.status === "error" && isRecord(e.parsed.error) ? e.parsed.error : e.parsed.output;
		emitToolResultOnce(e.tracker, t, e.parsed.status === "error", n, e.onToolResult);
	}
}
function partitionLeadingTaggedReasoning(e, t) {
	const n = e.search(/\S/u);
	if (n === -1) return t ? {
		pending: false,
		reasoningText: "",
		visibleText: e
	} : {
		pending: true,
		openWithoutPendingTag: false
	};
	if (e.charAt(n) !== "<") return {
		pending: false,
		reasoningText: "",
		visibleText: e
	};
	const r = scanReasoningTags(e, t);
	let i = 0;
	let a = -1;
	for (const t of r.tags) {
		if (i === 0) {
			const r = a === -1 ? n : a;
			if (e.slice(r, t.index).trim() || t.isClose || t.isSelfClosing) break;
		}
		i += t.isClose ? -1 : t.isSelfClosing ? 0 : 1;
		if (i === 0 && t.isClose) a = t.index + t.text.length;
	}
	const o = a !== -1 && r.pendingStart !== void 0 && !e.slice(a, r.pendingStart).trim();
	if (a === -1) {
		const a = r.pendingStart !== void 0 && !e.slice(n, r.pendingStart).trim();
		return !t && (i > 0 || a) ? {
			pending: true,
			openWithoutPendingTag: i > 0 && r.pendingStart === void 0
		} : {
			pending: false,
			reasoningText: "",
			visibleText: e
		};
	}
	if (!t && (i > 0 || o || !e.slice(a).trim())) return {
		pending: true,
		openWithoutPendingTag: i > 0 && r.pendingStart === void 0
	};
	const s = createReasoningTagTextPartitioner();
	const c = [...s.pushVisible(e.slice(0, a)), ...s.flush()].filter((e) => e.kind === "thinking").map((e) => e.text).join("");
	return c ? {
		pending: false,
		reasoningText: c,
		visibleText: e.slice(a)
	} : {
		pending: false,
		reasoningText: "",
		visibleText: e
	};
}
function createLeadingTaggedReasoningRouter() {
	let e = "";
	let t = false;
	let n = false;
	const consume = (r, i) => {
		if (t) return r ? [{
			kind: "text",
			text: r
		}] : [];
		e += r;
		if (!i && n && !r.includes("<")) return [];
		const a = partitionLeadingTaggedReasoning(e, i);
		if (a.pending) {
			n = a.openWithoutPendingTag;
			return [];
		}
		t = true;
		e = "";
		return [...a.reasoningText ? [{
			kind: "thinking",
			text: a.reasoningText
		}] : [], ...a.visibleText ? [{
			kind: "text",
			text: a.visibleText
		}] : []];
	};
	return {
		push: (e) => consume(e, false),
		finish: () => consume("", true)
	};
}
//#endregion
//#region src/agents/cli-output-lifecycle.ts
function parseCliBackendLifecycleLine(e) {
	if (!e.parse) return;
	try {
		const t = e.parse(e.line, {
			backendId: e.backendId,
			backend: e.backend
		});
		if (t == null) return;
		return { events: "kind" in t ? [t] : t };
	} catch (t) {
		return { errorText: truncateUtf16Safe(`CLI backend ${e.backendId} JSONL lifecycle parser failed: ${formatErrorMessage(t)}`, 500) };
	}
}
function projectCliBackendLifecycleEvent(e) {
	return e.phase === "start" ? { phase: "start" } : {
		phase: "end",
		completed: e.completed
	};
}
//#endregion
//#region src/agents/cli-output-results.ts
function transformCliResultText(e, t) {
	return {
		...e,
		rawText: e.text,
		...e.interimNativeReplies ? { interimNativeReplies: e.interimNativeReplies.map((e) => ({
			...e,
			text: applyPluginTextReplacements(e.text, t)
		})) } : {},
		text: applyPluginTextReplacements(e.text, t),
		...e.textParts ? { textParts: e.textParts.map((e) => applyPluginTextReplacements(e, t)) } : {}
	};
}
/** Records the model's final message when it differs from the cumulative delivery text. */
function withCliRawFinalText(e, t) {
	if (t !== e.text.trim()) return {
		...e,
		rawFinalText: t
	};
	const { rawFinalText: n, ...r } = e;
	return r;
}
/** Keep completed answers distinct while retaining cumulative transcript text. */
function appendCliResultText(e, t) {
	const n = e?.text.trim() ?? "";
	const r = e?.textParts ?? (n ? [n] : []);
	const i = t === r.at(-1) ? "" : t;
	return {
		text: i ? n ? `${n}\n${i}` : i : n,
		textParts: i ? [...r, i] : r,
		completedText: i
	};
}
/**
* Stores a record's message item text and returns the text that is still the
* final message: a later tool item ends it, like a tool_use block does.
*/
function recordItemText(e, t, n) {
	const r = isRecord(e.item) ? e.item : null;
	if (!r) return n;
	const i = normalizeLowercaseStringOrEmpty(r.type);
	if (!i || i.includes("message")) {
		if (typeof r.text !== "string") return n;
		t.push(r.text);
		return r.text;
	}
	return i.includes("reasoning") ? n : void 0;
}
//#endregion
//#region src/agents/cli-output-echoed-binary.ts
/** Drops Claude's echoed binary bytes before they enter retained tool/transcript state. */
function normalizeClaudeCliStreamJsonRecord(e) {
	if (e.type !== "user" || !isRecord(e.message)) return;
	let t = false;
	let n = 0;
	const r = [e];
	while (r.length > 0) {
		const e = r.pop();
		if (Array.isArray(e)) {
			for (const t of e) r.push(t);
			continue;
		}
		if (!isRecord(e)) continue;
		const i = e.source;
		if (isRecord(i) && i.type === "base64" && typeof i.data === "string" && (e.type === "image" || e.type === "document" && i.media_type === "application/pdf")) {
			const { data: r, ...a } = i;
			e.source = a;
			e.omitted = true;
			e.bytes = estimateBase64DecodedBytes(r);
			n += r.length;
			t = true;
		}
		const a = [
			e.file,
			...Array.isArray(e.images) ? e.images : [],
			...Array.isArray(e.documents) ? e.documents : []
		];
		for (const e of a) {
			if (!isRecord(e) || typeof e.base64 !== "string") continue;
			const r = e.base64;
			delete e.base64;
			e.omitted = true;
			e.bytes = estimateBase64DecodedBytes(r);
			n += r.length;
			t = true;
		}
		for (const t of Object.values(e)) r.push(t);
	}
	if (!t) return;
	try {
		return {
			line: JSON.stringify(e),
			omittedRawChars: n
		};
	} catch {
		return;
	}
}
//#endregion
//#region src/agents/cli-output-stream-limits.ts
const CLI_STREAM_JSON_DEFAULT_MAX_TURN_RAW_CHARS = 8388608;
const CLI_STREAM_JSON_DEFAULT_MAX_TURN_LINES = 2e4;
const CLI_STREAM_JSON_OUTPUT_LIMITS = Object.freeze({
	maxTurnRawChars: CLI_STREAM_JSON_DEFAULT_MAX_TURN_RAW_CHARS,
	maxPendingLineChars: CLI_STREAM_JSON_DEFAULT_MAX_TURN_RAW_CHARS,
	maxTurnLines: CLI_STREAM_JSON_DEFAULT_MAX_TURN_LINES
});
const PARTIAL_RECORD_METADATA_LIMITS = {
	uuid: 128,
	session_id: 128,
	parent_tool_use_id: 128,
	api_message_id: 64,
	thinking_display: 32
};
const PARTIAL_RECORD_KEYS = /* @__PURE__ */ new Set([
	"type",
	"event",
	...Object.keys(PARTIAL_RECORD_METADATA_LIMITS)
]);
const PARTIAL_EVENT_KEYS = /* @__PURE__ */ new Set([
	"type",
	"index",
	"delta"
]);
/** The event of a stream_event record with bounded metadata and a valid block index. */
function readBoundedStreamEvent(e) {
	if (e.type !== "stream_event" || !isRecord(e.event) || Object.keys(e).some((e) => !PARTIAL_RECORD_KEYS.has(e))) return;
	for (const [t, n] of Object.entries(PARTIAL_RECORD_METADATA_LIMITS)) {
		const r = e[t];
		if (r != null && (typeof r !== "string" || r.length > n)) return;
	}
	const t = e.event.index;
	if (t !== void 0 && (typeof t !== "number" || !Number.isSafeInteger(t) || t < 0)) return;
	return e.event;
}
/** Discount recognized token envelopes, retaining payload, padding, and a per-frame budget. */
function measureClaudePartialMessage(e, t) {
	const n = readBoundedStreamEvent(e);
	if (n?.type !== "content_block_delta" || !isRecord(n.delta) || Object.keys(n).some((e) => !PARTIAL_EVENT_KEYS.has(e))) return;
	const r = n.delta;
	const i = r.type === "text_delta" ? "text" : r.type === "thinking_delta" ? "thinking" : r.type === "input_json_delta" ? "partial_json" : void 0;
	const a = i ? r[i] : void 0;
	if (typeof a !== "string" || !a || e.thinking_display != null && r.type !== "thinking_delta" || Object.keys(r).some((e) => e !== "type" && e !== i && !(r.type === "thinking_delta" && e === "estimated_tokens"))) return;
	const o = r.estimated_tokens;
	if (o != null && (typeof o !== "number" || !Number.isFinite(o))) return;
	return JSON.stringify(a).length + 32 + (o === void 0 ? 0 : JSON.stringify({ estimated_tokens: o }).length) + Math.max(0, t.length - JSON.stringify(e).length);
}
const CONTROL_FRAME_EVENT_KEYS = /* @__PURE__ */ new Map([
	["content_block_start", /* @__PURE__ */ new Set([
		"type",
		"index",
		"content_block"
	])],
	["content_block_delta", /* @__PURE__ */ new Set([
		"type",
		"index",
		"delta"
	])],
	["content_block_stop", /* @__PURE__ */ new Set(["type", "index"])],
	["message_stop", /* @__PURE__ */ new Set(["type"])],
	["message_delta", /* @__PURE__ */ new Set([
		"type",
		"delta",
		"usage",
		"context_management"
	])]
]);
const PROGRESS_DELTA_KEYS = /* @__PURE__ */ new Set([
	"type",
	"thinking",
	"estimated_tokens"
]);
const SIGNATURE_DELTA_KEYS = /* @__PURE__ */ new Set(["type", "signature"]);
const CONTROL_FRAME_DISCARDED_ALLOWANCE_CHARS = 8192;
/**
* Fixed charge for stream events whose content the parser discards: thinking
* progress (only `estimated_tokens` is read), block starts (only the block
* header is kept), block/message stops, and signatures and message deltas,
* which are charged beyond their discarded allowance.
*/
function measureClaudeStreamControlFrame(e, t) {
	const n = readBoundedStreamEvent(e);
	const r = n ? CONTROL_FRAME_EVENT_KEYS.get(n.type) : void 0;
	if (!n || !r || Object.keys(n).some((e) => !r.has(e))) return;
	const i = isRecord(n.delta) ? n.delta : {};
	const a = i.estimated_tokens;
	const o = i.type === "thinking_delta" && i.thinking === "" && (a === null || typeof a === "number" && Number.isFinite(a)) && Object.keys(i).every((e) => PROGRESS_DELTA_KEYS.has(e));
	const s = i.type === "signature_delta" && typeof i.signature === "string" && i.signature.length > 0 && Object.keys(i).every((e) => SIGNATURE_DELTA_KEYS.has(e));
	if (n.type === "content_block_delta" && !o && !s || n.type === "content_block_start" && !isRecord(n.content_block) || e.thinking_display != null && !o) return;
	const c = s || n.type === "message_delta";
	const l = Math.max(0, t.length - JSON.stringify(e).length);
	if (c) {
		const e = t.length - CONTROL_FRAME_DISCARDED_ALLOWANCE_CHARS;
		return 32 + Math.max(l, e);
	}
	return 32 + (o ? JSON.stringify({ estimated_tokens: a }).length : n.type === "content_block_start" ? JSON.stringify(n.content_block).length : 0) + l;
}
/**
* Each model request opens with a `message_start` event and a `system/status`
* record whose metadata the parser discards; it reads at most their ids and usage.
*/
function measureClaudeRequestEnvelope(e, t) {
	return e.type === "stream_event" && isRecord(e.event) && e.event.type === "message_start" || e.type === "system" && e.subtype === "status" ? 32 + Math.max(0, t.length - CONTROL_FRAME_DISCARDED_ALLOWANCE_CHARS) : void 0;
}
/** Assistant snapshots keep only their content blocks; envelope and metadata are discarded. */
function measureClaudeAssistantMessage(e) {
	const t = isRecord(e.message) ? e.message.content : void 0;
	return e.type === "assistant" && Array.isArray(t) ? 32 + JSON.stringify(t).length : void 0;
}
/** Pure tool-result records keep only their tool ids; payloads go to consumers unretained. */
function measureClaudeToolResultMessage(e) {
	const t = isRecord(e.message) ? e.message.content : void 0;
	if (e.type !== "user" || !Array.isArray(t) || t.length === 0) return;
	let n = 0;
	for (const e of t) {
		if (!isRecord(e) || e.type !== "tool_result" || typeof e.tool_use_id !== "string") return;
		n += e.tool_use_id.length;
	}
	return 32 + n;
}
const CLAUDE_SUBAGENT_RECORD_CHARS = 64;
/** Fixed charge only for child message records the parser discards. */
function measureClaudeSubagentRecord(e) {
	if (e.type !== "assistant" && e.type !== "user" || e.item != null) return;
	const t = readClaudeAttributedSubagentProgressId(e);
	if (!t || t.length > 128) return;
	return CLAUDE_SUBAGENT_RECORD_CHARS;
}
const UNCOUNTED_FRAME_MAX_UNCHARGED_CHARS = 1024;
/** Budget charge for one Claude stream-json line, and whether it counts toward the frame limit. */
function chargeClaudeStreamJsonLine(e, t) {
	let n;
	try {
		n = e ? measureClaudeSubagentRecord(e) ?? measureClaudePartialMessage(e, t) ?? measureClaudeStreamControlFrame(e, t) ?? measureClaudeRequestEnvelope(e, t) ?? measureClaudeAssistantMessage(e) ?? measureClaudeToolResultMessage(e) : void 0;
	} catch {}
	const r = e ? normalizeClaudeCliStreamJsonRecord(e) : void 0;
	const i = n ?? (r ? Math.max(r.line.length, t.length - r.omittedRawChars) : t.length);
	return {
		chars: i,
		countsFrame: t.length - i > UNCOUNTED_FRAME_MAX_UNCHARGED_CHARS
	};
}
/** Frames arbitrary stdout chunks while bounding each individual raw JSONL line. */
function frameBoundedCliJsonlChunk(e, t, n) {
	for (let r = 0; r < t.length;) {
		const i = t.indexOf("\n", r);
		const a = i === -1 ? t.length : i;
		if (e.pending.length + (a - r) > CLI_STREAM_JSON_DEFAULT_MAX_TURN_RAW_CHARS) {
			e.pending = "";
			return false;
		}
		e.pending += t.slice(r, a);
		if (i === -1) return true;
		const o = e.pending;
		e.pending = "";
		r = i + 1;
		if (n(o) === false) return true;
	}
	return true;
}
function streamJsonOutputLimitErrorText(e, t) {
	if (e === "line") return `CLI JSONL line exceeded ${t} characters; refusing to parse output.`;
	if (e === "lines") return `CLI JSONL output exceeded ${t} lines; refusing to parse output.`;
	return `CLI JSONL output exceeded ${t} characters; refusing to parse output.`;
}
//#endregion
//#region src/agents/cli-output-stream-output.ts
const CLI_STREAM_JSON_MISSING_RESULT_ERROR = "CLI stream-json output ended without a result event.";
const CLAUDE_INTERRUPTED_RAW_TOOL_PROTOCOL_ERROR = "Claude CLI interrupted during raw tool protocol.";
/**
* Resolve the stream output when no result envelope was parsed. The text stays
* the cumulative delivery reply; diagnostics receive only the model's final
* message through `rawFinalText`.
*/
function resolveCliStreamOutput(e) {
	const { params: t, texts: n, assistantText: r, sessionId: i, usage: a, resumeCheckpointId: o, rawLines: s, sawCustomJsonlEvent: c, sawGeminiStructuredOutput: l, claudeStreamJson: u, finalStreamedMessageText: d } = e;
	if (s === 0) return null;
	let f = n.join("\n");
	if (c ? !f.trim() : supportsCliJsonlToolEvents(t)) f = r;
	const settle = (e) => withCliRawFinalText(e, d());
	const p = {
		text: f.trim(),
		sessionId: i,
		usage: a
	};
	if (u) {
		const e = findMarkdownCodeRegions(f);
		for (const t of f.matchAll(/(?:^|\n)[ \t]*<(?:invoke|parameter)(?=[\s/>]|$)/gu)) if (!isInsideCode(t.index + t[0].lastIndexOf("<"), e)) return {
			...p,
			text: "",
			errorText: CLAUDE_INTERRUPTED_RAW_TOOL_PROTOCOL_ERROR,
			partialOutputRejected: true
		};
	}
	if (c || p.text) return settle({
		...p,
		...!c && o ? { resumeCheckpointId: o } : {}
	});
	if (isGeminiStreamJsonDialect(t) && l) return p;
	if (supportsCliJsonlToolEvents(t)) return {
		...p,
		errorText: CLI_STREAM_JSON_MISSING_RESULT_ERROR
	};
	return null;
}
//#endregion
//#region src/agents/cli-output-stream.ts
const CLAUDE_SYNTHETIC_NO_RESPONSE_ERROR = "Claude CLI returned a synthetic no-response result.";
function createCliJsonlStreamingParser(e) {
	const t = { pending: "" };
	let n = "";
	let r = "";
	let i = "";
	let a;
	let o = "";
	let s = false;
	let c = 0;
	let l = 0;
	let u = 0;
	let d = 0;
	let f = false;
	let p = false;
	let m = false;
	let h;
	let g;
	let _;
	let v;
	let y = null;
	let b = "";
	let x = 0;
	let S = 0;
	let C = 0;
	const w = [];
	let T;
	let E = false;
	let D = false;
	let O = false;
	let k = false;
	const A = createToolUseTracker();
	const j = CLI_STREAM_JSON_OUTPUT_LIMITS;
	const M = Boolean(e.onCommentaryText) && supportsCliJsonlToolEvents(e);
	const N = {
		streamedByIndex: /* @__PURE__ */ new Map(),
		highestStreamedIndex: Number.NEGATIVE_INFINITY,
		emittedText: "",
		nextSyntheticBlockIndex: 0,
		progressTokens: 0
	};
	const P = isClaudeStreamJsonDialect(e);
	let F = createLeadingTaggedReasoningRouter();
	let I = "";
	const appendAssistantText = (t) => {
		n += t;
		e.onAssistantDelta({
			text: n,
			delta: t,
			sessionId: h,
			usage: _
		});
	};
	const flushPendingClaudeText = (t) => {
		if (!i) return;
		const r = t === "commentary" ? i.trim() : i;
		i = "";
		if (t === "assistant") {
			if (s || f) d = n.length;
			s = false;
			f = false;
			appendAssistantText(r);
		} else if (r) e.onCommentaryText?.(r);
	};
	const emitClaudeVisibleText = (e) => {
		if (!e) return;
		if (M) {
			i = `${i}${e}`;
			return;
		}
		const t = s || f;
		const r = s ? m : f;
		const a = t && n ? missingMessageBoundarySeparator(n, e) : "";
		if (t && n) {
			c = n.length + a.length;
			if (!r) u = c;
		}
		s = false;
		f = false;
		appendAssistantText(`${a}${e}`);
	};
	const routeTaggedReasoningDeltas = (t) => {
		I = projectCliTaggedReasoning({
			deltas: t,
			currentText: I,
			hasNativeThinking: Boolean(N.emittedText),
			onThinkingDelta: e.onThinkingDelta,
			onVisibleText: emitClaudeVisibleText
		});
	};
	const finishTaggedReasoningMessage = () => {
		if (P) routeTaggedReasoningDeltas(F.finish());
	};
	const beginClaudeMessage = (e) => {
		finishTaggedReasoningMessage();
		F = createLeadingTaggedReasoningRouter();
		I = "";
		s = true;
		T = void 0;
		m = p;
		p = false;
		a = e;
		o = "";
	};
	const finalStreamedMessageText = () => T?.trim() ?? (s || f ? "" : n.slice(Math.max(c, d)).trim());
	const accountClaudeJsonlLine = (e, n = false) => {
		if (n && ++C > j.maxTurnLines) {
			b = streamJsonOutputLimitErrorText("lines", j.maxTurnLines);
			t.pending = "";
			return false;
		}
		x += e + 1;
		if (x <= j.maxTurnRawChars) return true;
		b = streamJsonOutputLimitErrorText("raw", j.maxTurnRawChars);
		t.pending = "";
		return false;
	};
	const observeSessionId = (t) => {
		const n = pickCliSessionId(t, e.backend);
		if (n && n !== h) {
			h = n;
			e.onSessionId?.(n);
		}
	};
	const handleCustomJsonlLine = (t, i) => {
		const a = parseCliBackendLifecycleLine({
			line: t,
			backendId: e.providerId,
			backend: e.backend,
			parse: e.parseJsonlLifecycleEvent
		});
		if (a) {
			if ("errorText" in a) b = a.errorText;
			else {
				if (P && !accountClaudeJsonlLine(i.length)) return true;
				for (const e of decodeCliRecords(t)) observeSessionId(e);
				for (const t of a.events) e.onCompaction?.(projectCliBackendLifecycleEvent(t));
			}
			return true;
		}
		if (!e.parseJsonlEvent) return false;
		let o;
		try {
			o = e.parseJsonlEvent(t, {
				backendId: e.providerId,
				backend: e.backend
			});
		} catch (t) {
			b = truncateUtf16Safe(`CLI backend ${e.providerId} JSONL parser failed: ${formatErrorMessage(t)}`, 500);
			return true;
		}
		if (o == null) return false;
		if (P && !accountClaudeJsonlLine(i.length)) return true;
		for (const t of Array.isArray(o) ? o : [o]) {
			if (t.kind === "result") O = true;
			const i = y;
			const a = {
				assistantText: n,
				customThinkingText: r,
				sessionId: h,
				usage: _,
				output: y,
				sawCustomJsonlEvent: E
			};
			projectCliBackendEvent({
				...e,
				event: t,
				state: a,
				texts: w,
				toolTracker: A
			});
			({assistantText: n, customThinkingText: r, sessionId: h, usage: _, output: y, sawCustomJsonlEvent: E} = a);
			if (t.kind === "toolStart") c = n.length;
			else if (t.kind === "result" && y && !y.errorText) {
				const e = i?.rawFinalText ?? i?.text.trim();
				const n = t.text?.trim() || (e ?? finalStreamedMessageText());
				y = withCliRawFinalText(y, n);
			}
		}
		return true;
	};
	const resetReplySegment = () => {
		l = n.length;
		c = l;
		u = l;
		s = false;
		f = false;
		p = false;
		m = false;
	};
	const handleParsedRecord = (t) => {
		if (b) return;
		const r = readClaudeAttributedSubagentProgressId(t);
		if (r) e.onAttributedSubagentProgress?.(r);
		if (P && t.type === "system" && t.subtype === "init" && !isClaudeSubagentRecord(t)) try {
			e.onNativeTools?.(t.tools);
		} catch (e) {
			b = truncateUtf16Safe(formatErrorMessage(e), 500);
			return;
		}
		if (t.type === "result" && t.openclaw_interim_result !== true && supportsCliJsonlToolEvents(e)) O = true;
		observeSessionId(t);
		const i = readCliUsage(t);
		const s = P && t.type === "result";
		if (s && i && _) v = i;
		if (i) e.onUsage?.(i, s);
		if (!supportsCliJsonlToolEvents(e) || t.type !== "result" || !_) _ = i ?? _;
		if (t.type === "assistant" && isRecord(t.message) && !isClaudeSubagentRecord(t)) {
			if (P) {
				const e = typeof t.message.id === "string" ? t.message.id : void 0;
				if (e && e !== a) {
					if (a === void 0) a = e;
					else beginClaudeMessage(e);
				}
			}
			g = pickCliResumeCheckpointId({
				...e,
				parsed: t
			}) ?? g;
			e.onAssistantMessage?.(t.message);
			if (P && isClaudeSyntheticNoResponse(t)) k = true;
		}
		const d = isGeminiStreamJsonDialect(e) ? readGeminiCliStreamJsonError(t) : void 0;
		if (isGeminiStreamJsonDialect(e) && (t.type === "tool_use" || t.type === "tool_result" || t.type === "result")) {
			D = true;
			f ||= t.type === "tool_use";
		}
		if (d) {
			y = {
				text: "",
				sessionId: h,
				usage: _,
				errorText: preferGeminiCliStreamJsonError(y?.errorText, d)
			};
			return;
		}
		const m = P && !isClaudeSubagentRecord(t) && isClaudeStopHookFeedbackRecord(t);
		if (t.type === "result" || m) {
			finishTaggedReasoningMessage();
			if (M) flushPendingClaudeText("assistant");
		}
		if (m) resetReplySegment();
		const x = parseClaudeCliJsonlResult({
			backend: e.backend,
			providerId: e.providerId,
			parsed: t,
			sessionId: h,
			usage: _
		});
		if (x) {
			const r = x.terminalFailure?.reason === "turn_stopped" ? x.terminalFailure : void 0;
			const i = r ? x.errorText ?? "" : "";
			if (r) {
				delete x.errorText;
				delete x.terminalFailure;
			} else if (x.errorText) {
				y = x;
				return;
			}
			if (P && x.text) {
				const t = partitionLeadingTaggedReasoning(x.text, true);
				if (!t.pending && t.reasoningText) {
					if (!N.emittedText && t.reasoningText !== I) I = projectCliTaggedReasoning({
						deltas: [{
							kind: "thinking",
							text: t.reasoningText
						}],
						currentText: "",
						hasNativeThinking: false,
						onThinkingDelta: e.onThinkingDelta,
						onVisibleText: emitClaudeVisibleText
					});
					x.text = t.visibleText.trim();
				}
			}
			const a = n.slice(l).trim();
			const o = n.slice(u).trim();
			const s = (preferStreamedClaudeTextOverResult({
				streamedText: o,
				finalMessageText: n.slice(c).trim(),
				resultText: x.text
			}) ? o : x.text || a || w.join("\n").trim()).trim();
			const { text: d, textParts: f, completedText: p } = appendCliResultText(y, s);
			const m = k && t.subtype === "success" && !d && A.pendingByIndex.size === 0 && A.startedIds.size === 0 && A.resultDeliveredIds.size === 0;
			y = {
				...x,
				text: d,
				...(f.length > 1 || y?.textParts || t.openclaw_interim_result === true) && !(r && !s) ? { textParts: f } : {},
				...m ? {
					errorText: CLAUDE_SYNTHETIC_NO_RESPONSE_ERROR,
					terminalFailure: { reason: "synthetic_no_response" }
				} : {},
				...r && !s ? {
					text: "",
					errorText: i,
					terminalFailure: r
				} : {},
				...g ? { resumeCheckpointId: g } : {},
				...y?.interimNativeReplies ? { interimNativeReplies: y.interimNativeReplies } : {},
				...v ? { diagnosticUsage: v } : {}
			};
			y = withCliRawFinalText(y, x.text?.trim() || finalStreamedMessageText());
			if (t.openclaw_interim_result === true && p && !y.errorText && !y.terminalFailure) {
				const t = y.rawFinalText ?? s;
				if (h && g && t) y.interimNativeReplies = [...y.interimNativeReplies ?? [], {
					text: t,
					cliSessionId: h,
					externalId: g
				}];
				e.onCompletedReply?.(p, f.length - 1);
			}
			resetReplySegment();
			return;
		}
		T = recordItemText(t, w, T);
		if (t.type === "stream_event" && isRecord(t.event)) {
			const e = t.event;
			if (e.type === "message_start") {
				const t = isRecord(e.message) ? e.message : void 0;
				beginClaudeMessage(typeof t?.id === "string" ? t.id : void 0);
			} else if (e.type === "message_stop") finishTaggedReasoningMessage();
			const n = e.type === "content_block_start" && isRecord(e.content_block) && isClaudeToolUseBlockType(e.content_block.type);
			if (n) {
				f = true;
				T = void 0;
				p = true;
			}
			if (M) {
				if (n) flushPendingClaudeText("commentary");
				else if (e.type === "content_block_start" || e.type === "message_stop") flushPendingClaudeText("assistant");
			}
		}
		if (e.onThinkingDelta || e.onThinkingProgress) dispatchClaudeCliThinking({
			backend: e.backend,
			providerId: e.providerId,
			parsed: t,
			tracker: N,
			onThinkingDelta: e.onThinkingDelta,
			onThinkingProgress: e.onThinkingProgress
		});
		const S = parseClaudeCliStreamingDelta({
			backend: e.backend,
			providerId: e.providerId,
			parsed: t,
			previousText: o
		});
		if (S) {
			o = `${o}${S}`;
			if (P) routeTaggedReasoningDeltas(F.push(S));
			else emitClaudeVisibleText(S);
		}
		if (e.onToolUseStart || e.onToolResult) dispatchGeminiCliStreamingToolEvent({
			backend: e.backend,
			providerId: e.providerId,
			parsed: t,
			tracker: A,
			onToolUseStart: e.onToolUseStart,
			onToolResult: e.onToolResult
		});
		if (P || e.onToolUseStart || e.onToolInputDelta || e.onToolResult) {
			const n = P && t.type === "assistant" ? (t) => {
				f = true;
				T = void 0;
				p = true;
				if (M) flushPendingClaudeText("commentary");
				e.onToolUseStart?.(t);
			} : e.onToolUseStart;
			dispatchClaudeCliStreamingToolEvent({
				backend: e.backend,
				providerId: e.providerId,
				parsed: t,
				tracker: A,
				onToolUseStart: n,
				onToolInputDelta: e.onToolInputDelta,
				onToolResult: e.onToolResult
			});
		}
		if (!S && isGeminiStreamJsonDialect(e)) {
			if (t.type === "message" && t.role === "assistant" && typeof t.content === "string" && t.content) {
				if (f) {
					c = n.length;
					f = false;
				}
				appendAssistantText(t.content);
			} else if (t.type === "result" && t.status === "success") y = withCliRawFinalText({
				text: n.trim(),
				sessionId: h,
				usage: _
			}, finalStreamedMessageText());
		}
	};
	const handleJsonlLine = (e) => {
		if (b) return;
		const n = e.trim();
		if (!n && !P) return;
		S += 1;
		if (!P && S > j.maxTurnLines) {
			b = streamJsonOutputLimitErrorText("lines", j.maxTurnLines);
			t.pending = "";
			return;
		}
		if (!n) {
			accountClaudeJsonlLine(e.length);
			return;
		}
		if (handleCustomJsonlLine(n, e)) return;
		const r = decodeCliRecords(n);
		if (P) {
			const t = r.length === 1 ? r[0] : void 0;
			const n = chargeClaudeStreamJsonLine(t, e);
			if (!accountClaudeJsonlLine(n.chars, n.countsFrame)) return;
		}
		for (const e of r) handleParsedRecord(e);
	};
	return {
		push(e) {
			if (!e || b) return;
			if (!P) {
				x += e.length;
				if (x > j.maxTurnRawChars) {
					b = streamJsonOutputLimitErrorText("raw", j.maxTurnRawChars);
					t.pending = "";
					return;
				}
			}
			if (!frameBoundedCliJsonlChunk(t, e, (e) => {
				handleJsonlLine(e);
				return !b;
			})) b = streamJsonOutputLimitErrorText("line", j.maxPendingLineChars);
		},
		finish() {
			try {
				if (b) return;
				const e = t.pending;
				t.pending = "";
				if (e) handleJsonlLine(e);
				finishTaggedReasoningMessage();
				if (M) flushPendingClaudeText("assistant");
			} finally {
				A.inputProgressById.clear();
			}
		},
		getErrorText() {
			return b || null;
		},
		hasTerminalResult() {
			return O;
		},
		getOutput() {
			if (b) return {
				text: "",
				sessionId: h,
				usage: _,
				...v ? { diagnosticUsage: v } : {},
				errorText: b
			};
			if (y) return y;
			return resolveCliStreamOutput({
				params: e,
				texts: w,
				assistantText: n,
				sessionId: h,
				usage: _,
				resumeCheckpointId: g,
				rawLines: S,
				sawCustomJsonlEvent: E,
				sawGeminiStructuredOutput: D,
				claudeStreamJson: P,
				finalStreamedMessageText
			});
		}
	};
}
//#endregion
//#region src/agents/cli-output.ts
/**
* Parses output from CLI-backed model providers. It supports plain text, JSON,
* JSONL streaming, Claude stream-json dialects, usage metadata, and tool event
* reconstruction.
*/
function normalizeCliContextValue(e) {
	const t = e?.trim().replace(/\s+/g, " ");
	return t ? truncateUtf16Safe(t, 200) : void 0;
}
function formatCliOutputError(e, t = {}) {
	const n = e.terminalFailure;
	if (n?.reason !== "max_turns" && n?.reason !== "turn_stopped") return e.errorText || "CLI failed.";
	const r = normalizeCliContextValue(t.runId);
	const i = normalizeCliContextValue(t.sessionId);
	const a = normalizeCliContextValue(e.sessionId);
	const o = [
		r ? `OpenClaw run: ${r}.` : void 0,
		i ? `OpenClaw session: ${i}.` : void 0,
		a ? `Claude session: ${a}.` : void 0
	].filter((e) => Boolean(e));
	const s = n.reason === "max_turns";
	const c = !s && (n.terminalReason === "hook_stopped" || n.terminalReason === "stop_hook_prevented");
	return [
		s ? `Claude CLI stopped after reaching the maximum number of turns${n.limit ? ` (limit: ${n.limit})` : ""}.` : describeClaudeTurnStop(n),
		...o,
		"Tool actions may already have run; verify their effects before retrying.",
		...s ? ["Retry with a higher --max-turns value or a narrower task."] : c ? ["A Claude Code hook stopped this turn; user-scope hooks (including plugin hooks) apply to headless runs — move or disable that hook."] : []
	].join(" ");
}
function parseCliOutput(e) {
	const t = e.outputMode ?? "text";
	if (t === "jsonl") {
		const t = createCliJsonlStreamingParser({
			backend: e.backend,
			providerId: e.providerId,
			onAssistantDelta: () => {}
		});
		t.push(e.raw);
		t.finish();
		const n = t.getOutput();
		if (n) return n;
		if (supportsCliJsonlToolEvents(e)) return {
			text: "",
			sessionId: e.fallbackSessionId,
			errorText: CLI_STREAM_JSON_MISSING_RESULT_ERROR
		};
	} else if (t !== "text") {
		const t = parseCliJson(e.raw, e.backend, e.providerId);
		if (t) return t;
	}
	return {
		text: e.raw.trim(),
		sessionId: e.fallbackSessionId
	};
}
/** Extracts a human-readable error message from mixed CLI stderr/stdout text. */
function extractCliErrorMessage(e) {
	const t = decodeCliRecords(e);
	let n = "";
	for (const e of t) {
		const t = collectExplicitCliErrorText(e);
		if (t) n = t;
	}
	return n || null;
}
//#endregion
//#region src/agents/cli-runner/exit-error.ts
function stopFallbackAfterToolEffects(e, t) {
	if (((t.toolSummary?.calls ?? 0) > 0 || hasAcceptedSessionSpawn(t.acceptedSessionSpawns)) && e instanceof Error) recordModelFallbackStop(e);
}
function createCliFailoverError(e, t, n, r) {
	return new FailoverError(e, {
		reason: t,
		...n,
		status: resolveFailoverStatus(t),
		...r
	});
}
const refusedStreamOutputs = /* @__PURE__ */ new WeakMap();
/** Refuses unparseable CLI output while retaining the stream's partial facts for the runner. */
function createCliStreamRefusalError(e, t, n, r) {
	const i = createCliFailoverError(e, "format", t, r);
	if (n) refusedStreamOutputs.set(i, n);
	return i;
}
function readCliStreamRefusalOutput(e) {
	return e instanceof FailoverError ? refusedStreamOutputs.get(e) : void 0;
}
/** Adds the run's tool facts to a refused stream's partial output, as a returned turn carries them. */
function recordCliStreamRefusalToolEffects(e, t) {
	const n = readCliStreamRefusalOutput(e);
	if (n && e instanceof FailoverError) refusedStreamOutputs.set(e, {
		...n,
		...t
	});
}
function resolveCliResumeAtError(e, t, n) {
	if (isFailoverError(e) || isAbortError(e)) return;
	const r = formatErrorMessage(e).toLowerCase();
	const i = Boolean(t?.resumeAtArg && r.includes(t.resumeAtArg.toLowerCase()) && /\b(?:unknown|unexpected|unrecognized)\b|\bnot\s+recognized\b/.test(r));
	const a = Boolean(t?.resumeCheckpointId && r.includes(t.resumeCheckpointId.toLowerCase()) && /\bno\s+message\s+found\s+with\s+message\.uuid\b/.test(r));
	if (!i && !a) return;
	return createCliFailoverError("CLI backend cannot resume from the stored checkpoint.", "session_expired", n, {
		code: "cli_resume_at_unsupported",
		cause: e
	});
}
function createCliExitFailoverError(e) {
	const t = e.candidates.map((e) => e.trim()).filter(Boolean);
	const n = t.map((e) => extractCliErrorMessage(e)).find(Boolean) ?? null;
	const r = resolveCliResumeAtError(n || t[0] || "CLI failed.", {
		resumeAtArg: e.resumeAtArg,
		resumeCheckpointId: e.resumeCheckpointId
	}, e.context);
	if (r) return r;
	const i = [n, ...t].flatMap((t) => t ? [coerceToFailoverError(t, e.context)] : []).find((e) => e !== null);
	const a = n || i?.message || t[0] || "CLI failed.";
	const o = i?.reason ?? "unknown";
	const s = o === "context_overflow" ? "cli_context_overflow" : t.length === 0 && e.retryEmptyFailure ? "cli_unknown_empty_failure" : e.classifyErrorCode?.(a);
	return createCliFailoverError(a, o, e.context, { code: s });
}
//#endregion
//#region src/agents/cli-runner/cli-live-session-registry.ts
const MAX_LIVE_SESSIONS = 16;
const MIN_FREE_MEMORY_BYTES = 1024 ** 3;
const liveSessions = /* @__PURE__ */ new Map();
const retiredSessionCleanup = /* @__PURE__ */ new Map();
const retiringSessionHandles = /* @__PURE__ */ new WeakSet();
function buildCliLiveRegistryKey(e) {
	return `${e.backendId}:${buildCliLiveOwnerKey(e)}`;
}
/** One conversation owns the queue and process slot, regardless of its inbound route. */
function buildCliLiveOwnerKey(e) {
	return sha256Hex(JSON.stringify({
		agentId: e.agentId,
		sessionId: e.sessionId,
		sessionKey: e.sessionKey
	}));
}
function buildCliLiveSessionKey(e) {
	return buildCliLiveRegistryKey({
		backendId: e.backendResolved.id,
		agentId: e.params.agentId,
		sessionId: e.params.sessionId,
		sessionKey: e.params.sessionKey
	});
}
/** Returns whether this owner still has an in-process plugin-owned session. */
function hasCliLiveSession(e) {
	return getCliLiveSessionGeneration(e) !== void 0;
}
/** Returns the opaque generation of this owner's registered execution session. */
function getCliLiveSessionGeneration(e) {
	return liveSessions.get(buildCliLiveRegistryKey(e))?.handle.generation;
}
/** Reads owner-private standing approvals only from this exact current live process. */
function getCliLiveSessionApprovalGrants(e) {
	const t = liveSessions.get(buildCliLiveSessionKey(e));
	return t?.owner === e.preparedBackend ? t.approvalGrants : void 0;
}
async function closeCliLiveSession(e, t) {
	await runCliCleanup(e.params, "cli-live-session-close", async () => {
		await e.preparedBackend.closeLiveSession?.(t);
	});
}
/** Explicit fresh/fork execution owns replacement of the current idle process. */
async function restartCliLiveSession(e, t = e.params.abortSignal) {
	const n = createCliRunCurrentAssertion(e.params, t);
	n();
	const r = buildCliLiveSessionKey(e);
	const i = liveSessions.get(r);
	const a = retiredSessionCleanup.get(r);
	await runCliCleanup(e.params, "cli-live-session-close", async () => {
		n();
		await e.preparedBackend.closeLiveSession?.("restart");
		await a;
	}, "required");
	if (i) await runCliCleanup(e.params, "cli-live-session-restart", () => {
		n();
		return closeRecord(i, "restart");
	}, "required");
	n();
}
async function closeRecord(e, t) {
	if (!e.cleanupPromise) e.handle.close(t);
	await (e.cleanupPromise ?? e.handle.waitForExit());
}
/** Retire warm processes and join resources already waiting for their exit. */
async function disposeAllCliLiveSessions() {
	const e = (await Promise.allSettled([...retiredSessionCleanup.values(), ...Array.from(liveSessions.values()).map((e) => closeRecord(e, "abort"))])).find((e) => e.status === "rejected");
	if (e) throw e.reason;
}
function retainCleanup(e, t) {
	const n = e.preparedBackend;
	t.owner = n;
	n.closeLiveSession = async (e) => {
		if (t.owner === n || t.cleanupPromise) await closeRecord(t, e);
	};
}
function createCapacityError(e, t, n) {
	return createCliFailoverError(t, "rate_limit", {
		provider: e.params.provider,
		model: e.modelId,
		sessionId: e.params.sessionId,
		lane: e.params.lane
	}, n ? { code: n } : void 0);
}
function ensureCliLiveSessionCapacity(e) {
	if (liveSessions.size < MAX_LIVE_SESSIONS) return;
	for (const { handle: e } of liveSessions.values()) if (e.isIdle()) {
		e.close("idle");
		return;
	}
	throw createCapacityError(e, "Too many CLI live sessions are active.");
}
/**
* Before a turn may start a new warm process, retire least recently used idle
* processes while host memory is low. Busy processes stay; the turn fails over.
*/
async function ensureCliLiveSessionMemory(e, t) {
	const n = createCliRunCurrentAssertion(e.params, t);
	n();
	if (liveSessions.has(buildCliLiveSessionKey(e))) return;
	for (const e of Array.from(liveSessions.values())) {
		n();
		if (!e.handle.isIdle()) continue;
		if (readHostFreeMemoryBytes() >= MIN_FREE_MEMORY_BYTES) return;
		cliBackendLog.warn(`cli live session memory pressure: closing idle session activeSessions=${liveSessions.size}`);
		await racePromiseWithAbortSignal(() => closeRecord(e, "idle"), t);
	}
	n();
	if (readHostFreeMemoryBytes() < MIN_FREE_MEMORY_BYTES) throw createCapacityError(e, "Host memory is too low for another CLI live session.", CLI_LIVE_SESSION_HOST_MEMORY_ERROR_CODE);
}
/** Returns whether this prepared local plugin transport may retain its execution process. */
function acceptsCliLiveSession(e) {
	return e.executionTarget.kind === "plugin" && e.preparedBackend.backend.liveSession !== void 0 && e.preparedBackend.backend.output === "jsonl" && e.preparedBackend.backend.input === "stdin";
}
/** Creates host-owned lifecycle authority without exposing owner keys or bearer material. */
function createCliLiveSessionCapability(e) {
	const t = buildCliLiveSessionKey(e.context);
	const n = e.context;
	const r = n.preparedBackend.mcpClientGrantCapture;
	const i = e.env.OPENCLAW_MCP_TOKEN === r?.transportToken;
	const a = Boolean(n.preparedBackend.mcpConfigHash);
	const o = n.params.skillsSnapshot;
	const s = o ? sha256Hex(JSON.stringify({
		promptHash: sha256Hex(o.prompt),
		skillFilter: o.skillFilter,
		skills: o.skills,
		librarySelections: o.librarySelections,
		resolvedSkills: (o.resolvedSkills ?? []).map((e) => ({
			name: e.name,
			description: e.description,
			contentHash: e.contentHash,
			filePath: e.filePath,
			sourceInfo: e.sourceInfo
		})),
		version: o.resolvedSkills?.every((e) => Boolean(e.contentHash)) ? void 0 : o.version
	})) : void 0;
	const c = new Set([
		n.preparedBackend.backend.systemPromptArg,
		n.preparedBackend.backend.systemPromptFileArg,
		"--session-id",
		"--resume",
		"-r"
	].filter((e) => typeof e === "string" && e.length > 0));
	const l = new Set([
		a ? "--mcp-config" : void 0,
		s ? "--plugin-dir" : void 0,
		s ? "--plugin-dir-no-mcp" : void 0
	].filter((e) => typeof e === "string" && e.length > 0));
	const u = [];
	for (let t = 0; t < e.argv.length; t += 1) {
		const n = e.argv[t] ?? "";
		if (c.has(n)) {
			t += 1;
			continue;
		}
		if ([...c].some((e) => n.startsWith(`${e}=`))) continue;
		if (l.has(n)) {
			u.push("<unstable>");
			t += 1;
			continue;
		}
		if ([...l].some((e) => n.startsWith(`${e}=`))) {
			u.push("<unstable>");
			continue;
		}
		u.push(n);
	}
	const d = sha256Hex(JSON.stringify({
		argv: u,
		argv0: e.argv0,
		workspaceDirHash: sha256Hex(n.workspaceDir),
		cwdHash: n.cwdHash ?? sha256Hex(n.cwd ?? n.workspaceDir),
		provider: n.params.provider,
		model: n.normalizedModel,
		systemPromptHash: sha256Hex(n.systemPrompt),
		agentAccountId: n.params.agentAccountId,
		authProfileIdHash: n.effectiveAuthProfileId ? sha256Hex(n.effectiveAuthProfileId) : void 0,
		authEpochHash: n.authEpoch ? sha256Hex(n.authEpoch) : void 0,
		extraSystemPromptHash: n.extraSystemPromptHash,
		promptToolNamesHash: n.promptToolNamesHash,
		mcpResumeHash: n.preparedBackend.mcpResumeHash ?? n.preparedBackend.mcpConfigHash,
		credentialFingerprint: n.preparedBackend.secretInput?.fingerprint,
		nativeLoginOwnerHash: n.cliHistoryWriter?.bindsNativeLogin ? sha256Hex(n.cliHistoryWriter.authFingerprint) : void 0,
		skillsFingerprint: s,
		env: Object.keys(e.env).toSorted().filter((e) => e !== "OPENCLAW_MCP_CLI_CAPTURE_KEY").map((t) => [t, t === "OPENCLAW_MCP_TOKEN" && i ? "<managed-mcp-grant>" : e.env[t] ? sha256Hex(e.env[t]) : ""])
	}));
	const f = e.context.preparedBackend.mcpClientGrantCapture;
	if (Boolean(f) !== Boolean(e.captureKey)) throw new Error("CLI live process and current turn disagree about MCP capture ownership.");
	const requiredSessionError = (t) => createCliFailoverError("Managed CLI live session is no longer reusable.", "session_expired", {
		provider: e.context.params.provider,
		model: e.context.modelId,
		sessionId: e.context.params.sessionId,
		lane: e.context.params.lane
	}, { code: t });
	const p = createCliRunCurrentAssertion(e.context.params, e.abortSignal);
	const requireRegisteredRecord = (n) => {
		p();
		const r = liveSessions.get(t);
		if (n.fingerprint !== d || r?.handle !== n) throw new Error("CLI live session no longer belongs to this admitted run.");
		if (e.requiredGeneration && e.requiredGeneration !== n.generation) throw requiredSessionError("cli_live_session_changed");
		return r;
	};
	return Object.freeze({
		fingerprint: d,
		current: () => {
			p();
			const n = liveSessions.get(t)?.handle;
			if (e.requiredGeneration && n?.generation !== e.requiredGeneration) throw requiredSessionError(n ? "cli_live_session_changed" : "cli_live_session_missing");
			if (e.requiredGeneration && n?.fingerprint !== d) throw requiredSessionError("cli_live_session_changed");
			return n;
		},
		restart: async () => {
			p();
			if (e.requiredGeneration) throw requiredSessionError("cli_live_session_changed");
			await restartCliLiveSession(e.context, e.abortSignal);
		},
		register: (n) => {
			p();
			if (retiredSessionCleanup.has(t)) throw new Error("Previous CLI live session cleanup has not settled.");
			if (e.requiredGeneration) throw requiredSessionError("cli_live_session_changed");
			if (n.fingerprint !== d || !n.generation.trim() || liveSessions.has(t) || retiringSessionHandles.has(n) || Array.from(liveSessions.values()).some((e) => e.handle === n)) throw new Error("CLI live session registration does not match its admitted owner.");
			ensureCliLiveSessionCapacity(e.context);
			const r = e.claimResources?.();
			const i = {
				handle: n,
				owner: e.context.preparedBackend,
				approvalGrants: /* @__PURE__ */ new Set(),
				...r ? { cleanup: r } : {},
				...f && e.captureKey ? { capture: {
					token: f.transportToken,
					key: e.captureKey,
					revoke: f.revokeProcessToken
				} } : {}
			};
			liveSessions.set(t, i);
			retainCleanup(e.context, i);
			cliBackendLog.info(`cli live session start: provider=${e.context.backendResolved.id} model=${e.context.normalizedModel} activeSessions=${liveSessions.size}`);
		},
		activate: (n) => {
			const r = requireRegisteredRecord(n);
			if (Boolean(r.capture) !== Boolean(f)) throw new Error("CLI live session MCP topology changed across admitted turns.");
			if (r.capture && f) {
				f.adoptProcessToken(r.capture.token);
				requireRegisteredRecord(n);
				e.beginCapture(r.capture.key);
			}
			retainCleanup(e.context, r);
			liveSessions.delete(t);
			liveSessions.set(t, r);
		},
		remove: (e) => {
			const n = liveSessions.get(t);
			if (n?.handle !== e) return;
			n.capture?.revoke();
			liveSessions.delete(t);
			n.approvalGrants.clear();
			retiringSessionHandles.add(e);
			n.cleanupPromise = Promise.resolve().then(() => e.waitForExit()).then(() => n.cleanup?.()).finally(() => {
				retiringSessionHandles.delete(e);
				if (retiredSessionCleanup.get(t) === n.cleanupPromise) retiredSessionCleanup.delete(t);
			});
			retiredSessionCleanup.set(t, n.cleanupPromise);
			n.cleanupPromise.catch((e) => {
				cliBackendLog.warn(`cli live session cleanup failed: ${String(e)}`);
			});
		}
	});
}
//#endregion
export { isClaudeForegroundAgentToolName as C, sequenceCliCleanups as D, runCliCleanup as E, isClaudeCliProvider as S, isClaudeToolUseBlockType as T, stopFallbackAfterToolEffects as _, disposeAllCliLiveSessions as a, createCliJsonlStreamingParser as b, getCliLiveSessionGeneration as c, createCliExitFailoverError as d, createCliFailoverError as f, resolveCliResumeAtError as g, recordCliStreamRefusalToolEffects as h, createCliLiveSessionCapability as i, hasCliLiveSession as l, readCliStreamRefusalOutput as m, buildCliLiveOwnerKey as n, ensureCliLiveSessionMemory as o, createCliStreamRefusalError as p, closeCliLiveSession as r, getCliLiveSessionApprovalGrants as s, acceptsCliLiveSession as t, restartCliLiveSession as u, formatCliOutputError as v, isClaudeToolResultBlockType as w, transformCliResultText as x, parseCliOutput as y };