if (!globalThis.__gjc_js_prelude_loaded__) {
	globalThis.__gjc_js_prelude_loaded__ = true;

	const toOptions = value => (value && typeof value === "object" && !Array.isArray(value) ? value : {});
	const callHelper = (name, ...args) => globalThis.__gjc_helpers__[name](...args);

	const read = (path, opts = {}) => callHelper("read", path, toOptions(opts));
	const write = async (path, data) => callHelper("writeFile", path, data);
	const append = (path, content) => callHelper("append", path, content);
	const sort = (text, opts = {}) => callHelper("sortText", text, toOptions(opts));
	const uniq = (text, opts = {}) => callHelper("uniqText", text, toOptions(opts));
	const counter = (items, opts = {}) => callHelper("counter", items, toOptions(opts));
	const diff = (a, b) => callHelper("diff", a, b);
	const tree = (path = ".", opts = {}) => callHelper("tree", path, toOptions(opts));
	const env = (key, value) => callHelper("env", key, value);

	const tool = new Proxy(
		{},
		{
			get(_target, prop) {
				if (typeof prop !== "string") return undefined;
				return async args => globalThis.__gjc_call_tool__(prop, args ?? {});
			},
		},
	);

	const output = async (...args) => {
		let opts = {};
		let ids = args;
		if (args.length > 0) {
			const last = args.at(-1);
			if (last && typeof last === "object" && !Array.isArray(last)) {
				opts = last;
				ids = args.slice(0, -1);
			}
		}
		const reads = ids.map(id => tool.read({ path: `agent://${id}`, ...opts }));
		const values = await Promise.all(reads);
		return values.length === 1 ? values[0] : values;
	};

	const display = value => {
		globalThis.__gjc_display__(value);
	};

	const formatArgs = args => args.map(arg => (typeof arg === "string" ? arg : arg));

	const consoleBridge = {
		log: (...args) => globalThis.__gjc_log__("log", ...formatArgs(args)),
		info: (...args) => globalThis.__gjc_log__("info", ...formatArgs(args)),
		warn: (...args) => globalThis.__gjc_log__("warn", ...formatArgs(args)),
		error: (...args) => globalThis.__gjc_log__("error", ...formatArgs(args)),
		debug: (...args) => globalThis.__gjc_log__("debug", ...formatArgs(args)),
	};

	globalThis.console = consoleBridge;
	globalThis.print = consoleBridge.log;
	globalThis.display = display;
	globalThis.tool = tool;
	globalThis.output = output;
	globalThis.read = read;
	globalThis.write = write;
	globalThis.append = append;
	globalThis.sort = sort;
	globalThis.uniq = uniq;
	globalThis.counter = counter;
	globalThis.diff = diff;
	globalThis.tree = tree;
	globalThis.env = env;
}
