"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GetTestRunInfoToolDefinition = exports.getTestRunInfoResponseSchema = exports.testRunContextSchema = exports.getTestRunInfoParamsSchema = void 0;
var zod_1 = require("zod");
var toolDefinition_js_1 = require("../toolDefinition.js");
var agentToolNames_js_1 = require("./agentToolNames.js");
var schemas_js_1 = require("../shared/schemas.js");
/**
 * GetTestRunInfoDefinition - Tool definition for fetching comprehensive test run information.
 */
exports.getTestRunInfoParamsSchema = zod_1.z.object({
    test_run_id: zod_1.z.string().meta({
        description: 'Required. Test run ID to fetch info for.',
    }),
    include_steps: zod_1.z.boolean().optional().meta({
        description: 'Whether to include detailed step information. Default: true',
    }),
    step_start_index: zod_1.z.number().optional().meta({
        description: 'Start index for step range (0-based, inclusive). If not specified, starts from beginning. Only used if include_steps is true.',
    }),
    step_end_index: zod_1.z.number().optional().meta({
        description: 'End index for step range (0-based, inclusive). If not specified, includes all steps to the end. Only used if include_steps is true.',
    }),
    step_run_ids: zod_1.z.array(zod_1.z.string()).optional().meta({
        description: 'Filter to specific step executions by step_run_id. Takes precedence over step_start_index/step_end_index.',
    }),
    include_context: zod_1.z.boolean().optional().meta({
        description: 'Whether to include detailed context about application, environment, plan, and datatables. Default: true',
    }),
    include_flow_breakdown: zod_1.z.boolean().optional().meta({
        description: 'Whether to include flow-level breakdown showing execution summary per flow (pass/fail counts, duration). Useful for tests with nested flows or step groups. Default: false',
    }),
});
var testStepInfoSchema = zod_1.z.object({
    index: zod_1.z.number().meta({ description: 'Step index (0-based, cumulative across the entire journey/test)' }),
    stepNumber: zod_1.z.string().meta({
        description: 'Human-readable step number with dotted notation for nested steps (1-based). ' +
            'Examples: "5" for step 5, "3.2" for step 2 inside step group at position 3, "3.2.1" for deeply nested steps. ' +
            'Use this for display purposes instead of computing from index/nestedStepPath.',
    }),
    nestedStepPath: zod_1.z
        .array(zod_1.z.number())
        .optional()
        .meta({
        description: 'Path of step indices for nested steps. Format: [flow_index, step_index_in_flow, ...]. ' +
            'Example: [2, 1] means this step is within flow at index 2, and is step 1 within that flow. ' +
            'For step groups: [flow_index, step_group_index, step_in_group]. ' +
            'Empty or undefined for top-level steps in the main flow.',
    }),
    description: zod_1.z.string().meta({ description: 'Human-readable step description' }),
    status: zod_1.z.enum(['passed', 'failed', 'skipped', 'warning', 'disabled']).meta({
        description: 'Status of the step execution. ' +
            '"disabled" indicates the step was explicitly disabled by the user and not executed.',
    }),
    durationMs: zod_1.z.number().optional().meta({ description: 'Duration in milliseconds' }),
    errorMessage: zod_1.z.string().optional().meta({ description: 'Error message if the step failed' }),
    hasScreenshot: zod_1.z.boolean().meta({ description: 'Whether this step has a screenshot available' }),
    url: zod_1.z.string().optional().meta({ description: 'Page URL at the time of this step execution' }),
    flowId: zod_1.z.string().optional().meta({
        description: 'ID of the flow this step belongs to. Format: "invariant_id:version". The invariant_id portion is stable across flow versions.',
    }),
    flowIndex: zod_1.z.number().optional().meta({
        description: 'Index of the flow in the test (0 = main flow, 1+ = nested flows in order of first execution)',
    }),
    stepLoop: zod_1.z
        .number()
        .optional()
        .meta({
        description: 'For steps that loop (retry logic, etc.), the 1-based loop iteration number (1, 2, 3...). ' +
            'Undefined if step only executed once. This is step-level looping, distinct from flow-level looping.',
    }),
    isInNestedFlow: zod_1.z.boolean().optional().meta({
        description: 'True if this step is executing inside a nested flow (a flow called by another flow). Helps identify steps that are part of reusable flows.',
    }),
    isInStepGroup: zod_1.z.boolean().optional().meta({
        description: 'True if this step is inside a step group. Step groups are collections of steps that are grouped together for organization.',
    }),
    flowName: zod_1.z.string().optional().meta({
        description: 'Human-readable name of the flow this step belongs to, if available.',
    }),
    stepId: zod_1.z.string().optional().meta({
        description: 'Stable step identifier within the flow (step_id_in_flow). Consistent across test runs of the same test version.',
    }),
    stepRunId: zod_1.z.string().optional().meta({
        description: 'Unique identifier for this specific step execution instance. Different for each run, including loop iterations.',
    }),
    traSessionId: zod_1.z
        .string()
        .optional()
        .meta({
        description: 'Test Recovery Agent session ID, if TRA ran on this step. ' +
            'Use get_test_recovery_session to fetch what the TRA did.',
    }),
});
// Schema for plan context (extracted from execution logs and plan run)
var planContextSchema = zod_1.z.object({
    id: zod_1.z.string().meta({ description: 'Plan ID' }),
    planRunId: zod_1.z.string().optional().meta({ description: 'Plan run ID' }),
    name: zod_1.z.string().optional().meta({ description: 'Plan name (fetched when relevant)' }),
    triggerType: zod_1.z
        .enum(['manual', 'retry', 'schedule', 'customer_event', 'insight', 'external'])
        .optional()
        .meta({ description: 'How the plan run was triggered' }),
    retryCount: zod_1.z
        .number()
        .optional()
        .meta({ description: 'Retry attempt number (0 = initial run, 1 = first retry, etc.)' }),
    retryOfId: zod_1.z.string().optional().meta({ description: 'ID of the plan run this is a retry of' }),
    retryType: zod_1.z
        .enum(['all', 'failed', 'failed_and_skipped'])
        .optional()
        .meta({ description: 'For retries: which tests were retried' }),
    willRetry: zod_1.z.boolean().optional().meta({ description: 'Whether this plan run will automatically retry on failure' }),
});
// Schema for application context
var applicationContextSchema = zod_1.z.object({
    id: zod_1.z.string().meta({ description: 'Application ID' }),
    name: zod_1.z.string().optional().meta({ description: 'Application name (fetched when relevant)' }),
});
// Schema for environment context
var environmentContextSchema = zod_1.z.object({
    id: zod_1.z.string().meta({ description: 'Environment ID' }),
    name: zod_1.z.string().optional().meta({ description: 'Environment name (fetched when relevant)' }),
});
// Schema for credentials context
var credentialsContextSchema = zod_1.z.object({
    credentialsId: zod_1.z.string().optional().meta({ description: 'Login credentials ID used for this run' }),
    httpAuthCredentialsId: zod_1.z.string().optional().meta({ description: 'HTTP Basic Auth credentials ID used for this run' }),
});
// Schema for scenario/datatable context (from journey_parameters)
var scenarioContextSchema = zod_1.z.object({
    scenarioIds: zod_1.z.array(zod_1.z.string()).optional().meta({ description: 'Specific scenario IDs run' }),
    datatableId: zod_1.z.string().optional().meta({ description: 'Datatable/Variable table ID' }),
    datatableRowId: zod_1.z.string().optional().meta({ description: 'Datatable row ID (specific scenario)' }),
    scenarioId: zod_1.z.string().optional().meta({ description: 'Scenario ID from the datatable row' }),
});
// Schema for URL context (extracted from execution logs)
var urlContextSchema = zod_1.z.object({
    startUrl: zod_1.z.string().optional().meta({ description: 'Initial URL the test started on' }),
    uniqueUrls: zod_1.z.array(zod_1.z.string()).optional().meta({ description: 'List of unique URLs visited during the test' }),
});
// Schema for device emulation info (for web tests with device emulation)
var deviceEmulationContextSchema = zod_1.z.object({
    deviceName: zod_1.z.string().optional().meta({ description: 'Emulated device name (e.g., "iPhone 12", "iPad Pro")' }),
    orientation: zod_1.z
        .string()
        .optional()
        .meta({ description: 'Device orientation (portrait_primary, landscape_primary, etc.)' }),
});
// Schema for mobile device info (for mobile tests)
var mobileDeviceContextSchema = zod_1.z.object({
    platform: zod_1.z.string().optional().meta({ description: 'Mobile platform (ios, android)' }),
    deviceName: zod_1.z.string().optional().meta({ description: 'Device name (e.g., "iPhone 14", "Pixel 7")' }),
    deviceManufacturer: zod_1.z
        .string()
        .optional()
        .meta({ description: 'Device manufacturer (e.g., "Apple", "Google", "Samsung")' }),
    osVersion: zod_1.z.string().optional().meta({ description: 'Operating system version' }),
});
// Schema for localization settings
var localizationContextSchema = zod_1.z.object({
    locale: zod_1.z.string().optional().meta({ description: 'Language locale identifier (e.g., en-US, jp)' }),
    timezoneIdentifier: zod_1.z.string().optional().meta({ description: 'Timezone identifier (e.g., America/Los_Angeles, UTC)' }),
});
// Schema for deployment info
var deploymentContextSchema = zod_1.z.object({
    deploymentId: zod_1.z.string().optional().meta({ description: 'Deployment ID' }),
    applicationId: zod_1.z.string().optional().meta({ description: 'Application ID' }),
    environmentId: zod_1.z.string().optional().meta({ description: 'Environment ID' }),
    deploymentType: zod_1.z
        .enum(['web_application', 'api', 'mobile_application'])
        .optional()
        .meta({ description: 'Type of deployment' }),
});
// Schema for timing summary
var timingSummaryContextSchema = zod_1.z.object({
    findTimeMs: zod_1.z.number().optional().meta({ description: 'Total time spent finding elements (ms)' }),
    findExtraWaitTimeMs: zod_1.z.number().optional().meta({ description: 'Extra wait time added by intelligent waiting (ms)' }),
});
// Schema for assert failure details
var assertFailureSchema = zod_1.z.object({
    reason: zod_1.z.string().optional().meta({ description: 'Assert failure description' }),
    expected: zod_1.z.string().optional().meta({ description: 'Expected value' }),
    found: zod_1.z.string().optional().meta({ description: 'Actual value found' }),
});
// Schema for link checker results
var linkCheckerResultsSchema = zod_1.z.object({
    checkedLinks: zod_1.z.number().optional().meta({ description: 'Total number of links checked' }),
    brokenLinks: zod_1.z.number().optional().meta({ description: 'Number of broken links found' }),
    checkedPages: zod_1.z.number().optional().meta({ description: 'Number of pages checked for links' }),
});
// Schema for HAR (HTTP Archive) summary - aggregated HTTP status codes from network requests
var harSummarySchema = zod_1.z.object({
    totalRequests: zod_1.z.number().meta({ description: 'Total number of HTTP requests' }),
    statusCodeCounts: zod_1.z
        .record(zod_1.z.string(), zod_1.z.number())
        .meta({ description: 'Count of requests by HTTP status code (e.g., {"200": 45, "404": 2})' }),
    errorCount: zod_1.z.number().optional().meta({ description: 'Number of requests with error status codes (4xx, 5xx)' }),
});
// Schema for the test run context (plan, scenario, etc. - from journey_parameters and plan run)
exports.testRunContextSchema = zod_1.z.object({
    application: applicationContextSchema.optional().meta({ description: 'Application this test ran against' }),
    environment: environmentContextSchema.optional().meta({ description: 'Environment this test ran in' }),
    plan: planContextSchema.optional().meta({ description: 'Plan that triggered this test run' }),
    credentials: credentialsContextSchema.optional().meta({ description: 'Credentials used for this test run' }),
    scenario: scenarioContextSchema.optional().meta({ description: 'Scenario/datatable info used in this run' }),
    urls: urlContextSchema.optional().meta({ description: 'URL information from the test run' }),
    triggeredBy: zod_1.z.string().optional().meta({ description: 'How the test run was triggered (e.g., plan, ad-hoc)' }),
    browserVersion: zod_1.z.string().optional().meta({ description: 'Browser version used' }),
    deviceEmulation: deviceEmulationContextSchema
        .optional()
        .meta({ description: 'Device emulation settings (for web tests with device emulation like iPad, iPhone)' }),
    mobileDevice: mobileDeviceContextSchema
        .optional()
        .meta({ description: 'Mobile device configuration (for mobile tests)' }),
    localization: localizationContextSchema.optional().meta({ description: 'Localization settings (locale and timezone)' }),
    pageLoadWait: zod_1.z
        .enum(['FAST', 'NORMAL', 'SLOW', 'SLOWER'])
        .optional()
        .meta({ description: 'Page load wait setting that affects timing' }),
    linkServerIds: zod_1.z.array(zod_1.z.string()).optional().meta({ description: 'Link server IDs used for network tunneling' }),
    relatedDeployments: zod_1.z
        .array(deploymentContextSchema)
        .optional()
        .meta({ description: 'Related deployments (e.g., API deployment for browser tests)' }),
    sourceControl: schemas_js_1.sourceControlContextSchema
        .optional()
        .meta({ description: 'Source control context (revision, branch, PR info) from CI/CD integration' }),
    timingSummary: timingSummaryContextSchema
        .optional()
        .meta({ description: 'Timing metrics for element finding operations' }),
    linkCheckerResults: linkCheckerResultsSchema.optional().meta({ description: 'Link checker results if enabled' }),
    stepFeatures: zod_1.z
        .array(zod_1.z.string())
        .optional()
        .meta({ description: 'List of advanced step features used in this test (e.g., ai_assertion, visual_change)' }),
    harSummary: harSummarySchema
        .optional()
        .meta({ description: 'Aggregated HTTP status code summary from network requests during test execution' }),
    exportedVariables: zod_1.z
        .record(zod_1.z.string(), zod_1.z.unknown())
        .optional()
        .meta({
        description: 'Variables exported from this test run. These can be passed to subsequent tests in a plan. ' +
            'Keys are variable names, values are the exported values.',
    }),
});
var testRunSummarySchema = zod_1.z.object({
    testRunId: zod_1.z.string().meta({ description: 'Test run ID' }),
    testId: zod_1.z.string().optional().meta({ description: 'Test ID (journey_id)' }),
    testInvariantId: zod_1.z.string().optional().meta({ description: 'Test invariant ID (stable across versions)' }),
    testVariantId: zod_1.z.string().optional().meta({ description: 'Test variant ID (changes when test is modified)' }),
    testName: zod_1.z.string().meta({ description: 'Test name' }),
    testType: zod_1.z.enum(['browser', 'api', 'mobile', 'performance', 'unknown']).optional().meta({
        description: 'Type of test (browser, api, mobile, performance). Affects available data (e.g., API tests have no screenshots).',
    }),
    status: zod_1.z.enum(['passed', 'failed', 'skipped', 'terminated']).meta({ description: 'Overall status' }),
    startTime: zod_1.z.string().meta({ description: 'Start time as ISO string' }),
    endTime: zod_1.z.string().optional().meta({ description: 'End time as ISO string' }),
    durationMs: zod_1.z.number().optional().meta({ description: 'Total duration in milliseconds' }),
    totalSteps: zod_1.z.number().meta({ description: 'Total number of steps' }),
    passedSteps: zod_1.z.number().meta({ description: 'Number of passed steps' }),
    failedSteps: zod_1.z.number().meta({ description: 'Number of failed steps' }),
    browser: zod_1.z
        .string()
        .optional()
        .meta({ description: 'Browser used for the test (browser tests only, not included for API/mobile)' }),
    failureReason: zod_1.z.string().optional().meta({ description: 'Failure reason if test failed' }),
    assertFailure: assertFailureSchema
        .optional()
        .meta({ description: 'Structured assertion failure details with expected/found values' }),
    terminationReason: zod_1.z
        .enum(['cancelled', 'timeout', 'exceeded_max_steps', 'exceeded_max_time', 'error', 'unknown'])
        .optional()
        .meta({ description: 'Why the test was terminated (only present if status is terminated)' }),
    statusCause: zod_1.z
        .string()
        .optional()
        .meta({ description: 'Additional context for the status (e.g., termination reason)' }),
    failureCategoryId: zod_1.z
        .string()
        .optional()
        .meta({ description: 'Failure category ID if categorized (informational, may be user-assigned or AI-suggested)' }),
    firstFailedStepIndex: zod_1.z.number().optional().meta({ description: 'Index of the first failed step' }),
});
// Base schema for flow step fields (used by both regular steps and nested steps)
var flowStepBaseSchema = zod_1.z.object({
    index: zod_1.z.number().meta({ description: 'Step index (execution order across journey)' }),
    stepNumber: zod_1.z.string().meta({
        description: 'Human-readable step number with dotted notation for nested steps (1-based). ' +
            'Examples: "5" for step 5, "3.2" for step 2 inside step group at position 3.',
    }),
    stepIndexInFlow: zod_1.z.number().meta({ description: 'Step index within this flow or step group (0-based)' }),
    description: zod_1.z.string().meta({ description: 'Human-readable step description' }),
    status: zod_1.z.enum(['passed', 'failed', 'skipped', 'warning', 'disabled']).meta({
        description: 'Status of the step execution. ' +
            '"disabled" indicates the step was explicitly disabled by the user and not executed.',
    }),
    durationMs: zod_1.z.number().optional().meta({ description: 'Duration in milliseconds' }),
    errorMessage: zod_1.z.string().optional().meta({ description: 'Error message if the step failed' }),
    hasScreenshot: zod_1.z.boolean().meta({ description: 'Whether this step has a screenshot available' }),
    isStepGroup: zod_1.z.boolean().optional().meta({ description: 'True if this is a step group containing nested steps' }),
    stepGroupName: zod_1.z.string().optional().meta({ description: 'Name of the step group if this is a step group' }),
    nestingDepth: zod_1.z.number().optional().meta({ description: 'How deep this step is nested (0 = top level in flow)' }),
});
var flowStepSchema = flowStepBaseSchema.extend({
    nestedSteps: zod_1.z
        .lazy(function () { return zod_1.z.array(flowStepSchema); })
        .optional()
        .meta({
        description: 'Nested steps if this is a step group. Step groups can contain other step groups (recursive nesting up to 5 levels). ' +
            'Each nested step has the same structure as top-level steps.',
    }),
});
// Schema for flow execution summary (when include_flow_breakdown is true)
var flowExecutionSummarySchema = zod_1.z.object({
    flowId: zod_1.z.string().meta({
        description: 'Flow ID in format "invariant_id:version". Use the invariant_id portion for stable identification across versions.',
    }),
    flowIndex: zod_1.z.number().meta({ description: 'Index of this flow in execution order (0 = main flow)' }),
    flowName: zod_1.z.string().optional().meta({ description: 'Human-readable flow name if available' }),
    isMainFlow: zod_1.z.boolean().meta({ description: 'True if this is the main test flow (not a nested flow)' }),
    loopNumber: zod_1.z.number().optional().meta({
        description: 'For flows that execute multiple times (loops), the 1-based loop iteration number (1, 2, 3...). Undefined if flow only ran once.',
    }),
    totalLoops: zod_1.z.number().optional().meta({
        description: 'Total number of times this flow executed. Only present if flow ran more than once.',
    }),
    calledFromStepIndex: zod_1.z
        .number()
        .optional()
        .meta({
        description: 'For nested flows: the step index in the journey that triggered this flow call. ' +
            'This allows linking a nested flow back to the EvaluateFlow step in the parent flow. ' +
            'Only present for nested flows (isMainFlow=false).',
    }),
    parentFlowId: zod_1.z
        .string()
        .optional()
        .meta({
        description: 'For nested flows: the flowId of the parent flow that called this flow. ' +
            'Use this to build the flow call tree (which flow called which). ' +
            'Only present for nested flows (isMainFlow=false).',
    }),
    totalSteps: zod_1.z.number().meta({ description: 'Total number of steps in this flow execution' }),
    passedSteps: zod_1.z.number().meta({ description: 'Number of passed steps in this flow execution' }),
    failedSteps: zod_1.z.number().meta({ description: 'Number of failed steps in this flow execution' }),
    skippedSteps: zod_1.z.number().meta({ description: 'Number of skipped steps in this flow execution' }),
    disabledSteps: zod_1.z.number().meta({ description: 'Number of disabled steps in this flow execution' }),
    status: zod_1.z.enum(['passed', 'failed', 'skipped', 'disabled']).meta({
        description: 'Overall status of this flow execution. ' +
            'failed if any step failed, skipped if all skipped, disabled if all disabled, passed otherwise.',
    }),
    durationMs: zod_1.z.number().optional().meta({ description: 'Total duration of this flow execution in milliseconds' }),
    firstStepIndex: zod_1.z.number().meta({ description: 'Index of the first step of this flow in the flattened step list' }),
    lastStepIndex: zod_1.z.number().meta({ description: 'Index of the last step of this flow in the flattened step list' }),
    flowSteps: zod_1.z
        .array(flowStepSchema)
        .optional()
        .meta({
        description: 'Steps within this flow execution, organized hierarchically. Step groups show their nested steps. ' +
            'Each step includes its position in the flow (stepIndexInFlow) and execution index.',
    }),
});
exports.getTestRunInfoResponseSchema = zod_1.z.object({
    summary: testRunSummarySchema.meta({ description: 'Summary information about the test run' }),
    context: exports.testRunContextSchema.optional().meta({ description: 'Contextual information about the test run' }),
    steps: zod_1.z
        .array(testStepInfoSchema)
        .optional()
        .meta({ description: 'Detailed step information (if include_steps is true)' }),
    stepRange: zod_1.z
        .object({
        start: zod_1.z.number(),
        end: zod_1.z.number(),
        total: zod_1.z.number(),
    })
        .optional()
        .meta({ description: 'Range of steps included in the response' }),
    flowBreakdown: zod_1.z
        .array(flowExecutionSummarySchema)
        .optional()
        .meta({
        description: 'Flow-level execution breakdown (if include_flow_breakdown is true). Shows summary per flow including step counts, status, and duration. ' +
            'Useful for understanding which nested flows passed/failed and identifying problems in specific reusable flows.',
    }),
    formattedStepList: zod_1.z
        .string()
        .optional()
        .meta({
        description: 'Pre-formatted step list with each step on its own line, proper indentation for nested flows, and status indicators. ' +
            'ALWAYS use this for displaying steps to users - it ensures correct formatting with newlines and indentation.',
    }),
});
exports.GetTestRunInfoToolDefinition = (0, toolDefinition_js_1.defineTool)({
    name: agentToolNames_js_1.AgentToolNames.GetTestRunInfo,
    description: "Retrieves comprehensive information about a test run including status, steps, timing, configuration, and contextual details.\n\nUse this tool to:\n- Understand the overall test run result and status\n- Get a list of all test steps with their execution status\n- Find which steps failed and why\n- Get timing information about the test execution\n- Learn about the test configuration (browser, environment, etc.)\n- Understand the context: which application, environment, plan, and datatables were used\n- See URLs visited during the test\n- Identify how the test was triggered (plan, API, manual, etc.)\n- Analyze nested flows and step groups (use include_flow_breakdown=true)\n\nYou can filter to specific steps using step_run_ids (preferred for precise targeting) or step_start_index/step_end_index for ranges.\nSet include_context=false if you only need basic summary information without detailed context.\n\nFor tests with nested flows or step groups, use include_flow_breakdown=true to get a flow-level summary showing:\n- Which flows passed or failed\n- Step counts and duration per flow\n- Step groups within each flow",
    argumentsSchema: exports.getTestRunInfoParamsSchema,
    responseSchema: exports.getTestRunInfoResponseSchema,
});
//# sourceMappingURL=GetTestRunInfoDefinition.js.map