import * as fs from "node:fs/promises"; import * as path from "node:path"; import { discoverGitLabDuoWorkflowRuntimeNamespace, type GitLabDuoWorkflowNamespaceSelection, } from "@oh-my-pi-zen/pi-catalog/discovery/gitlab-duo-workflow"; import * as AIError from "../error"; import { parseToolCallArguments } from "../utils/tool-call-arguments"; import type { Api, AssistantMessage, Context, FetchImpl, Message, Model, ProviderSessionState, StreamFunction, StreamOptions, Tool, ToolCall, ToolChoice, ToolResultMessage, } from "../types"; import { normalizeSystemPrompts } from "../utils"; import { AssistantMessageEventStream } from "../utils/event-stream"; import { toolWireSchema } from "../utils/schema/wire"; import chatmlHistoryNote from "./gitlab-duo-workflow-chatml-note.md" with { type: "text" }; import { redactSensitiveCredentials } from "./transform-messages"; export const GITLAB_DUO_WORKFLOW_PROVIDER_ID = "gitlab-duo-agent"; export const GITLAB_DUO_WORKFLOW_API = "gitlab-duo-agent"; export const GITLAB_DUO_WORKFLOW_DEFINITION = "ambient"; export type GitLabDuoWorkflowDefinition = "ambient" | (string & {}); const DEFAULT_GITLAB_BASE_URL = "https://gitlab.com"; const GITLAB_DUO_WORKFLOW_TRACE_ENV = "GITLAB_DUO_WORKFLOW_TRACE"; const GITLAB_DUO_WORKFLOW_TRACE_FILE_ENV = "GITLAB_DUO_WORKFLOW_TRACE_FILE"; const DEFAULT_GITLAB_DUO_WORKFLOW_TRACE_FILE = path.resolve( import.meta.dir, "../../../../.tmp/gitlab-duo-workflow-trace.log", ); const GITLAB_DUO_WORKFLOW_CLIENT_TYPE = "node-websocket"; /** * Idle deadline for the workflow WebSocket. The socket has no server-side * keepalive contract OMP can rely on, so a connection silently going half-open * (proxy/LB drops the TCP link without delivering FIN/RST) would otherwise leave * `runGitLabDuoWorkflowSocket` waiting forever. If no frame arrives within this * window — before open or between checkpoints — the socket is aborted and the * run reconnects once on the same `workflowID` (server-side resume). */ const GITLAB_DUO_WORKFLOW_IDLE_TIMEOUT_MS = 90_000; /** * Absolute deadline (ms) for each REST setup fetch (`ensureGitLabDuoWorkflowSettings`, * `discoverGitLabDuoWorkflowProject`, `resolveGitLabDuoWorkflowNumericProjectId`, * `requestGitLabDuoWorkflowDirectAccess`, `createGitLabDuoWorkflow`, * `fetchGitLabDuoWorkflowAvailableModels`, `stopGitLabDuoWorkflow`). * * `streamGitLabDuoWorkflow` pushes its `start` event before these calls run and the * `gitlab-duo-agent` bypass in `streamSimple` skips the `register-builtins` * `iterateWithIdleTimeout` wrapper, so a stalled setup fetch would otherwise leave * the stream with no terminal event. 30s covers healthy p99 for every REST endpoint * the workflow touches while still surfacing a real stall as a provider error; * matches the OAuth `TOKEN_REQUEST_TIMEOUT_MS` used by sibling GitLab flows. */ const GITLAB_DUO_WORKFLOW_REST_TIMEOUT_MS = 30_000; /** * How many times a single stream may restart on a FRESH workflow after the server * reports its per-workflow step (graph-recursion) limit. Long OMP tool-call loops * legitimately overrun the cap; each restart resets the budget. Bounded so a task * that perpetually overruns degrades to a graceful stop instead of looping on quota. */ const GITLAB_DUO_WORKFLOW_MAX_STEP_LIMIT_RESTARTS = 4; /** * How many times a single stream may restart on a FRESH workflow after the server * returns its de-identified catch-all FAILED (transient upstream fault wrapper). * Kept low because, unlike the step limit, a generic failure that repeats is more * likely deterministic; one bounded retry covers the common transient case without * looping on quota. */ const GITLAB_DUO_WORKFLOW_MAX_GENERIC_ERROR_RETRIES = 1; /** * How many times a single stream may restart on a FRESH workflow after detecting a * stalled workflow: the server emitted a fresh checkpoint at a tool-call boundary * but its `ui_chat_log` total did NOT advance past the previous tool-call boundary * of the SAME workflow. A healthy run strictly grows the log each turn (agent * reasoning + tool boundary entries); a flat total means the server-side turn did * not progress — the model re-issues the same tool call against a history that * never gained its prior call/result (captured live: total pinned at 2 while the * model repeated `next_step({"n":1})`). Restarting on a fresh workflow resends the * full goal transcript (rebuilt from the agent loop's intact `context.messages`, * so no in-flight tool result is lost) and the new run progresses. Bounded so a * persistently stalling endpoint degrades to a surfaced result instead of a quota * sink. */ const GITLAB_DUO_WORKFLOW_MAX_STALL_RESTARTS = 2; /** * Surfaced when a workflow stalled (its `ui_chat_log` total stopped advancing) and * every bounded fresh-workflow restart also stalled. Phrased as a transient * server-side failure so the agent loop treats it as a normal error rather than a * client bug. */ const GITLAB_DUO_WORKFLOW_STALL_ERROR_MESSAGE = "GitLab Duo Agent stopped making progress (the workflow's visible history did not advance after multiple restarts)."; /** * Two rendered-`goal` byte thresholds bounding three reliability zones. Empirically * the DWS/Workhorse transport accepts no fixed token wall (it has tokenized * 970k-token goals) but its failure probability rises with the rendered-goal BYTE * size: ≤~1MB is the reliable floor we now treat as the auto-compaction trigger, * ~1.4–1.7MB is a jitter band where a request fails more often than not but can still * go through, ≥~2MB basically always fails, and 4MB is the DWS gRPC `MAX_MESSAGE_SIZE` * hard cap. The soft threshold was lowered from 1.25MB to 1MB because the higher value * almost never fired in practice — auto-compaction needs to engage earlier. * * - `[0, SOFT)` reliable zone: send normally; an error here is a genuine upstream * fault and surfaces verbatim. * - `[SOFT, HARD)` jitter zone: still attempt once (it can succeed); if the run then * ERRORS, the size is the likely cause, so re-label it as a context-overflow to * drive auto-compaction. * - `[HARD, ∞)` necessary-fail zone: do NOT spend the request — proactively end the * stream with the overflow error so the session compacts immediately. * * `SOFT` is the auto-compaction trigger floor; `HARD` is the necessary-fail floor. * Re-labeling uses {@link buildGitLabDuoWorkflowGoalOverflowMessage}. */ const GITLAB_DUO_WORKFLOW_GOAL_SOFT_OVERFLOW_BYTES = 1_048_576; const GITLAB_DUO_WORKFLOW_GOAL_HARD_OVERFLOW_BYTES = 2_000_000; // An overflow-pattern message for an oversized goal. The "prompt is too long" prefix // is one of the shared overflow classifier patterns, so // `isContextOverflow` recognizes it and the session triggers auto-compaction instead // of surfacing a hard failure. Byte counts (not tokens) are reported because the // budget is a byte budget. function buildGitLabDuoWorkflowGoalOverflowMessage(goalBytes: number): string { return `prompt is too long: ${goalBytes} bytes exceeds the GitLab Duo Agent goal byte budget (soft ${GITLAB_DUO_WORKFLOW_GOAL_SOFT_OVERFLOW_BYTES}, hard ${GITLAB_DUO_WORKFLOW_GOAL_HARD_OVERFLOW_BYTES})`; } const GITLAB_DUO_WORKFLOW_LANGUAGE_SERVER_VERSION = "8.104.0"; const GITLAB_DUO_WORKFLOW_AVAILABLE_MODELS_QUERY = `query omp_gitlabDuoWorkflowAvailableModels($rootNamespaceId: GroupID!) { aiChatAvailableModels(rootNamespaceId: $rootNamespaceId) { defaultModel { name ref } selectableModels { name ref } pinnedModel { name ref } } }`; export const GITLAB_DUO_WORKFLOW_CLIENT_CAPABILITIES = [ "incremental_streaming", "read_file_chunked", "shell_command", "command_timeout", "tool_call_approval", ] as const; const GITLAB_DUO_WORKFLOW_INLINE_AGENT_NAME = "omp_agent"; const GITLAB_DUO_WORKFLOW_INLINE_PROMPT_ID = "omp_inline_prompt"; // `on_agent_reasoning` is what makes the server tag an agent's pre-tool-call // commentary as `message_sub_type: "reasoning"` — the chain-of-thought the // official Duo CLI surfaces. An inline flow must opt in explicitly. const GITLAB_DUO_WORKFLOW_INLINE_UI_LOG_EVENTS = [ "on_agent_reasoning", "on_agent_final_answer", "on_tool_execution_success", "on_tool_execution_failed", ] as const; const GITLAB_DUO_WORKFLOW_ACTION_NAMES = ["runMCPTool", "run_mcp_tool"] as const; export interface GitLabMcpToolArgs { name?: string; tool_name?: string; toolName?: string; providerIdentifier?: string; provider_identifier?: string; toolCallId?: string; tool_call_id?: string; args?: Record | string; arguments?: Record | string; } export interface GitLabPlainTextResponse { response?: string; error?: string; } export type PlainTextResponse = GitLabPlainTextResponse; export interface GitLabDuoWorkflowOptions extends StreamOptions { rootNamespaceId?: string; namespaceId?: string; projectId?: string; projectPath?: string; workflowDefinition?: GitLabDuoWorkflowDefinition; workflowId?: string; workflowToken?: string; cwd?: string; webSocketFactory?: GitLabDuoWorkflowWebSocketFactory; /** Idle WebSocket deadline (ms) before aborting and resuming; defaults to {@link GITLAB_DUO_WORKFLOW_IDLE_TIMEOUT_MS}. */ idleTimeoutMs?: number; /** * Tool-choice override forwarded from the stream layer. Only `"none"` is * acted on: a side-request (e.g. handoff) keeps tool definitions in the cache * prefix but disables tool use, so the provider must not advertise them to Duo. */ toolChoice?: ToolChoice; } export interface GitLabDuoWorkflowWebSocketLike { readyState?: number; binaryType?: string; onopen: ((event: Event) => void) | null; onmessage: ((event: MessageEvent) => void) | null; onerror: ((event: Event) => void) | null; onclose: ((event: CloseEvent) => void) | null; send(data: string): void; close(code?: number, reason?: string): void; } export interface GitLabDuoWorkflowWebSocketFactoryOptions { headers: Record; protocols?: string[]; } export type GitLabDuoWorkflowWebSocketFactory = ( url: string, options: GitLabDuoWorkflowWebSocketFactoryOptions, ) => GitLabDuoWorkflowWebSocketLike; export interface GitLabDirectAccessResponse { token?: string; access_token?: string; jwt?: string; workflow_token?: string; duo_workflow_access_token?: string; duo_workflow_service?: { token?: string; base_url?: string; headers?: Record }; gitlab_rails?: { token?: string }; [key: string]: unknown; } interface GitLabDuoWorkflowDirectAccessConnection { token: string; baseUrl?: string; headers: Record; serviceEndpoint: boolean; } interface GitLabCreateWorkflowResponse { id?: string | number; workflow_id?: string | number; workflowId?: string | number; [key: string]: unknown; } interface GitLabDuoWorkflowCreateBodyOptions { projectId?: string; goal?: string; workflowDefinition?: GitLabDuoWorkflowDefinition; } interface GitLabDuoWorkflowStartMetadataOptions { projectId?: string; projectPath?: string; namespaceId?: string; rootNamespaceId?: string; workflowDefinition?: GitLabDuoWorkflowDefinition; inlineFlow?: boolean; } export interface GitLabMcpToolDefinition { name: string; originalToolName: string; serverName: string; description: string; inputSchema: string; isApproved: boolean; } export interface GitLabDuoWorkflowAdditionalContextItem { id: string; category: "agent_user_environment" | "user_rule"; content: string; metadata: { title: string; enabled: boolean; subType: "snippet"; icon: string; secondaryText: string; subTypeLabel: string; }; } export interface GitLabDuoWorkflowStartRequest { workflowID: string; clientVersion: "1.0"; workflowDefinition: GitLabDuoWorkflowDefinition; goal: string; workflowMetadata: string; additional_context: readonly GitLabDuoWorkflowAdditionalContextItem[]; approval?: { approval?: Record; rejection?: { message?: string }; }; clientCapabilities: readonly (typeof GITLAB_DUO_WORKFLOW_CLIENT_CAPABILITIES)[number][]; mcpTools: GitLabMcpToolDefinition[]; preapproved_tools: string[]; flowConfigSchemaVersion?: "v1"; flowConfigId?: string; flowVersion?: string; flowConfig?: GitLabDuoWorkflowInlineFlowConfig; } export interface GitLabDuoWorkflowInlineFlowComponent { name: string; type: "AgentComponent"; prompt_id: string; toolset: string[]; inputs: { from: string; as: string }[]; ui_log_events: string[]; } export interface GitLabDuoWorkflowInlineFlowPrompt { name: string; prompt_id: string; unit_primitives: string[]; prompt_template: { system: string; user: string; placeholder: string }; } export interface GitLabDuoWorkflowInlineFlowConfig { version: "v1"; environment: "ambient"; flow: { entry_point: string }; components: GitLabDuoWorkflowInlineFlowComponent[]; routers: { from: string; to: string }[]; prompts: GitLabDuoWorkflowInlineFlowPrompt[]; } export interface GitLabDuoWorkflowActionResponse { actionResponse: { requestID: string; plainTextResponse?: GitLabPlainTextResponse; }; } interface GitLabDuoWorkflowActionDescriptor { requestID: string; name: string; args: unknown; } export interface GitLabDuoWorkflowActiveSession { workflowId: string; startPayload: GitLabDuoWorkflowStartRequest; ws: GitLabDuoWorkflowWebSocketLike; // Best-effort server-side stop for THIS workflow, captured with its own // fetch/baseUrl/apiKey so `ProviderSessionState.close()` (session reset/dispose) // can stop a workflow the server is still running, even though it holds none of // that context itself. Fire-and-forget; never throws. stop?: () => void; pendingActions?: GitLabDuoWorkflowActionDescriptor[]; checkpointAgentContentByKey?: Record; checkpointAgentContentSignatures?: Record; paused?: boolean; pauseBuffer?: unknown[]; // Byte length of the server's last checkpoint observed at this workflow's tool-call // boundaries. The control experiment proved a healthy turn emits checkpoints whose // byte size varies and progresses, while a stalled workflow re-emits a byte-identical // checkpoint — so equal lengths across consecutive boundaries flag a stall (see // GITLAB_DUO_WORKFLOW_MAX_STALL_RESTARTS). Persisted on the session so the comparison // survives the resume that reuses this socket. lastToolBoundaryContentLength?: number; } export interface GitLabDuoWorkflowProviderSessionState extends ProviderSessionState { active?: GitLabDuoWorkflowActiveSession; } export interface GitLabDuoWorkflowStreamState { stream: AssistantMessageEventStream; output: AssistantMessage; activeTextIndex?: number; activeThinkingIndex?: number; activeCheckpointMessageKey?: string; started: boolean; checkpointAgentContentByKey?: Record; checkpointAgentContentSignatures?: Record; pauseRequested?: boolean; stepLimitRequested?: boolean; retryableErrorRequested?: boolean; // Byte length of the server's latest checkpoint seen this socket run; the action // handler compares it against the previous tool-call boundary's length to detect a // stall (a byte-identical checkpoint means the server-side turn did not advance). lastCheckpointContentLength?: number; // Set when a tool-call boundary's checkpoint byte length did not change from the // previous boundary — the socket settles "stalled" so the run restarts fresh. stalledRequested?: boolean; providerSessionState?: GitLabDuoWorkflowProviderSessionState; lastApprovalStatus?: string; // When the rendered goal exceeds the byte budget, this carries an overflow-pattern // message. A terminal/exhausted error then surfaces THIS instead of the raw server // error so `isContextOverflow` recognizes it and the agent loop auto-compacts. Left // undefined for a goal within budget, so ordinary errors surface verbatim. goalOverflowMessage?: string; } type GitLabDuoWorkflowSocketResult = | "closed" | "terminal" | "approval" | "action" | "pause" | "timeout" | "step_limit" | "retryable_error" | "stalled"; export interface GitLabAvailableModel { name?: string | null; ref?: string | null; } export interface GitLabAvailableModelsPayload { pinnedModel?: GitLabAvailableModel | null; selectedModel?: GitLabAvailableModel | null; defaultModel?: GitLabAvailableModel | null; selectableModels?: GitLabAvailableModel[] | null; } export const streamGitLabDuoWorkflow: StreamFunction<"gitlab-duo-agent"> = ( model: Model<"gitlab-duo-agent">, context: Context, options: GitLabDuoWorkflowOptions, ): AssistantMessageEventStream => { const stream = new AssistantMessageEventStream(); const output = createAssistantMessage(model); stream.push({ type: "start", partial: output }); const state: GitLabDuoWorkflowStreamState = { stream, output, started: true }; void runGitLabDuoWorkflow(model, context, options, state).catch(error => { const errorText = gitLabDuoWorkflowErrorText(error); if (!stream.done) { output.stopReason = "error"; // A throw (socket reject, abnormal 1006 close, …) on a goal already past the // byte budget is almost certainly the oversized request — surface it as a // context-overflow so the session auto-compacts rather than hard-failing. output.errorMessage = state.goalOverflowMessage ?? errorText; stream.push({ type: "error", reason: "error", error: output }); } }); return stream; }; export function buildGitLabDuoWorkflowDirectAccessBody( rootNamespaceId: string, projectId?: string, workflowDefinition: GitLabDuoWorkflowDefinition = GITLAB_DUO_WORKFLOW_DEFINITION, ): Record { return { workflow_definition: workflowDefinition, root_namespace_id: toGitLabGraphQLNamespaceId(rootNamespaceId), ...(projectId ? { project_id: projectId } : undefined), }; } export function buildGitLabDuoWorkflowCreateBody( namespaceId?: string, options: GitLabDuoWorkflowCreateBodyOptions = {}, ): Record { return { workflow_definition: options.workflowDefinition ?? GITLAB_DUO_WORKFLOW_DEFINITION, environment: "ide", allow_agent_to_request_user: false, agent_privileges: [6], pre_approved_agent_privileges: [6], requires_duo_cli_enabled: false, ...(namespaceId && !options.projectId ? { namespace_id: namespaceId } : undefined), ...(options.projectId ? { project_id: options.projectId } : undefined), ...(options.goal !== undefined ? { goal: options.goal } : { goal: "" }), }; } export function buildGitLabDuoWorkflowStopBody(): Record { return { status_event: "stop" }; } export function buildGitLabDuoWorkflowWebSocketUrl( baseUrl: string, options: { projectId?: string; namespaceId?: string; rootNamespaceId?: string; selectedModelIdentifier?: string; workflowDefinition?: GitLabDuoWorkflowDefinition; serviceEndpoint?: boolean; } = {}, ): string { // serviceEndpoint connects to the DWS runway host (root path); otherwise route to the // GitLab instance, preserving any relative install base path (e.g. `https://host/gitlab`). const wsUrl = options.serviceEndpoint ? new URL("/", normalizeGitLabBaseUrl(baseUrl)) : gitLabApiUrl(baseUrl, "/api/v4/ai/duo_workflows/ws"); wsUrl.protocol = wsUrl.protocol === "http:" ? "ws:" : "wss:"; if (options.projectId) wsUrl.searchParams.set("project_id", options.projectId); if (options.namespaceId && !options.serviceEndpoint) wsUrl.searchParams.set("namespace_id", toGitLabRestNamespaceId(options.namespaceId)); if (options.rootNamespaceId) wsUrl.searchParams.set("root_namespace_id", toGitLabRestNamespaceId(options.rootNamespaceId)); if (options.selectedModelIdentifier) wsUrl.searchParams.set("user_selected_model_identifier", options.selectedModelIdentifier); if (options.workflowDefinition) wsUrl.searchParams.set("workflow_definition", options.workflowDefinition); return wsUrl.toString(); } export function buildGitLabDuoWorkflowWebSocketHeaders(options: { token: string; baseUrl?: string; projectId?: string; namespaceId?: string; rootNamespaceId?: string; extraHeaders?: Record; }): Record { const base = new URL(normalizeGitLabBaseUrl(options.baseUrl ?? DEFAULT_GITLAB_BASE_URL)); return { ...options.extraHeaders, authorization: `Bearer ${options.token}`, "x-gitlab-client-type": GITLAB_DUO_WORKFLOW_CLIENT_TYPE, "x-gitlab-language-server-version": GITLAB_DUO_WORKFLOW_LANGUAGE_SERVER_VERSION, "user-agent": `unknown/unknown unknown/unknown gitlab-language-server/${GITLAB_DUO_WORKFLOW_LANGUAGE_SERVER_VERSION}`, origin: base.origin, ...(options.projectId ? { "x-gitlab-project-id": options.projectId } : {}), ...(options.namespaceId ? { "x-gitlab-namespace-id": toGitLabRestNamespaceId(options.namespaceId) } : {}), ...(options.rootNamespaceId ? { "x-gitlab-root-namespace-id": toGitLabRestNamespaceId(options.rootNamespaceId) } : {}), }; } export function buildGitLabDuoWorkflowStartRequest( workflowId: string, model: Model<"gitlab-duo-agent">, context: Context, tools: Tool[] | undefined = context.tools, availableModels?: GitLabAvailableModelsPayload | null, metadataOptions: GitLabDuoWorkflowStartMetadataOptions = {}, ): GitLabDuoWorkflowStartRequest { const workflowMetadata = buildGitLabDuoWorkflowStartMetadata(model, availableModels, metadataOptions); const mcpTools = buildGitLabDuoWorkflowMcpTools(tools); return { workflowID: workflowId, clientVersion: "1.0", workflowDefinition: metadataOptions.workflowDefinition ?? GITLAB_DUO_WORKFLOW_DEFINITION, goal: buildGitLabDuoWorkflowGoal(context), workflowMetadata: JSON.stringify(workflowMetadata), additional_context: buildGitLabDuoWorkflowClientAdditionalContext(), clientCapabilities: GITLAB_DUO_WORKFLOW_CLIENT_CAPABILITIES, mcpTools, preapproved_tools: mcpTools.map(tool => tool.name), flowConfigSchemaVersion: "v1" as const, flowConfig: buildGitLabDuoWorkflowInlineFlowConfig(buildGitLabDuoWorkflowSystemPrompt(context)), }; } // Build the inline ambient flow sent over the wire (Path B / `flowConfig`). The // server constructs the whole flow from this struct: a single agent component // whose system slot carries OMP's own authoritative system prompt (no GitLab jinja // wrapper / project metadata) and `on_agent_reasoning` so pre-tool-call commentary // streams back as reasoning. `toolset: []` because MCP tools auto-attach from // `startRequest.mcpTools` when the workflow's `mcp_enabled` is true. The user slot // is `{{goal}}`, which the provider fills with the flat conversation transcript. export function buildGitLabDuoWorkflowInlineFlowConfig(systemPrompt: string): GitLabDuoWorkflowInlineFlowConfig { return { version: "v1", environment: "ambient", flow: { entry_point: GITLAB_DUO_WORKFLOW_INLINE_AGENT_NAME }, components: [ { name: GITLAB_DUO_WORKFLOW_INLINE_AGENT_NAME, type: "AgentComponent", prompt_id: GITLAB_DUO_WORKFLOW_INLINE_PROMPT_ID, toolset: [], inputs: [{ from: "context:goal", as: "goal" }], ui_log_events: [...GITLAB_DUO_WORKFLOW_INLINE_UI_LOG_EVENTS], }, ], routers: [{ from: GITLAB_DUO_WORKFLOW_INLINE_AGENT_NAME, to: "end" }], prompts: [ { name: GITLAB_DUO_WORKFLOW_INLINE_PROMPT_ID, prompt_id: GITLAB_DUO_WORKFLOW_INLINE_PROMPT_ID, unit_primitives: ["duo_agent_platform"], prompt_template: { system: sanitizeGitLabDuoWorkflowFlowPrompt(systemPrompt), user: "{{goal}}", placeholder: "history", }, }, ], }; } const GITLAB_DUO_WORKFLOW_MARKDOWN_COMMENT = /(^|\\n|\n)\s*\[(?:\/\/|comment)\]:\s*(?:<[^>]*>|#|\S*)\s*\((?:[^)\\]|\\.)*\)/gi; // Python `\s` on `str` patterns also covers \x1c-\x1f and \x85; `re.IGNORECASE` folds ſ→s and ı/İ→i. const GITLAB_DUO_WORKFLOW_TAG_WS = String.raw`[\s\x1c-\x1f\x85]`; const GITLAB_DUO_WORKFLOW_DANGEROUS_TAGS = ["goal", "system", "truncated_tool_output", "truncation_notice"] as const; const GITLAB_DUO_WORKFLOW_TAG_PATTERNS = GITLAB_DUO_WORKFLOW_DANGEROUS_TAGS.map(tag => { const name = tag.replace(/s/g, "[sſ]").replace(/i/g, "[iıİ]"); return { tag, plain: new RegExp( String.raw`<${GITLAB_DUO_WORKFLOW_TAG_WS}*(\/?)${GITLAB_DUO_WORKFLOW_TAG_WS}*${name}${GITLAB_DUO_WORKFLOW_TAG_WS}*>`, "giu", ), escaped: new RegExp( String.raw`\\{1,2}u003c${GITLAB_DUO_WORKFLOW_TAG_WS}*(\/?)${GITLAB_DUO_WORKFLOW_TAG_WS}*${name}${GITLAB_DUO_WORKFLOW_TAG_WS}*\\{1,2}u003e`, "giu", ), }; }); /** * The Duo Workflow Service refuses an inline flow whose prompt text its * `flow_config_prompts` sanitizers would change (ai-assist * `duo_workflow_service/workflows/registry.py` runs `PromptSecurity` validate-only): * the WebSocket closes with 4400 "Flow configuration failed security validation". * The system prompt carries context files verbatim, so one HTML comment in an * AGENTS.md fails every request — and any `/g, "") .replace(/\\+u003c!--|