import { u as resolveGatewayPort } from "./paths-mmi2xb99.js";
import "./globals-D5pM_phR.js";
import "./utils-3Lue6wVm.js";
import "./subsystem-_lp1q2Mi.js";
import "./boolean-BhvV-zDA.js";
import "./env-aEqmsXHj.js";
import { r as loadConfig } from "./config-VoJVjSgT.js";
import "./agent-scope-u760_XKU.js";
import "./exec-NeyMP-Tl.js";
import "./edwinpai-root-fGTEvnPp.js";
import "./model-selection-CMHF17-l.js";
import "./github-copilot-token-Bu-iLSUh.js";
import "./command-format-D8drL8c2.js";
import "./manifest-registry-Cobl4jxs.js";
import { t as canonicalizeRequest } from "./bsv-auth-SUjvapkY.js";
import { t as BSVCrypto } from "./bsv-sdk-wrapper-WQddHzMe.js";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { homedir } from "node:os";
import { createHash } from "node:crypto";
import { createNodeIdentityCoreBinding, loadNativeIdentityCore } from "@edwinpai/identity-core";

//#region ../../src/auth/request-signer.ts
/**
* BRC-103 Request Signing Client
*
* Client-side utility for signing outgoing HTTP requests following
* the BRC-103 peer-to-peer authentication specification.
*
* @see https://github.com/bitcoin-sv/BRCs/blob/master/peer-to-peer/0103.md
* @see https://github.com/bitcoin-sv/BRCs/blob/master/peer-to-peer/0104.md
*/
/**
* BRC-103 Request Signer
*
* Signs outgoing HTTP requests with the sender's private key for
* peer-to-peer authentication.
*
* @example
* ```typescript
* // Create signer with a private key
* const privateKey = BSVCrypto.privateKeyFromHex("...");
* const signer = new RequestSigner(privateKey);
*
* // Sign a request
* const headers = signer.signRequest({
*   method: "POST",
*   path: "/api/agent/run",
*   body: { prompt: "hello" }
* });
*
* // Attach headers to fetch request
* const response = await fetch("https://example.com/api/agent/run", {
*   method: "POST",
*   headers: {
*     "Content-Type": "application/json",
*     ...headers
*   },
*   body: JSON.stringify({ prompt: "hello" })
* });
* ```
*/
var RequestSigner = class RequestSigner {
	/**
	* Create a new RequestSigner
	*
	* @param privateKey - Identity private key for signing requests
	*/
	constructor(privateKey) {
		this.privateKey = privateKey;
		this.publicKey = privateKey.toPublicKey();
		this.identityKeyHex = this.publicKey.toHex();
	}
	/**
	* Create a RequestSigner from a hex-encoded private key
	*
	* @param privateKeyHex - 64-character hex string
	* @returns RequestSigner instance
	*/
	static fromHex(privateKeyHex) {
		return new RequestSigner(BSVCrypto.privateKeyFromHex(privateKeyHex));
	}
	/**
	* Create a RequestSigner with a randomly generated key
	*
	* @returns RequestSigner instance with random key
	*/
	static fromRandom() {
		return new RequestSigner(BSVCrypto.privateKeyFromRandom());
	}
	/**
	* Sign an HTTP request and return headers to attach
	*
	* Follows BRC-103 canonicalization format:
	* `METHOD\nPATH\nTIMESTAMP\nNONCE\nBODY_OR_EMPTY`
	*
	* @param params - Request parameters to sign
	* @returns Headers object with authentication data
	*/
	signRequest(params) {
		const { method, path, body } = params;
		const timestamp = params.timestamp ?? Date.now();
		const nonce = params.nonce ?? crypto.randomUUID();
		const canonicalRequest = canonicalizeRequest({
			method,
			path,
			body,
			timestamp,
			nonce,
			identityKey: this.identityKeyHex
		});
		const messageHash = createHash("sha256").update(canonicalRequest).digest("hex");
		const signatureHex = BSVCrypto.sign(this.privateKey, messageHash).toString("hex");
		return {
			"x-bsv-identity-key": this.identityKeyHex,
			"x-bsv-signature": signatureHex,
			"x-bsv-timestamp": timestamp.toString(),
			"x-bsv-nonce": nonce
		};
	}
	/**
	* Get the identity public key (hex)
	*
	* This is the key used to identify the signer in BRC-103.
	*
	* @returns Compressed public key as 66-character hex string
	*/
	getIdentityKey() {
		return this.identityKeyHex;
	}
	/**
	* Get the identity public key as SecurePublicKey
	*
	* @returns SecurePublicKey instance
	*/
	getPublicKey() {
		return this.publicKey;
	}
	/**
	* Get the private key (USE WITH CAUTION)
	*
	* @returns SecurePrivateKey instance
	*/
	getPrivateKey() {
		return this.privateKey;
	}
};

//#endregion
//#region ../../src/gateway/gateway-http-client.ts
let _identityCore;
function loadIdentityCore() {
	if (_identityCore !== void 0) return _identityCore;
	const native = loadNativeIdentityCore();
	if (native) {
		_identityCore = native;
		return _identityCore;
	}
	try {
		const hex = readFileSync(join(homedir(), ".edwinpai", "identity-key"), "utf-8").trim();
		const signer = RequestSigner.fromHex(hex);
		_identityCore = createNodeIdentityCoreBinding({
			async getPublicKey() {
				return signer.getIdentityKey();
			},
			async signHttpRequest(input) {
				return signer.signRequest({
					method: input.method,
					path: input.path,
					body: input.body ?? void 0,
					timestamp: input.timestamp,
					nonce: input.nonce
				});
			}
		});
	} catch {
		_identityCore = null;
	}
	return _identityCore;
}
function resolveGatewayHttp() {
	try {
		const config = loadConfig();
		const port = resolveGatewayPort(config);
		const token = config.gateway?.auth?.token;
		if (!token) {
			const envToken = process.env.EDWINPAI_GATEWAY_TOKEN?.trim();
			if (!envToken) return null;
			return {
				url: `http://127.0.0.1:${port}`,
				token: envToken
			};
		}
		return {
			url: `http://127.0.0.1:${port}`,
			token
		};
	} catch {
		const envToken = process.env.EDWINPAI_GATEWAY_TOKEN?.trim();
		if (!envToken) return null;
		return {
			url: `http://127.0.0.1:18789`,
			token: envToken
		};
	}
}
/**
* Send an authenticated HTTP request to the local gateway.
*
* Includes both the bearer token and BRC-103 BSV identity headers
* when an identity key is available at ~/.edwinpai/identity-key.
*/
async function gatewayHttpFetch(endpoint, method, body, opts) {
	const gw = resolveGatewayHttp();
	if (!gw) throw new Error("Gateway not configured. Set gateway.auth.token in ~/.edwinpai/edwinpai.json or EDWINPAI_GATEWAY_TOKEN env var.");
	const controller = new AbortController();
	const timeout = setTimeout(() => controller.abort(), opts?.timeoutMs ?? 12e4);
	const headers = {
		"Content-Type": "application/json",
		Authorization: `Bearer ${gw.token}`
	};
	const identityCore = loadIdentityCore();
	if (identityCore) {
		const bsvHeaders = await identityCore.signHttpRequest({
			method,
			path: endpoint,
			body: body ?? void 0
		});
		Object.assign(headers, bsvHeaders);
	}
	try {
		const response = await fetch(`${gw.url}${endpoint}`, {
			method,
			headers,
			body: body ? JSON.stringify(body) : void 0,
			signal: controller.signal
		});
		const data = await response.json().catch(() => null);
		return {
			ok: response.ok,
			status: response.status,
			data
		};
	} finally {
		clearTimeout(timeout);
	}
}

//#endregion
//#region ../../src/cli/tool-cli.ts
function registerToolCli(program) {
	const toolCmd = program.command("tool").description("Invoke gateway tools (message, TTS, browser, canvas, cron, etc.)");
	toolCmd.command("list").description("List available gateway tools").action(async () => {
		try {
			const result = await gatewayHttpFetch("/tools/list", "GET");
			if (!result.ok) {
				const reason = result.status === 401 || result.status === 403 ? "Gateway auth failed. Check gateway.auth.token / EDWINPAI_GATEWAY_TOKEN." : "Is the gateway running?";
				console.error(`Gateway returned ${result.status}. ${reason}`);
				process.exit(1);
			}
			const tools = result.data?.tools ?? result.data;
			if (Array.isArray(tools)) for (const tool of tools) {
				const name = tool.name ?? tool;
				const desc = tool.description ? ` — ${tool.description}` : "";
				console.log(`${name}${desc}`);
			}
			else console.log(JSON.stringify(result.data, null, 2));
		} catch (err) {
			console.error(`Error: ${err.message}`);
			process.exit(1);
		}
	});
	toolCmd.command("describe <tool>").description("Show tool schema and parameters").action(async (toolName) => {
		try {
			const result = await gatewayHttpFetch(`/tools/describe?tool=${encodeURIComponent(toolName)}`, "GET");
			if (!result.ok) {
				console.error(`Tool not found or gateway error: ${JSON.stringify(result.data)}`);
				process.exit(1);
			}
			console.log(JSON.stringify(result.data, null, 2));
		} catch (err) {
			console.error(`Error: ${err.message}`);
			process.exit(1);
		}
	});
	toolCmd.command("invoke <tool>").description("Invoke a gateway tool").option("-a, --action <action>", "Tool action (e.g. send, list, create)").option("--args <json>", "Tool arguments as JSON string").option("--to <target>", "Message target (shorthand for message tools)").option("--text <text>", "Message text (shorthand for message tools)").option("--session <key>", "Session key context").option("--dry-run", "Validate without executing").allowUnknownOption(true).action(async (toolName, opts) => {
		try {
			let args = {};
			if (typeof opts.args === "string") try {
				args = JSON.parse(opts.args);
			} catch {
				console.error("Invalid JSON in --args");
				process.exit(1);
			}
			if (opts.to) args.to = opts.to;
			if (opts.text) args.text = opts.text;
			const body = {
				tool: toolName,
				args
			};
			if (opts.action) body.action = opts.action;
			if (opts.session) body.sessionKey = opts.session;
			if (opts.dryRun) body.dryRun = true;
			const result = await gatewayHttpFetch("/tools/invoke", "POST", body);
			if (!result.ok) {
				const errData = result.data;
				const message = errData?.error?.message ?? JSON.stringify(errData);
				console.error(`Tool invocation failed (${result.status}): ${message}`);
				process.exit(1);
			}
			console.log(JSON.stringify(result.data, null, 2));
		} catch (err) {
			if (err.name === "AbortError") {
				console.error("Tool invocation timed out (120s). The gateway may be waiting for desktop approval.");
				process.exit(1);
			}
			console.error(`Error: ${err.message}`);
			process.exit(1);
		}
	});
}

//#endregion
export { registerToolCli };