import "./subsystem-B57zAnh3.js";
import "./paths-aMBPuCJR.js";
import "./auth-profiles-vy16iW9a.js";
import "./env-DFfOiqpV.js";
import { t as runCommandWithTimeout } from "./exec-rVpUMUjU.js";
import "./agent-scope-C3vq_G9s.js";
import "./github-copilot-token-5G6j3BB0.js";
import "./reliability-CU83NHOD.js";
import "./sqlite-CbyDDiup.js";
import "./image-ops-D6in9bm7.js";
import "./config-BWfcFg-o.js";
import "./manifest-registry-DOrMVNcS.js";
import "./skills-WWjjkPNZ.js";
import "./tool-images-DTeIBF5l.js";
import { a as jsonResult, u as readStringParam } from "./common-CBZ0Olph.js";
import { c as importTokensToGogKeyring, s as getValidCredentials } from "./gog-credentials-CcFdYjtv.js";
import { Type } from "@sinclair/typebox";

//#region src/hooks/gog-command-exec.ts
/**
* Build environment for gog commands.
* Inherits all process.env (including GOG_KEYRING_BACKEND, GOG_KEYRING_PASSWORD
* needed for file-based keyring on headless servers) and merges extra vars on top.
*/
function buildGogEnv(extraEnv) {
	return extraEnv ? {
		...process.env,
		...extraEnv
	} : { ...process.env };
}
/**
* Build environment for gog command with session credentials
* Useful for tools that need to set up environment before spawning
*/
async function buildGogEnvironment(context) {
	const extraEnv = {};
	if (context.sessionKey) {
		const { credentials } = await getValidCredentials(context.agentId, context.sessionKey, context.email);
		if (credentials) extraEnv.GOG_ACCOUNT = credentials.email;
	}
	return buildGogEnv(extraEnv);
}

//#endregion
//#region src/agents/tools/auth/gog-exec-tool.ts
/**
* gog_exec tool - Run gog CLI commands with auto-injected session credentials
*/
const GogExecSchema = Type.Object({
	command: Type.String({
		description: "The gog command to run (without the \"gog\" prefix). Example: 'gmail search \"newer_than:7d\" --max 10'",
		minLength: 1
	}),
	json: Type.Optional(Type.Boolean({ description: "Auto-append --json flag and parse output as structured data (default: false)" })),
	timeout: Type.Optional(Type.Number({
		description: "Timeout in seconds (default: 60, max: 300)",
		minimum: 5,
		maximum: 300
	}))
});
function createGogExecTool(opts) {
	return {
		label: "Google Exec",
		name: "gog_exec",
		description: "Run gog CLI commands with auto-injected session credentials. Requires prior authentication via gog_auth_start. See the gog skill for command reference. If this tool returns a scope/permission error, IMMEDIATELY call gog_auth_start with the missing service — do NOT try workarounds or alternative commands. IMPORTANT: When this tool returns data (file lists, emails, events), you MUST include the actual content in your reply to the user — do NOT just summarize or say 'here is the list' without showing it.",
		parameters: GogExecSchema,
		execute: async (_toolCallId, args) => {
			const params = args;
			const command = readStringParam(params, "command", { required: true });
			const wantJson = params.json === true;
			const timeoutSec = Math.min(params.timeout || 60, 300);
			if (!opts?.agentId || !opts?.sessionKey) return jsonResult({ error: "Missing agent context (agentId or sessionKey)" });
			if ((await runCommandWithTimeout(["which", "gog"], { timeoutMs: 3e3 })).code !== 0) return jsonResult({ error: "gog CLI is not installed on this server. Ask the administrator to install it from https://github.com/steipete/gogcli/releases" });
			const credResult = await getValidCredentials(opts.agentId, opts.sessionKey);
			if (!credResult.credentials) return jsonResult({ error: credResult.refreshFailed ? `Google token refresh failed: ${credResult.error}. Re-authenticate with gog_auth_start.` : "Not authenticated with Google. Use gog_auth_start first to authorize, then retry." });
			const credentials = credResult.credentials;
			const commandArgs = parseCommandArgs(command);
			const targetService = commandArgs.find((arg) => [
				"gmail",
				"calendar",
				"drive",
				"contacts",
				"docs",
				"sheets"
			].includes(arg));
			if (targetService && !credentials.services.includes(targetService)) {
				const allServices = [...new Set([...credentials.services, targetService])];
				return jsonResult({ error: `SCOPE MISSING: Current credentials for ${credentials.email} only have scopes for: ${credentials.services.join(", ")}. The "${targetService}" service is not authorized. ACTION REQUIRED: Call gog_auth_start NOW with email="${credentials.email}" and services=[${allServices.map((s) => `"${s}"`).join(", ")}]. Do NOT retry this command or try alternative commands — authentication must be expanded first.` });
			}
			if (!commandArgs.includes("--account") && !commandArgs.includes("-a")) {
				const subcommandIndex = commandArgs.findIndex((arg) => [
					"gmail",
					"calendar",
					"drive",
					"contacts",
					"docs",
					"sheets",
					"auth"
				].includes(arg));
				if (subcommandIndex >= 0) commandArgs.splice(subcommandIndex + 1, 0, "--account", credentials.email);
			}
			if (wantJson && !commandArgs.includes("--json")) commandArgs.push("--json");
			const env = await buildGogEnvironment({
				agentId: opts.agentId,
				sessionKey: opts.sessionKey,
				email: credentials.email
			});
			const syncResult = await importTokensToGogKeyring(credentials, env);
			let keyringSyncWarning;
			if (!syncResult.success) keyringSyncWarning = `Keyring sync failed: ${syncResult.error}. The gog command will still be attempted.`;
			const result = await runCommandWithTimeout(["gog", ...commandArgs], {
				timeoutMs: timeoutSec * 1e3,
				env
			});
			if (result.killed || result.termination === "timeout") return jsonResult({
				error: `Command timed out after ${timeoutSec}s`,
				stdout: result.stdout.slice(0, 2e3),
				stderr: result.stderr.slice(0, 2e3)
			});
			if (result.code !== 0) {
				const scopeHint = /insufficientPermissions|insufficient.*scopes?|403/i.test(result.stderr) ? `\nSCOPE ERROR: The current token was not granted "${targetService || "the required"}" permissions. ACTION REQUIRED: Call gog_auth_start NOW with email="${credentials.email}" and services=["gmail", "calendar", "drive"] to fix this. Do NOT retry this command or try alternative commands.` : "";
				return jsonResult({
					error: `gog exited with code ${result.code}${scopeHint}`,
					stdout: result.stdout,
					stderr: result.stderr,
					keyringSyncWarning
				});
			}
			if (wantJson) try {
				return jsonResult({
					data: JSON.parse(result.stdout),
					stderr: result.stderr || void 0
				});
			} catch {
				return jsonResult({
					stdout: result.stdout,
					stderr: result.stderr || void 0,
					warning: "json=true was set but output was not valid JSON"
				});
			}
			return jsonResult({
				stdout: result.stdout,
				stderr: result.stderr || void 0,
				keyringSyncWarning
			});
		}
	};
}
/**
* Parse a command string into an array of arguments, respecting quoted strings.
* - Single quotes: literal (no escape interpretation)
* - Double quotes: interprets \n, \t, \\, \"
* - Unquoted backslash: escapes next character
*
* Note: Does not handle shell-specific $'...' ANSI-C quoting or heredocs.
* For multi-line content, prefer --body-file with a temp file instead.
*/
function parseCommandArgs(command) {
	const args = [];
	let current = "";
	let inSingle = false;
	let inDouble = false;
	let escaped = false;
	const DOUBLE_QUOTE_ESCAPES = {
		n: "\n",
		t: "	",
		"\\": "\\",
		"\"": "\""
	};
	for (const char of command) {
		if (escaped) {
			if (inDouble) current += DOUBLE_QUOTE_ESCAPES[char] ?? `\\${char}`;
			else current += char;
			escaped = false;
			continue;
		}
		if (char === "\\" && !inSingle) {
			escaped = true;
			continue;
		}
		if (char === "'" && !inDouble) {
			inSingle = !inSingle;
			continue;
		}
		if (char === "\"" && !inSingle) {
			inDouble = !inDouble;
			continue;
		}
		if (char === " " && !inSingle && !inDouble) {
			if (current.length > 0) {
				args.push(current);
				current = "";
			}
			continue;
		}
		current += char;
	}
	if (current.length > 0) args.push(current);
	return args;
}

//#endregion
export { createGogExecTool };