import { i as jsonResult, r as errorResult, u as Type } from "../../tool-helpers-CVAcqiCy.mjs";
import { getUserToolService } from "./user-tool-service.mjs";
import { createSandboxContext, executeApiConnector, executeComposedTool } from "./sandbox-runtime.mjs";
//#region extensions/crypto/src/services/tool-compiler.ts
/**
* Tool Compiler — converts UserTool definitions into AnyAgentTool-compatible objects.
*
* This is the bridge between the user-tool-service (CRUD / persistence) and
* the OpenClaw plugin registration system. It:
*
* 1. Generates TypeBox schemas from UserToolParam[] definitions
* 2. Creates execute functions that route to the sandbox runtime
* 3. Returns objects matching the AnyAgentTool shape expected by api.registerTool()
*
* User tools are compiled at plugin init time (for all enabled tools) and
* on-demand when new tools are created at runtime.
*/
/**
* Build a TypeBox schema from UserToolParam[] definitions.
*
* Each param becomes a property in a Type.Object schema. Required params
* are listed in the object's `required` array (handled by TypeBox's
* Type.Optional wrapper for non-required params).
*/
function buildSchemaFromParams(params) {
	if (params.length === 0) return Type.Object({});
	const properties = {};
	for (const param of params) {
		let schema;
		switch (param.type) {
			case "string":
				schema = Type.String({ description: param.description });
				break;
			case "number":
				schema = Type.Number({ description: param.description });
				break;
			case "boolean":
				schema = Type.Boolean({ description: param.description });
				break;
			default: schema = Type.String({ description: param.description });
		}
		if (param.default !== void 0) schema = Type.Optional({
			...schema,
			default: param.default
		});
		if (!param.required) schema = Type.Optional(schema);
		properties[param.name] = schema;
	}
	return Type.Object(properties);
}
/**
* Compile a UserTool into an AnyAgentTool-compatible object.
*
* The returned object has the same shape as built-in tools (name, label,
* ownerOnly, description, parameters, execute) and can be passed directly
* to api.registerTool().
*
* @param tool - The user tool definition from UserToolService
* @param dispatcher - Interface for calling built-in tools (for composed/custom types)
* @returns CompiledTool ready for registration
*/
function compileTool(tool, dispatcher) {
	const schema = buildSchemaFromParams(tool.params);
	return {
		name: tool.name,
		label: tool.label,
		ownerOnly: tool.isWrite,
		description: `[User Tool] ${tool.description}`,
		parameters: schema,
		execute: async (_toolCallId, args, ctx) => {
			const current = getUserToolService().get(tool.id);
			if (!current || !current.enabled) return errorResult(`User tool "${tool.name}" is disabled or has been deleted.`);
			const sandbox = createSandboxContext(current, ctx?.senderId ?? ctx?.from ?? ctx?.metadata?.senderId ?? "unknown");
			try {
				const params = args ?? {};
				let result;
				switch (current.definition.type) {
					case "api_connector":
						result = await executeApiConnector(current.definition, params, sandbox);
						break;
					case "composed":
						result = await executeComposedTool(current.definition.steps, params, sandbox, dispatcher);
						break;
					case "custom":
						result = jsonResult({
							type: "custom_tool_invocation",
							behavior: current.definition.behavior,
							allowedTools: current.definition.allowedTools,
							maxCalls: current.definition.maxCalls ?? 5,
							inputArgs: params,
							instructions: `This is a user-defined custom tool. Follow the behavior description above to fulfill the request. You may call the listed allowedTools (up to ${current.definition.maxCalls ?? 5} times) to achieve the goal. Return the final result.`
						});
						break;
					default: result = errorResult(`Unknown tool type: ${current.definition.type}`);
				}
				getUserToolService().recordUsage(current.id);
				if (result?.details && typeof result.details === "object") result.details._audit = {
					callCount: sandbox.callCount,
					budgetUsedUsd: current.maxBudgetUsd - sandbox.budgetRemainingUsd,
					entries: sandbox.auditLog
				};
				return result;
			} catch (err) {
				return errorResult(`User tool "${tool.name}" failed: ${err instanceof Error ? err.message : String(err)}`);
			}
		}
	};
}
/**
* Compile all enabled user tools into registerable tool objects.
*
* Called at plugin init time to load persisted user tools.
*/
function compileAllEnabledTools(dispatcher) {
	return getUserToolService().getEnabledTools().map((tool) => compileTool(tool, dispatcher));
}
//#endregion
export { buildSchemaFromParams, compileAllEnabledTools, compileTool };

//# sourceMappingURL=tool-compiler.mjs.map