
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="11f586f7-4f91-5f1c-ad5f-03ecc777b992")}catch(e){}}();
import log from '@apify/log';
import { TOOL_MAX_OUTPUT_CHARS } from '../../const.js';
import { ensureOutputWithinCharLimit, getActorDefinitionStorageFieldNames } from '../../utils/actor.js';
import { logHttpError, redactSkyfirePayId } from '../../utils/logging.js';
import { generateSchemaFromItems } from '../../utils/schema_generation.js';
/**
 * Calls an Apify Actor and retrieves metadata about the dataset results.
 *
 * This function executes an Actor and returns summary information instead with a result items preview of the full dataset
 * to prevent overwhelming responses. The actual data can be retrieved using the get-actor-output tool.
 *
 * It requires the `APIFY_TOKEN` environment variable to be set.
 * If the `APIFY_IS_AT_HOME` the dataset items are pushed to the Apify dataset.
 *
 * @returns {Promise<CallActorGetDatasetResult | null>} - A promise that resolves to an object containing the actor run and dataset items.
 * @throws {Error} - Throws an error if the `APIFY_TOKEN` is not set
 * @param options
 */
export async function callActorGetDataset(options) {
    var _a, _b;
    const { actorName, input, apifyClient, callOptions, progressTracker, abortSignal, previewOutput = true, mcpSessionId, } = options;
    const CLIENT_ABORT = Symbol('CLIENT_ABORT'); // Just an internal symbol to identify client abort
    const actorClient = apifyClient.actor(actorName);
    // Start the actor run
    const actorRun = await actorClient.start(input, callOptions);
    // Start progress tracking if a tracker is provided
    if (progressTracker) {
        progressTracker.startActorRunUpdates(actorRun.id, apifyClient, actorName);
    }
    // Create abort promise that handles both API abort and race rejection
    const abortPromise = async () => new Promise((resolve) => {
        abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.addEventListener('abort', async () => {
            // Abort the actor run via API
            try {
                await apifyClient.run(actorRun.id).abort({ gracefully: false });
            }
            catch (e) {
                logHttpError(e, 'Error aborting Actor run', { runId: actorRun.id });
            }
            // Reject to stop waiting
            resolve(CLIENT_ABORT);
        }, { once: true });
    });
    // Wait for completion or cancellation
    const potentialAbortedRun = await Promise.race([
        apifyClient.run(actorRun.id).waitForFinish(),
        ...(abortSignal ? [abortPromise()] : []),
    ]);
    if (potentialAbortedRun === CLIENT_ABORT) {
        log.info('Actor run aborted by client', { actorName, mcpSessionId, input: redactSkyfirePayId(input) });
        return null;
    }
    const completedRun = potentialAbortedRun;
    // Process the completed run
    const dataset = apifyClient.dataset(completedRun.defaultDatasetId);
    const [datasetItems, defaultBuild] = await Promise.all([
        dataset.listItems(),
        (await actorClient.defaultBuild()).get(),
    ]);
    // Generate schema using the shared utility
    const generatedSchema = generateSchemaFromItems(datasetItems.items, {
        clean: true,
        arrayMode: 'all',
    });
    const schema = generatedSchema || { type: 'object', properties: {} };
    /**
     * Get important fields that are using in any dataset view as they MAY be used in filtering to ensure the output fits
     * the tool output limits. Client has to use the get-actor-output tool to retrieve the full dataset or filtered out fields.
     */
    const storageDefinition = (_b = (_a = defaultBuild === null || defaultBuild === void 0 ? void 0 : defaultBuild.actorDefinition) === null || _a === void 0 ? void 0 : _a.storages) === null || _b === void 0 ? void 0 : _b.dataset;
    const importantProperties = getActorDefinitionStorageFieldNames(storageDefinition || {});
    const previewItems = previewOutput
        ? ensureOutputWithinCharLimit(datasetItems.items, importantProperties, TOOL_MAX_OUTPUT_CHARS)
        : [];
    return {
        runId: actorRun.id,
        datasetId: completedRun.defaultDatasetId,
        // `datasetItems.total` comes from the X-Apify-Pagination-Total header, which is backed
        // by the dataset's cached `itemCount` counter. Per the API docs, this counter may lag
        // up to 5 seconds after items are written (eventual consistency). When called immediately
        // after a run finishes it can return 0 even though items are already stored.
        // Fall back to `items.length`: safe here because listItems() has no limit, so all items
        // are fetched and the length always reflects the true count.
        // See: https://docs.apify.com/api/v2/dataset-get (itemCount note)
        totalItemCount: datasetItems.total || datasetItems.items.length,
        previewItemCount: previewItems.length,
        schema,
        previewItems,
        usageTotalUsd: completedRun.usageTotalUsd,
        usageUsd: completedRun.usageUsd,
    };
}
//# sourceMappingURL=actor_execution.js.map
//# debugId=11f586f7-4f91-5f1c-ad5f-03ecc777b992
