All files / src/entities/duo commands.ts

100% Statements 99/99
100% Branches 75/75
100% Functions 8/8
100% Lines 96/96

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 23521x   21x 21x 21x 21x 21x 21x 21x 21x               21x             21x   21x   21x                                                                         27x 27x             23x 23x           4x 19x                 8x     8x 3x 3x   5x                         36x 24x 24x 24x 1x 23x 23x 23x 23x 1x 22x 22x 1x 21x                   21x 1x   20x 2x             13x 13x 1x 12x 1x 11x 1x 10x               42x 42x 42x 13x 10x 10x 29x 3x 1x 2x 2x   2x 1x 1x   26x 1x     25x   36x     21x       43x 43x 43x 43x 1x     42x 36x 36x 19x     21x       12x 12x 12x     12x 11x   12x 1x 11x 11x 1x 10x 1x     9x 1x     8x 8x 8x            
import { gql } from 'graphql-tag';
import type { EffectivePolicy } from '../../configuration/policy';
import { gitlab, GitLabApiError } from '../../utils/gitlab-api';
import { getGitLabBaseUrl } from '../../utils/gitlab-base-url';
import { normalizeProjectId } from '../../utils/projectIdentifier';
import { encodeApiSegment } from '../../utils/api-path';
import { extractSimpleId } from '../../utils/idConversion';
import { instanceAtLeast } from '../instance-version';
import { readDuoProject, assertDuoProject, assertWorkflowProject, type DuoProject } from './access';
import {
  readConsumer,
  foundationalAgents,
  projectEnablement,
  isDuoChat,
  executionUnavailable,
  type Consumer,
} from './discovery';
import {
  DUO_RESPONSE_BYTES,
  requestDuo,
  readWorkflow,
  workflowGid,
  type Workflow,
} from './queries';
import { WAITING, statusCode } from './sessions';
import type { ManageDuoSessionInput } from './schema';
import { legacyGoalContext } from './legacy-goal-context';
 
const INPUT_STATE = gql`
  query DuoResumeState($id: AiDuoWorkflowsWorkflowID!) {
    duoWorkflowWorkflows(workflowId: $id, first: 1) {
      nodes {
        id
        projectId
        humanStatus
        createdAt
        statusName @optional
        status @optional
        workflowDefinition @optional
        aiCatalogItemVersionId @optional
        project @optional {
          id
          fullPath
        }
        userPermissions {
          resumeDuoWorkflow
        }
      }
    }
  }
`;
 
interface MutationResult {
  id: string | number;
  status: string;
  web_url?: string | null;
  workload?: { id?: string | null } | null;
}
 
/** Never replay an HTTP write, including redirects and ambiguous transport failures. */
async function mutate(
  path: string,
  body: Record<string, unknown>,
  workflowId?: string,
): Promise<unknown> {
  try {
    const result = await gitlab.post<MutationResult>(path, {
      body,
      contentType: 'json',
      rawResponse: true,
      responseByteLimit: DUO_RESPONSE_BYTES,
      redirect: 'error',
    });
    const id = result?.id;
    if (
      (typeof id !== 'string' && typeof id !== 'number') ||
      (typeof id === 'number' && !Number.isSafeInteger(id)) ||
      !/^[1-9]\d*$/.test(String(id)) ||
      typeof result.status !== 'string'
    )
      throw new Error('GitLab did not return a usable Duo session identity');
    return {
      workflow_id: String(result.id),
      status: result.status,
      web_url: result.web_url ?? null,
      workload_id: result.workload?.id ?? null,
      poll_after_seconds: 120,
    };
  } catch (error) {
    const guidance =
      workflowId === undefined
        ? 'Inspect browse_duo_sessions list before trying to start another session.'
        : `Inspect browse_duo_sessions get for workflow ${workflowId} before trying again.`;
    if (error instanceof GitLabApiError) {
      error.message += ` ${guidance} Do not automatically replay this command.`;
      throw error;
    }
    throw new Error(
      `Duo mutation outcome is unknown. ${guidance} Do not automatically replay this command.`,
      { cause: error },
    );
  }
}
 
/** These documented flows use a target URL, not a prose goal or the default branch. */
async function goalContext(
  project: DuoProject,
  flow: string | null | undefined,
  goal: string,
): Promise<Record<string, unknown>> {
  if (flow !== 'fix_pipeline/v1' && flow !== 'code_review/v1') return { goal };
  const target = new URL(goal);
  const base = new URL(getGitLabBaseUrl());
  if (target.origin !== base.origin || target.username || target.password)
    throw new Error('Duo target URL must belong to the selected GitLab instance');
  const kind = flow === 'fix_pipeline/v1' ? 'pipelines' : 'merge_requests';
  const prefix = `${base.pathname.replace(/\/$/, '')}/${project.path}/-/${kind}/`;
  const pathname = decodeURIComponent(target.pathname);
  if (!pathname.startsWith(prefix))
    throw new Error('Duo target URL must belong to the selected project');
  const id = pathname.slice(prefix.length);
  if (!/^[1-9]\d*$/.test(id))
    throw new Error('Duo target URL must identify one pipeline or merge request');
  const object = await gitlab.get<{
    project_id: number;
    ref?: string;
    source_branch?: string;
    source?: string;
    sha?: string;
  }>(
    `projects/${normalizeProjectId(project.id)}/${encodeApiSegment(kind)}/${encodeApiSegment(id)}`,
    { responseByteLimit: DUO_RESPONSE_BYTES, rawResponse: true },
  );
  if (String(object.project_id) !== project.id)
    throw new Error('Duo goal target belongs to another project');
  // GitLab 19.5 resolves the validated URL to its branch and additional context itself.
  if (!instanceAtLeast('19.5')) return legacyGoalContext(project, flow, object, target.href, id);
  return { goal: target.href };
}
 
async function checkedConsumer(
  id: string,
  project: DuoProject,
): Promise<NonNullable<Consumer['item']>> {
  const consumer = await readConsumer(id);
  if (!consumer.project || extractSimpleId(consumer.project.id) !== project.id)
    throw new Error('Configured Duo consumer does not belong to the selected project');
  if (!consumer.enabled || consumer.item?.itemType !== 'FLOW')
    throw new Error('Configured Duo consumer is not an enabled flow');
  if (consumer.userPermissions?.executeAiCatalogItem === false)
    throw new Error('GitLab does not permit executing this Duo flow');
  return consumer.item;
}
 
async function startSelection(
  input: Extract<ManageDuoSessionInput, { action: 'start' }>,
  project: DuoProject,
  enabledFlows: string[] | null | undefined,
): Promise<{ body: Record<string, unknown>; flow: string | null | undefined }> {
  const body: Record<string, unknown> = {};
  let flow: string | null | undefined = input.flow;
  if (input.consumer_id !== undefined) {
    const item = await checkedConsumer(input.consumer_id, project);
    flow = item.foundationalFlowReference;
    body.ai_catalog_item_consumer_id = input.consumer_id;
  } else if (input.agent !== undefined) {
    if (!instanceAtLeast('19.5'))
      throw new Error('Foundational agent CI sessions require GitLab 19.5');
    const available = (await foundationalAgents(project)).some(
      (entry) => entry.referenceWithVersion === input.agent,
    );
    if (!available || isDuoChat(input.agent))
      throw new Error('Select a startable foundational agent from project discovery');
    body.workflow_definition = input.agent;
  } else {
    if (input.flow === undefined || !enabledFlows?.includes(input.flow))
      throw new Error(
        'The foundational flow is not enabled in this project; select a configured consumer from discovery',
      );
    body.workflow_definition = input.flow;
  }
  return { body, flow };
}
 
export async function startDuoSession(
  input: Extract<ManageDuoSessionInput, { action: 'start' }>,
  policy: EffectivePolicy,
): Promise<unknown> {
  const project = await readDuoProject(input.project_id);
  assertDuoProject(project, policy);
  const enablement = await projectEnablement(project);
  if (executionUnavailable(enablement))
    throw new Error(
      'GitLab Duo CI execution is unavailable; inspect agents_and_flows prerequisites',
    );
  const { body, flow } = await startSelection(input, project, enablement?.enabledFoundationalFlows);
  Object.assign(body, { project_id: project.id, start_workflow: true, environment: 'ambient' });
  Object.assign(body, await goalContext(project, flow, input.goal));
  return mutate('ai/duo_workflows/workflows', body);
}
 
export async function sendDuoInput(
  input: Extract<ManageDuoSessionInput, { action: 'send_input' }>,
  policy: EffectivePolicy,
): Promise<unknown> {
  const before = await readWorkflow(input.workflow_id);
  await assertWorkflowProject(before, policy);
  const result = await requestDuo<{
    duoWorkflowWorkflows: { nodes: Array<Workflow & { aiCatalogItemVersionId?: string | null }> };
  }>(INPUT_STATE, { id: workflowGid(input.workflow_id) });
  const row = result.duoWorkflowWorkflows.nodes.find(
    (entry) => extractSimpleId(entry.id) === extractSimpleId(input.workflow_id),
  );
  if (row?.projectId !== before.projectId)
    throw new Error('Duo session project changed or is unavailable');
  const status = statusCode(row);
  if (status === null || !WAITING.has(status))
    throw new Error('Duo session is not in a supported waiting state');
  if (row.userPermissions?.resumeDuoWorkflow !== true)
    throw new Error(
      'GitLab does not currently allow resuming: the preceding CI job may still be running, or access is restricted',
    );
  if (!instanceAtLeast('19.5') && !row.aiCatalogItemVersionId)
    throw new Error(
      'This GitLab version can resume catalog flows only; foundational agents require GitLab 19.5',
    );
  const body: Record<string, unknown> = { human_approval: input.human_approval };
  if (input.human_message !== undefined) body.human_message = input.human_message;
  return mutate(
    `ai/duo_workflows/workflows/${extractSimpleId(input.workflow_id)}/resume`,
    body,
    extractSimpleId(input.workflow_id),
  );
}