
!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]="b7867f4b-b918-58ac-b803-6f92472b880e")}catch(e){}}();
var _a;
import { z } from 'zod';
import log from '@apify/log';
import { HelperTools, TOOL_STATUS } from '../../const.js';
import { getWidgetConfig, WIDGET_URIS } from '../../resources/widgets.js';
import { compileSchema } from '../../utils/ajv.js';
import { buildMCPResponse } from '../../utils/mcp.js';
import { generateSchemaFromItems } from '../../utils/schema_generation.js';
import { getActorRunOutputSchema } from '../structured_output_schemas.js';
/**
 * Zod schema for get-actor-run arguments — shared between default and openai variants.
 */
export const getActorRunArgs = z.object({
    runId: z.string()
        .min(1)
        .describe('The ID of the Actor run.'),
});
const GET_ACTOR_RUN_DESCRIPTION = `Get detailed information about a specific Actor run by runId.
The results will include run metadata (status, timestamps), performance stats, and resource IDs (datasetId, keyValueStoreId, requestQueueId).

CRITICAL WARNING: NEVER call this tool immediately after call-actor in UI mode. The call-actor response includes a widget that automatically polls for updates. Calling this tool after call-actor is FORBIDDEN and unnecessary.

USAGE:
- Use ONLY when user explicitly asks about a specific run's status or details.
- Use ONLY for runs that were started outside the current conversation.
- DO NOT use this tool as part of the call-actor workflow in UI mode.

USAGE EXAMPLES:
- user_input: Show details of run y2h7sK3Wc (where y2h7sK3Wc is an existing run)
- user_input: What is the datasetId for run y2h7sK3Wc?`;
/**
 * Shared tool metadata for get-actor-run — everything except the `call` handler.
 * Used by both default and openai variants.
 */
export const getActorRunMetadata = {
    type: 'internal',
    name: HelperTools.ACTOR_RUNS_GET,
    description: GET_ACTOR_RUN_DESCRIPTION,
    inputSchema: z.toJSONSchema(getActorRunArgs),
    outputSchema: getActorRunOutputSchema,
    ajvValidate: compileSchema({ ...z.toJSONSchema(getActorRunArgs), additionalProperties: true }),
    requiresSkyfirePayId: true,
    // openai/* and ui keys are stripped in non-openai mode by stripWidgetMeta() in src/utils/tools.ts
    _meta: {
        ...(_a = getWidgetConfig(WIDGET_URIS.ACTOR_RUN)) === null || _a === void 0 ? void 0 : _a.meta,
    },
    annotations: {
        title: 'Get Actor run',
        readOnlyHint: true,
        destructiveHint: false,
        idempotentHint: true,
        openWorldHint: false,
    },
};
/**
 * Fetches actor run data, resolves actor name, and fetches dataset results if completed.
 * Shared data-fetching logic used by both default and openai variants.
 *
 * Returns the run data and structured content, or an early error response.
 */
export async function fetchActorRunData(params) {
    var _a, _b;
    const { runId, client, mcpSessionId } = params;
    const run = await client.run(runId).get();
    if (!run) {
        return {
            error: buildMCPResponse({
                texts: [`Run with ID '${runId}' not found.`],
                isError: true,
                toolStatus: TOOL_STATUS.SOFT_FAIL,
            }),
        };
    }
    log.debug('Get actor run', { runId, status: run.status, mcpSessionId });
    let actorName;
    if (run.actId) {
        try {
            const actor = await client.actor(run.actId).get();
            if (actor) {
                actorName = `${actor.username}/${actor.name}`;
            }
        }
        catch (error) {
            log.warning(`Failed to fetch actor name for run ${runId}`, { mcpSessionId, error });
        }
    }
    const structuredContent = {
        runId: run.id,
        actorName,
        status: run.status,
        startedAt: ((_a = run.startedAt) === null || _a === void 0 ? void 0 : _a.toISOString()) || '',
        finishedAt: (_b = run.finishedAt) === null || _b === void 0 ? void 0 : _b.toISOString(),
        stats: run.stats,
    };
    // If completed, fetch dataset results
    if (run.status === 'SUCCEEDED' && run.defaultDatasetId) {
        const dataset = client.dataset(run.defaultDatasetId);
        const datasetItems = await dataset.listItems({ limit: 5 });
        const generatedSchema = generateSchemaFromItems(datasetItems.items, {
            clean: true,
            arrayMode: 'all',
        });
        structuredContent.dataset = {
            datasetId: run.defaultDatasetId,
            totalItemCount: datasetItems.total,
            previewItemCount: datasetItems.items.length,
            schema: generatedSchema || { type: 'object', properties: {} },
            previewItems: datasetItems.items,
        };
    }
    return { result: { run: run, structuredContent } };
}
//# sourceMappingURL=get_actor_run_common.js.map
//# debugId=b7867f4b-b918-58ac-b803-6f92472b880e
