//#region src/koi/code-mode/declarations.ts
/**
* Convert a JSON-Schema-ish parameter description into a TypeScript
* type literal. Deliberately permissive — anything we don't understand
* falls through as `unknown` so the model is signalled "I don't know
* the precise shape, just pass it along."
*/
function typeFromSchema(schema, depth = 0) {
	if (!schema || depth > 6) return "unknown";
	if (schema.enum && schema.enum.length > 0) return schema.enum.map((v) => typeof v === "string" ? JSON.stringify(v) : String(v)).join(" | ");
	if (schema.anyOf || schema.oneOf) {
		const union = (schema.anyOf ?? schema.oneOf).map((s) => typeFromSchema(s, depth + 1));
		return Array.from(new Set(union)).join(" | ");
	}
	switch (schema.type) {
		case "string": return "string";
		case "number":
		case "integer": return "number";
		case "boolean": return "boolean";
		case "null": return "null";
		case "array": return `Array<${typeFromSchema(schema.items, depth + 1)}>`;
		case "object": {
			const props = schema.properties ?? {};
			const required = new Set(schema.required ?? []);
			const entries = Object.entries(props).map(([k, v]) => {
				const optional = required.has(k) ? "" : "?";
				return `${v.description ? ` /** ${oneLine(v.description)} */` : ""}\n    ${quoteKey(k)}${optional}: ${typeFromSchema(v, depth + 1)};`;
			});
			if (entries.length === 0) return "Record<string, unknown>";
			return `{${entries.join("")}\n  }`;
		}
		default: return "unknown";
	}
}
const SAFE_KEY = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
function quoteKey(k) {
	return SAFE_KEY.test(k) ? k : JSON.stringify(k);
}
function oneLine(s) {
	return s.replace(/\s+/g, " ").trim().slice(0, 160);
}
/**
* Build the full declaration block for all tools — used at the top of
* the system prompt when code-mode is enabled.
*/
function buildToolDeclarations(tools) {
	const lines = [];
	lines.push("declare const tools: {");
	for (const tool of tools) {
		const name = quoteKey(tool.name);
		const args = typeFromSchema(tool.parameters);
		const desc = tool.description ? `  /** ${oneLine(tool.description)} */\n` : "";
		lines.push(`${desc}  ${name}(args: ${args}): Promise<unknown>;`);
	}
	lines.push("};");
	lines.push("");
	lines.push("/** Push human-readable output back to the chat. Call as many times as you like. */");
	lines.push("declare function text(message: string): void;");
	lines.push("");
	lines.push("/** Log a non-final intermediate note for the user (rendered as a status pill, not a chat message). */");
	lines.push("declare function progress(message: string): void;");
	return lines.join("\n");
}
function toToolHandles(tools) {
	return tools.map((tool) => ({
		name: tool.name,
		invoke: async (args, signal) => {
			const toolCallId = `code-mode-${tool.name}-${Math.random().toString(36).slice(2, 10)}`;
			return await tool.execute(toolCallId, args ?? {}, signal, void 0);
		}
	}));
}

//#endregion
export { toToolHandles as n, buildToolDeclarations as t };