"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildToolContextFromScope = buildToolContextFromScope;
exports.wrapWithScope = wrapWithScope;
const context_1 = require("../../iam/context");
/**
 * Build a ToolContext from the `_scope` input parameter.
 * YAML activities receive `_scope` threaded from the trigger through every step.
 */
function buildToolContextFromScope(scope) {
    return {
        principal: scope.principal,
        ...(scope.initiatingPrincipal
            ? { initiatingPrincipal: scope.initiatingPrincipal }
            : {}),
        credentials: {
            scopes: scope.scopes ?? [],
        },
        trace: {},
    };
}
/**
 * Wrap a worker callback with scope injection via AsyncLocalStorage.
 * If `_scope` is present in the input data, builds a ToolContext and
 * wraps the callback so `getToolContext()` works inside tool code.
 */
function wrapWithScope(callback) {
    return async (data) => {
        const input = (data.data || {});
        const scope = input._scope;
        if (scope?.principal) {
            const ctx = buildToolContextFromScope(scope);
            return (0, context_1.runWithToolContext)(ctx, () => callback(data));
        }
        return callback(data);
    };
}
