"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildSystemMessage = buildSystemMessage;
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const instructionFiles_1 = require("../utils/main/instructionFiles");
const markdown_1 = require("../utils/main/markdown");
// NOTE: keep this in sync with the docs/models.md file
// The PRELUDE is intentionally minimal to not conflict with the user's instructions.
// cmux is designed to be model agnostic, and models have shown large inconsistency in how they
// follow instructions.
const PRELUDE = ` 
<prelude>
You are a coding agent.
  
<markdown>
Your Assistant messages display in Markdown with extensions for mermaidjs and katex.

When creating mermaid diagrams:
- Avoid side-by-side subgraphs (they display too wide)
- For comparisons, use separate diagram blocks or single graph with visual separation
- When using custom fill colors, include contrasting color property (e.g., "style note fill:#ff6b6b,color:#fff")
- Make good use of visual space: e.g. use inline commentary
- Wrap node labels containing brackets or special characters in quotes (e.g., Display["Message[]"] not Display[Message[]])

Use GitHub-style \`<details>/<summary>\` tags to create collapsible sections for lengthy content, error traces, or supplementary information. Toggles help keep responses scannable while preserving detail.
</markdown>
</prelude>
`;
/**
 * Build environment context XML block describing the workspace.
 */
function buildEnvironmentContext(workspacePath) {
    return `
<environment>
You are in a git worktree at ${workspacePath}

- This IS a git repository - run git commands directly (no cd needed)
- Tools run here automatically
- Do not modify or visit other worktrees (especially the main project) without explicit user intent
- You are meant to do your work isolated from the user and other agents
</environment>
`;
}
/**
 * Get the system directory where global cmux configuration lives.
 * Users can place global AGENTS.md and .cmux/PLAN.md files here.
 */
function getSystemDirectory() {
    return path.join(os.homedir(), ".cmux");
}
/**
 * Builds a system message for the AI model by combining instruction sources.
 *
 * Instruction layers:
 * 1. Global: ~/.cmux/AGENTS.md (always included)
 * 2. Context: workspace/AGENTS.md OR project/AGENTS.md (workspace takes precedence)
 * 3. Mode: Extracts "Mode: <mode>" section from context then global (if mode provided)
 *
 * File search order: AGENTS.md → AGENT.md → CLAUDE.md
 * Local variants: AGENTS.local.md appended if found (for .gitignored personal preferences)
 *
 * @param metadata - Workspace metadata (contains projectPath)
 * @param runtime - Runtime for reading workspace files (supports SSH)
 * @param workspacePath - Workspace directory path
 * @param mode - Optional mode name (e.g., "plan", "exec")
 * @param additionalSystemInstructions - Optional instructions appended last
 * @throws Error if metadata or workspacePath invalid
 */
async function buildSystemMessage(metadata, runtime, workspacePath, mode, additionalSystemInstructions) {
    if (!metadata)
        throw new Error("Invalid workspace metadata: metadata is required");
    if (!workspacePath)
        throw new Error("Invalid workspace path: workspacePath is required");
    // Read instruction sets
    const globalInstructions = await (0, instructionFiles_1.readInstructionSet)(getSystemDirectory());
    const workspaceInstructions = await (0, instructionFiles_1.readInstructionSetFromRuntime)(runtime, workspacePath);
    const contextInstructions = workspaceInstructions ?? (await (0, instructionFiles_1.readInstructionSet)(metadata.projectPath));
    // Combine: global + context (workspace takes precedence over project)
    const customInstructions = [globalInstructions, contextInstructions].filter(Boolean).join("\n\n");
    // Extract mode-specific section (context first, then global fallback)
    let modeContent = null;
    if (mode) {
        modeContent =
            (contextInstructions && (0, markdown_1.extractModeSection)(contextInstructions, mode)) ??
                (globalInstructions && (0, markdown_1.extractModeSection)(globalInstructions, mode)) ??
                null;
    }
    // Build system message
    let systemMessage = `${PRELUDE.trim()}\n\n${buildEnvironmentContext(workspacePath)}`;
    if (customInstructions) {
        systemMessage += `\n<custom-instructions>\n${customInstructions}\n</custom-instructions>`;
    }
    if (modeContent) {
        const tag = (mode ?? "mode").toLowerCase().replace(/[^a-z0-9_-]/gi, "-");
        systemMessage += `\n\n<${tag}>\n${modeContent}\n</${tag}>`;
    }
    if (additionalSystemInstructions) {
        systemMessage += `\n\n<additional-instructions>\n${additionalSystemInstructions}\n</additional-instructions>`;
    }
    return systemMessage;
}
//# sourceMappingURL=systemMessage.js.map