"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.runWithToolContext = runWithToolContext;
exports.getToolContext = getToolContext;
/**
 * ToolContext access for activities and workflow-scoped code.
 *
 * Two paths, checked in order:
 *
 * 1. **headers** (production-safe, distributed):
 *    The activity interceptor injects `principal` + `scopes` into
 *    `headers`, which HotMesh delivers to the activity worker
 *    via `Durable.activity.getContext()`. Works across process boundaries.
 *
 * 2. **AsyncLocalStorage** (workflow-local, single-process):
 *    The workflow interceptor wraps `next()` with `runWithToolContext()`
 *    for code running in the workflow's own async scope (e.g., MCP server
 *    tools called directly, not via proxy activities).
 */
const async_hooks_1 = require("async_hooks");
const hotmesh_1 = require("@hotmeshio/hotmesh");
const store = new async_hooks_1.AsyncLocalStorage();
/**
 * Run a function with ToolContext available via `getToolContext()`.
 * Called by the interceptor to wrap workflow execution.
 */
function runWithToolContext(ctx, fn) {
    return store.run(ctx, fn);
}
/**
 * Retrieve the ToolContext for the current execution scope.
 *
 * Activities: reads from headers (injected by activity interceptor).
 * Workflow scope: reads from AsyncLocalStorage (set by workflow interceptor).
 * Returns undefined when no identity is available.
 */
function getToolContext() {
    // 1. Try headers (activity worker — works distributed)
    try {
        const actCtx = hotmesh_1.Durable.activity.getContext();
        const meta = actCtx?.headers;
        if (meta?.principal) {
            const principal = meta.principal;
            return {
                principal,
                ...(meta.initiatingPrincipal
                    ? { initiatingPrincipal: meta.initiatingPrincipal }
                    : {}),
                credentials: {
                    scopes: meta.scopes ?? [],
                },
                trace: {},
            };
        }
    }
    catch {
        // Not inside an activity execution — fall through
    }
    // 2. Fallback: AsyncLocalStorage (workflow-local scope)
    return store.getStore();
}
