// engine/errors/middleware.ts — SPEC-902: withErrorContract HOF for tool handlers
import { wrapError, isStructuredError } from './error-wrapper.js';
import { structuredErrorToResult } from './error-result.js';
const WRAPPER_SYMBOL = Symbol.for('planu.errorContractWrapped');
export function withErrorContract(handler, ctx) {
    const wrapped = async (args, extra) => {
        try {
            const result = await handler(args, extra);
            if (result.isError !== true) {
                return result;
            }
            return result;
        }
        catch (err) {
            if (isStructuredError(err)) {
                return structuredErrorToResult(err);
            }
            const structured = wrapError(err, ctx);
            return structuredErrorToResult(structured);
        }
    };
    Object.defineProperty(wrapped, WRAPPER_SYMBOL, { value: true, enumerable: false });
    return wrapped;
}
//# sourceMappingURL=middleware.js.map