import { s as normalizeOptionalString } from "./string-coerce-CIT1-v_a.js";
import "./runtime-DvDGh8U9.js";
import { l as resolveLoaderPackageRoot } from "./sdk-alias-Czt6OgXf.js";
import { t as findBundledPluginMetadataById } from "./bundled-plugin-metadata-AEhTUUZp.js";
import { t as normalizeBundledPluginArtifactSubpath } from "./public-surface-runtime-D0G15uBG.js";
import "./safe-text-ChDECSB-.js";
import "./registry-DBOuapU8.js";
import { t as normalizeChatType } from "./chat-type-Bzu1kXBu.js";
import { t as resolveConversationLabel } from "./conversation-label-C_QzGmCa.js";
import { i as loadBundledPluginPublicSurfaceModuleSync } from "./facade-loader-DnyIP17h.js";
import "./system-events-CAYHEKX1.js";
import "./call-BbnBxegf.js";
import { i as toAcpRuntimeError } from "./errors-D7NmF8w-.js";
import "./manager-C2wmIxL8.js";
import { n as parseInlineDirectives } from "./directive-handling.parse-7twiWiev.js";
import "./directive-handling.defaults-CcMMlB9Q.js";
import { t as buildCommandContext } from "./commands-context-mNjoy0Tm.js";
import { n as vi, s as it, t as globalExpect } from "./test.p_J6dB8a-Dyq-JxSD.js";
import "./channel-test-registry-DwsIIoes.js";
import "./provider-auth-choice.runtime-Cy08b4wB.js";
import "./state-dir-env-DMdJ7sn9.js";
import "./commands-acp-BPI9eUv1.js";
import "./directive-handling.shared-B1jZLaWy.js";
import "./directive-handling.impl-BOSph54T.js";
import "./directive-handling.fast-lane-DlxTFkXb.js";
import "./directive-handling.persist-DddJz6Nu.js";
import "./temp-home-B6M9TKRF.js";
import { fileURLToPath } from "node:url";
import path from "node:path";
import fs from "node:fs/promises";
import { randomUUID } from "node:crypto";
//#region src/channels/sender-identity.ts
function validateSenderIdentity(ctx) {
	const issues = [];
	const isDirect = normalizeChatType(ctx.ChatType) === "direct";
	const senderId = normalizeOptionalString(ctx.SenderId) || "";
	const senderName = normalizeOptionalString(ctx.SenderName) || "";
	const senderUsername = normalizeOptionalString(ctx.SenderUsername) || "";
	const senderE164 = normalizeOptionalString(ctx.SenderE164) || "";
	if (!isDirect) {
		if (!senderId && !senderName && !senderUsername && !senderE164) issues.push("missing sender identity (SenderId/SenderName/SenderUsername/SenderE164)");
	}
	if (senderE164) {
		if (!/^\+\d{3,}$/.test(senderE164)) issues.push(`invalid SenderE164: ${senderE164}`);
	}
	if (senderUsername) {
		if (senderUsername.includes("@")) issues.push(`SenderUsername should not include "@": ${senderUsername}`);
		if (/\s/.test(senderUsername)) issues.push(`SenderUsername should not include whitespace: ${senderUsername}`);
	}
	if (ctx.SenderId != null && !senderId) issues.push("SenderId is set but empty");
	return issues;
}
//#endregion
//#region src/channels/plugins/contracts/test-helpers.ts
function primeChannelOutboundSendMock(sendMock, fallbackResult, sendResults = []) {
	sendMock.mockReset();
	if (sendResults.length === 0) {
		sendMock.mockResolvedValue(fallbackResult);
		return;
	}
	for (const result of sendResults) sendMock.mockResolvedValueOnce(result);
}
function expectChannelInboundContextContract(ctx) {
	globalExpect(validateSenderIdentity(ctx)).toEqual([]);
	globalExpect(ctx.Body).toBeTypeOf("string");
	globalExpect(ctx.BodyForAgent).toBeTypeOf("string");
	globalExpect(ctx.BodyForCommands).toBeTypeOf("string");
	const chatType = normalizeChatType(ctx.ChatType);
	if (chatType && chatType !== "direct") globalExpect(ctx.ConversationLabel?.trim() || resolveConversationLabel(ctx)).toBeTruthy();
}
//#endregion
//#region src/channels/plugins/contracts/inbound-testkit.ts
function createInboundContextCapture() {
	return { ctx: void 0 };
}
function buildDispatchInboundCaptureMock(actual, setCtx) {
	const dispatchInboundMessage = vi.fn(async (params) => {
		setCtx(params.ctx);
		return {
			queuedFinal: false,
			counts: {
				tool: 0,
				block: 0,
				final: 0
			}
		};
	});
	return {
		...actual,
		dispatchInboundMessage,
		dispatchInboundMessageWithDispatcher: dispatchInboundMessage,
		dispatchInboundMessageWithBufferedDispatcher: dispatchInboundMessage
	};
}
createInboundContextCapture();
//#endregion
//#region src/cli/test-runtime-capture.ts
function normalizeRuntimeStdout(value) {
	return value.endsWith("\n") ? value.slice(0, -1) : value;
}
function stringifyRuntimeJson(value, space = 2) {
	return JSON.stringify(value, null, space > 0 ? space : void 0);
}
function createCliRuntimeCapture() {
	const runtimeLogs = [];
	const runtimeErrors = [];
	const stringifyArgs = (args) => args.map((value) => String(value)).join(" ");
	const defaultRuntime = {
		log: vi.fn((...args) => {
			runtimeLogs.push(stringifyArgs(args));
		}),
		error: vi.fn((...args) => {
			runtimeErrors.push(stringifyArgs(args));
		}),
		writeStdout: vi.fn((value) => {
			defaultRuntime.log(normalizeRuntimeStdout(value));
		}),
		writeJson: vi.fn((value, space = 2) => {
			defaultRuntime.log(stringifyRuntimeJson(value, space));
		}),
		exit: vi.fn((code) => {
			throw new Error(`__exit__:${code}`);
		})
	};
	return {
		runtimeLogs,
		runtimeErrors,
		defaultRuntime,
		resetRuntimeCapture: () => {
			runtimeLogs.length = 0;
			runtimeErrors.length = 0;
		}
	};
}
function spyRuntimeLogs(runtime) {
	return vi.spyOn(runtime, "log").mockImplementation(() => {});
}
function spyRuntimeErrors(runtime) {
	return vi.spyOn(runtime, "error").mockImplementation(() => {});
}
function spyRuntimeJson(runtime) {
	return vi.spyOn(runtime, "writeJson").mockImplementation(() => {});
}
function firstWrittenJsonArg(writeJson) {
	return writeJson.mock.calls[0]?.[0] ?? null;
}
//#endregion
//#region src/agents/sandbox/test-fixtures.ts
function createSandboxTestContext(params) {
	const overrides = params?.overrides ?? {};
	const { docker: _unusedDockerOverrides, ...sandboxOverrides } = overrides;
	const docker = {
		image: "kaijibot-sandbox:bookworm-slim",
		containerPrefix: "kaijibot-sbx-",
		network: "none",
		user: "1000:1000",
		workdir: "/workspace",
		readOnlyRoot: false,
		tmpfs: [],
		capDrop: [],
		seccompProfile: "",
		apparmorProfile: "",
		setupCommand: "",
		binds: [],
		dns: [],
		extraHosts: [],
		pidsLimit: 0,
		...overrides.docker,
		...params?.dockerOverrides
	};
	return {
		enabled: true,
		backendId: "docker",
		sessionKey: "sandbox:test",
		workspaceDir: "/tmp/workspace",
		agentWorkspaceDir: "/tmp/workspace",
		workspaceAccess: "rw",
		runtimeId: "kaijibot-sbx-test",
		runtimeLabel: "kaijibot-sbx-test",
		containerName: "kaijibot-sbx-test",
		containerWorkdir: "/workspace",
		tools: {
			allow: ["*"],
			deny: []
		},
		browserAllowHostControl: false,
		...sandboxOverrides,
		docker
	};
}
//#endregion
//#region src/agents/skills.e2e-test-helpers.ts
async function writeSkill(params) {
	const { dir, name, description, metadata, body, frontmatterExtra } = params;
	await fs.mkdir(dir, { recursive: true });
	const frontmatter = [
		`name: ${name}`,
		`description: ${description}`,
		metadata ? `metadata: ${metadata}` : "",
		frontmatterExtra ?? ""
	].filter((line) => line.trim().length > 0).join("\n");
	await fs.writeFile(path.join(dir, "SKILL.md"), `---\n${frontmatter}\n---

${body ?? `# ${name}\n`}
`, "utf-8");
}
//#endregion
//#region src/acp/runtime/adapter-contract.testkit.ts
async function runAcpRuntimeAdapterContract(params) {
	const runtime = await params.createRuntime();
	const sessionKey = `agent:${params.agentId ?? "codex"}:acp:contract-${randomUUID()}`;
	const agent = params.agentId ?? "codex";
	const handle = await runtime.ensureSession({
		sessionKey,
		agent,
		mode: "persistent"
	});
	globalExpect(handle.sessionKey).toBe(sessionKey);
	globalExpect(handle.backend.trim()).not.toHaveLength(0);
	globalExpect(handle.runtimeSessionName.trim()).not.toHaveLength(0);
	const successEvents = [];
	for await (const event of runtime.runTurn({
		handle,
		text: params.successPrompt ?? "contract-success",
		mode: "prompt",
		requestId: `contract-success-${randomUUID()}`
	})) successEvents.push(event);
	globalExpect(successEvents.some((event) => event.type === "done" || event.type === "text_delta" || event.type === "status" || event.type === "tool_call")).toBe(true);
	await params.assertSuccessEvents?.(successEvents);
	if (params.includeControlChecks ?? true) {
		if (runtime.getStatus) {
			const status = await runtime.getStatus({ handle });
			globalExpect(status).toBeDefined();
			globalExpect(typeof status).toBe("object");
		}
		if (runtime.setMode) await runtime.setMode({
			handle,
			mode: "contract"
		});
		if (runtime.setConfigOption) await runtime.setConfigOption({
			handle,
			key: "contract_key",
			value: "contract_value"
		});
	}
	let errorThrown = null;
	const errorEvents = [];
	const errorPrompt = normalizeOptionalString(params.errorPrompt);
	if (errorPrompt) {
		try {
			for await (const event of runtime.runTurn({
				handle,
				text: errorPrompt,
				mode: "prompt",
				requestId: `contract-error-${randomUUID()}`
			})) errorEvents.push(event);
		} catch (error) {
			errorThrown = error;
		}
		const sawErrorEvent = errorEvents.some((event) => event.type === "error");
		globalExpect(Boolean(errorThrown) || sawErrorEvent).toBe(true);
		if (errorThrown) {
			const acpError = toAcpRuntimeError({
				error: errorThrown,
				fallbackCode: "ACP_TURN_FAILED",
				fallbackMessage: "ACP runtime contract expected an error turn failure."
			});
			globalExpect(acpError.code.length).toBeGreaterThan(0);
			globalExpect(acpError.message.length).toBeGreaterThan(0);
		}
	}
	await params.assertErrorOutcome?.({
		events: errorEvents,
		thrown: errorThrown
	});
	await runtime.cancel({
		handle,
		reason: "contract-cancel"
	});
	await runtime.close({
		handle,
		reason: "contract-close"
	});
}
//#endregion
//#region src/auto-reply/reply/commands.test-harness.ts
function buildCommandTestParams$1(commandBody, cfg, ctxOverrides, options) {
	const ctx = {
		Body: commandBody,
		CommandBody: commandBody,
		CommandSource: "text",
		CommandAuthorized: true,
		Provider: "whatsapp",
		Surface: "whatsapp",
		...ctxOverrides
	};
	return {
		ctx,
		cfg,
		command: buildCommandContext({
			ctx,
			cfg,
			isGroup: false,
			triggerBodyNormalized: commandBody.trim(),
			commandAuthorized: true
		}),
		directives: parseInlineDirectives(commandBody),
		elevated: {
			enabled: true,
			allowed: true,
			failures: []
		},
		sessionKey: "agent:main:main",
		workspaceDir: options?.workspaceDir ?? "/tmp",
		defaultGroupActivation: () => "mention",
		resolvedVerboseLevel: "off",
		resolvedReasoningLevel: "off",
		resolveDefaultThinkingLevel: async () => void 0,
		provider: "whatsapp",
		model: "test-model",
		contextTokens: 0,
		isGroup: false
	};
}
//#endregion
//#region src/auto-reply/reply/commands-spawn.test-harness.ts
function buildCommandTestParams(commandBody, cfg, ctxOverrides) {
	return buildCommandTestParams$1(commandBody, cfg, ctxOverrides);
}
//#endregion
//#region src/test-helpers/windows-cmd-shim.ts
async function createWindowsCmdShimFixture(params) {
	await fs.mkdir(path.dirname(params.scriptPath), { recursive: true });
	await fs.mkdir(path.dirname(params.shimPath), { recursive: true });
	await fs.writeFile(params.scriptPath, "module.exports = {};\n", "utf8");
	await fs.writeFile(params.shimPath, `@echo off\r\n${params.shimLine}\r\n`, "utf8");
}
//#endregion
//#region src/test-helpers/resolve-target-error-cases.ts
function installCommonResolveTargetErrorCases(params) {
	const { resolveTarget, implicitAllowFrom } = params;
	it("should error on normalization failure with allowlist (implicit mode)", () => {
		const result = resolveTarget({
			to: "invalid-target",
			mode: "implicit",
			allowFrom: implicitAllowFrom
		});
		globalExpect(result.ok).toBe(false);
		globalExpect(result.error).toBeDefined();
	});
	it("should error when no target provided with allowlist", () => {
		const result = resolveTarget({
			to: void 0,
			mode: "implicit",
			allowFrom: implicitAllowFrom
		});
		globalExpect(result.ok).toBe(false);
		globalExpect(result.error).toBeDefined();
	});
	it("should error when no target and no allowlist", () => {
		const result = resolveTarget({
			to: void 0,
			mode: "explicit",
			allowFrom: []
		});
		globalExpect(result.ok).toBe(false);
		globalExpect(result.error).toBeDefined();
	});
	it("should handle whitespace-only target", () => {
		const result = resolveTarget({
			to: "   ",
			mode: "explicit",
			allowFrom: []
		});
		globalExpect(result.ok).toBe(false);
		globalExpect(result.error).toBeDefined();
	});
}
//#endregion
//#region src/test-utils/chunk-test-helpers.ts
function countLines(text) {
	return text.split("\n").length;
}
function hasBalancedFences(chunk) {
	let open = null;
	for (const line of chunk.split("\n")) {
		const match = line.match(/^( {0,3})(`{3,}|~{3,})(.*)$/);
		if (!match) continue;
		const marker = match[2];
		if (!open) {
			open = {
				markerChar: marker[0],
				markerLen: marker.length
			};
			continue;
		}
		if (open.markerChar === marker[0] && marker.length >= open.markerLen) open = null;
	}
	return open === null;
}
//#endregion
//#region src/test-utils/bundled-plugin-public-surface.ts
const KAIJIBOT_PACKAGE_ROOT = resolveLoaderPackageRoot({
	modulePath: fileURLToPath(import.meta.url),
	moduleUrl: import.meta.url
}) ?? fileURLToPath(new URL("../..", import.meta.url));
function findBundledPluginMetadata(pluginId) {
	const metadata = findBundledPluginMetadataById(pluginId);
	if (!metadata) throw new Error(`Unknown bundled plugin id: ${pluginId}`);
	return metadata;
}
function loadBundledPluginPublicSurfaceSync(params) {
	return loadBundledPluginPublicSurfaceModuleSync({
		dirName: findBundledPluginMetadata(params.pluginId).dirName,
		artifactBasename: normalizeBundledPluginArtifactSubpath(params.artifactBasename)
	});
}
function loadBundledPluginTestApiSync(pluginId) {
	return loadBundledPluginPublicSurfaceSync({
		pluginId,
		artifactBasename: "test-api.js"
	});
}
function resolveRelativeBundledPluginPublicModuleId(params) {
	const metadata = findBundledPluginMetadata(params.pluginId);
	const fromFilePath = fileURLToPath(params.fromModuleUrl);
	const artifactBasename = normalizeBundledPluginArtifactSubpath(params.artifactBasename);
	const targetPath = path.resolve(KAIJIBOT_PACKAGE_ROOT, "extensions", metadata.dirName, artifactBasename);
	const relativePath = path.relative(path.dirname(fromFilePath), targetPath).replaceAll(path.sep, "/");
	return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
}
//#endregion
//#region src/test-utils/auth-token-assertions.ts
function expectGeneratedTokenPersistedToGatewayAuth(params) {
	globalExpect(params.generatedToken).toMatch(/^[0-9a-f]{48}$/);
	globalExpect(params.authToken).toBe(params.generatedToken);
	globalExpect(params.persistedConfig?.gateway?.auth?.mode).toBe("token");
	globalExpect(params.persistedConfig?.gateway?.auth?.token).toBe(params.generatedToken);
}
//#endregion
export { spyRuntimeLogs as _, countLines as a, primeChannelOutboundSendMock as b, createWindowsCmdShimFixture as c, writeSkill as d, createSandboxTestContext as f, spyRuntimeJson as g, spyRuntimeErrors as h, resolveRelativeBundledPluginPublicModuleId as i, buildCommandTestParams as l, firstWrittenJsonArg as m, loadBundledPluginPublicSurfaceSync as n, hasBalancedFences as o, createCliRuntimeCapture as p, loadBundledPluginTestApiSync as r, installCommonResolveTargetErrorCases as s, expectGeneratedTokenPersistedToGatewayAuth as t, runAcpRuntimeAdapterContract as u, buildDispatchInboundCaptureMock as v, expectChannelInboundContextContract as y };
