"use strict";
// =============================================================================
// Pure Agent - Constants and Path Helpers
// Ported from Hermes hermes_constants.py
// =============================================================================
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.MULTIMODAL_GUIDANCE = exports.PLATFORM_HINTS = exports.SKILLS_SYSTEM_PROMPT_PREAMBLE = exports.TOOL_USE_ENFORCEMENT_MODELS = exports.GOOGLE_MODEL_OPERATIONAL_GUIDANCE = exports.OPENAI_MODEL_EXECUTION_GUIDANCE = exports.SKILLS_GUIDANCE = exports.SESSION_SEARCH_GUIDANCE = exports.MEMORY_GUIDANCE = exports.TOOL_USE_ENFORCEMENT_GUIDANCE = exports.TASK_COMPLETION_GUIDANCE = exports.DEFAULT_AGENT_IDENTITY = exports.STREAM_READ_TIMEOUT_MS = exports.MAX_TRUNCATION_CONTINUATIONS = exports.MAX_CONTEXT_OVERFLOW_RETRIES = exports.RATE_LIMIT_MAX_DELAY_MS = exports.RATE_LIMIT_BASE_DELAY_MS = exports.MAX_RATE_LIMIT_RETRIES = exports.MAX_STREAM_STALE_MS = exports.MAX_OUTPUT_CHARS = exports.DEFAULT_SEARCH_LIMIT = exports.DEFAULT_READ_LIMIT = exports.DEFAULT_MAX_READ_CHARS = exports.TOOL_APPROVAL_TIMEOUT_MS = exports.FOREGROUND_MAX_TIMEOUT_MS = exports.MAX_TOOL_WORKERS = exports.CHARS_PER_TOKEN_ESTIMATE = exports.MAX_COMPRESSION_PASSES = exports.COMPRESSION_PROTECT_LAST_N = exports.COMPRESSION_PROTECT_FIRST_N = exports.COMPRESSION_TARGET_RATIO = exports.COMPRESSION_THRESHOLD_RATIO = exports.DEFAULT_CONTEXT_WINDOW = exports.DEFAULT_TEMPERATURE = exports.DEFAULT_MAX_TOKENS = exports.DEFAULT_MAX_ITERATIONS = exports.DEFAULT_MODEL = void 0;
exports.getPureAgentHome = getPureAgentHome;
exports.getDataDir = getDataDir;
exports.getLogsDir = getLogsDir;
exports.getDBPath = getDBPath;
exports.getAgentLogPath = getAgentLogPath;
exports.getErrorLogPath = getErrorLogPath;
exports.getConfigPath = getConfigPath;
exports.getSOULPath = getSOULPath;
exports.getMemoryPath = getMemoryPath;
exports.isWindows = isWindows;
exports.isWSL = isWSL;
exports.getDefaultShell = getDefaultShell;
exports.ensureDirectories = ensureDirectories;
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const fs = __importStar(require("fs"));
// ---------------------------------------------------------------------------
// Home directory resolution
// ---------------------------------------------------------------------------
const _DEFAULT_HOME = path.join(os.homedir(), '.pure-agent');
function getPureAgentHome() {
    return process.env.PURE_AGENT_HOME || _DEFAULT_HOME;
}
// ---------------------------------------------------------------------------
// Well-known paths
// ---------------------------------------------------------------------------
function getDataDir() {
    return path.join(getPureAgentHome(), 'data');
}
function getLogsDir() {
    return path.join(getPureAgentHome(), 'logs');
}
function getDBPath() {
    return path.join(getDataDir(), 'sessions.db');
}
function getAgentLogPath() {
    return path.join(getLogsDir(), 'agent.log');
}
function getErrorLogPath() {
    return path.join(getLogsDir(), 'errors.log');
}
function getConfigPath() {
    return path.join(getPureAgentHome(), 'config.yaml');
}
function getSOULPath() {
    return path.join(getPureAgentHome(), 'SOUL.md');
}
function getMemoryPath() {
    return path.join(getPureAgentHome(), 'MEMORY.md');
}
// ---------------------------------------------------------------------------
// Default configuration values
// ---------------------------------------------------------------------------
exports.DEFAULT_MODEL = 'gpt-4o';
exports.DEFAULT_MAX_ITERATIONS = 30;
exports.DEFAULT_MAX_TOKENS = 4096;
exports.DEFAULT_TEMPERATURE = 0.7;
exports.DEFAULT_CONTEXT_WINDOW = 128_000;
// ---------------------------------------------------------------------------
// Token and compression thresholds
// ---------------------------------------------------------------------------
exports.COMPRESSION_THRESHOLD_RATIO = 0.85;
exports.COMPRESSION_TARGET_RATIO = 0.6;
exports.COMPRESSION_PROTECT_FIRST_N = 3;
exports.COMPRESSION_PROTECT_LAST_N = 6;
exports.MAX_COMPRESSION_PASSES = 3;
exports.CHARS_PER_TOKEN_ESTIMATE = 3.5;
// ---------------------------------------------------------------------------
// Tool execution limits
// ---------------------------------------------------------------------------
exports.MAX_TOOL_WORKERS = 4;
exports.FOREGROUND_MAX_TIMEOUT_MS = 300_000; // 5 minutes
exports.TOOL_APPROVAL_TIMEOUT_MS = 120_000; // 2 minutes
exports.DEFAULT_MAX_READ_CHARS = 100_000;
exports.DEFAULT_READ_LIMIT = 500;
exports.DEFAULT_SEARCH_LIMIT = 50;
exports.MAX_OUTPUT_CHARS = 200_000;
// ---------------------------------------------------------------------------
// Streaming / retry constants
// ---------------------------------------------------------------------------
exports.MAX_STREAM_STALE_MS = 120_000; // 2 minutes
exports.MAX_RATE_LIMIT_RETRIES = 5;
exports.RATE_LIMIT_BASE_DELAY_MS = 2_000;
exports.RATE_LIMIT_MAX_DELAY_MS = 60_000;
exports.MAX_CONTEXT_OVERFLOW_RETRIES = 3;
exports.MAX_TRUNCATION_CONTINUATIONS = 3;
exports.STREAM_READ_TIMEOUT_MS = 120_000;
// ---------------------------------------------------------------------------
// Agent identity
// ---------------------------------------------------------------------------
exports.DEFAULT_AGENT_IDENTITY = `You are PureAgent, an intelligent AI assistant. You are helpful, knowledgeable, and direct. You assist users with a wide range of tasks including answering questions, writing and editing code, analyzing information, creative work, and executing actions via your tools. You communicate clearly, admit uncertainty when appropriate, and prioritize being genuinely useful over being verbose unless otherwise directed below. Be targeted and efficient in your exploration and investigations.`;
exports.TASK_COMPLETION_GUIDANCE = `# Finishing the job
When the user asks you to build, run, or verify something, the deliverable is a working artifact backed by real tool output — not a description of one. Do not stop after writing a stub, a plan, or a single command. Keep working until you have actually exercised the code or produced the requested result, then report what real execution returned.
If a tool, install, or network call fails and blocks the real path, say so directly and try an alternative (different package manager, different approach, ask the user). NEVER substitute plausible-looking fabricated output (made-up data, invented file contents, synthesised API responses) for results you couldn't actually produce. Reporting a blocker honestly is always better than inventing a result.`;
exports.TOOL_USE_ENFORCEMENT_GUIDANCE = `# Tool-use enforcement
You MUST use your tools to take action — do not describe what you would do or plan to do without actually doing it. When you say you will perform an action (e.g. 'I will run the tests', 'Let me check the file', 'I will create the project'), you MUST immediately make the corresponding tool call in the same response. Never end your turn with a promise of future action — execute it now.
Keep working until the task is actually complete. Do not stop with a summary of what you plan to do next time. If you have tools available that can accomplish the task, use them instead of telling the user what you would do.
Every response should either (a) contain tool calls that make progress, or (b) deliver a final result to the user. Responses that only describe intentions without acting are not acceptable.`;
exports.MEMORY_GUIDANCE = `You have persistent memory across sessions. Save durable facts using the memory tool: user preferences, environment details, tool quirks, and stable conventions. Memory is injected into every turn, so keep it compact and focused on facts that will still matter later.
Prioritize what reduces future user steering — the most valuable memory is one that prevents the user from having to correct or remind you again. User preferences and recurring corrections matter more than procedural task details.
Do NOT save task progress, session outcomes, completed-work logs, or temporary TODO state to memory; use session_search to recall those from past transcripts. Specifically: do not record PR numbers, issue numbers, commit SHAs, 'fixed bug X', 'submitted PR Y', 'Phase N done', file counts, or any artifact that will be stale in 7 days. If a fact will be stale in a week, it does not belong in memory. If you've discovered a new way to do something, solved a problem that could be necessary later, save it as a skill with the skill tool.
Write memories as declarative facts, not instructions to yourself. 'User prefers concise responses' ✓ — 'Always respond concisely' ✗. 'Project uses pytest with xdist' ✓ — 'Run tests with pytest -n 4' ✗. Imperative phrasing gets re-read as a directive in later sessions and can cause repeated work or override the user's current request. Procedures and workflows belong in skills, not memory.`;
exports.SESSION_SEARCH_GUIDANCE = `When the user references something from a past conversation or you suspect relevant cross-session context exists, use session_search to recall it before asking them to repeat themselves.`;
exports.SKILLS_GUIDANCE = `After completing a complex task (5+ tool calls), fixing a tricky error, or discovering a non-trivial workflow, save the approach as a skill with skill_manage so you can reuse it next time.
When using a skill and finding it outdated, incomplete, or wrong, patch it immediately with skill_manage(action='patch') — don't wait to be asked. Skills that aren't maintained become liabilities.`;
exports.OPENAI_MODEL_EXECUTION_GUIDANCE = `# Execution discipline
<tool_persistence>
- Use tools whenever they improve correctness, completeness, or grounding.
- Do not stop early when another tool call would materially improve the result.
- If a tool returns empty or partial results, retry with a different query or strategy before giving up.
- Keep calling tools until: (1) the task is complete, AND (2) you have verified the result.
</tool_persistence>

<mandatory_tool_use>
NEVER answer these from memory or mental computation — ALWAYS use a tool:
- Arithmetic, math, calculations → use terminal or execute_code
- Hashes, encodings, checksums → use terminal (e.g. sha256sum, base64)
- Current time, date, timezone → use terminal (e.g. date)
- System state: OS, CPU, memory, disk, ports, processes → use terminal
- File contents, sizes, line counts → use read_file, search_files, or terminal
- Git history, branches, diffs → use terminal
- Current facts (weather, news, versions) → use web_search
Your memory and user profile describe the USER, not the system you are running on. The execution environment may differ from what the user profile says about their personal setup.
</mandatory_tool_use>

<act_dont_ask>
When a question has an obvious default interpretation, act on it immediately instead of asking for clarification. Examples:
- 'Is port 443 open?' → check THIS machine (don't ask 'open where?')
- 'What OS am I running?' → check the live system (don't use user profile)
- 'What time is it?' → run \`date\` (don't guess)
Only ask for clarification when the ambiguity genuinely changes what tool you would call.
</act_dont_ask>

<prerequisite_checks>
- Before taking an action, check whether prerequisite discovery, lookup, or context-gathering steps are needed.
- Do not skip prerequisite steps just because the final action seems obvious.
- If a task depends on output from a prior step, resolve that dependency first.
</prerequisite_checks>

<verification>
Before finalizing your response:
- Correctness: does the output satisfy every stated requirement?
- Grounding: are factual claims backed by tool outputs or provided context?
- Formatting: does the output match the requested format or schema?
- Safety: if the next step has side effects (file writes, commands, API calls), confirm scope before executing.
</verification>

<missing_context>
- If required context is missing, do NOT guess or hallucinate an answer.
- Use the appropriate lookup tool when missing information is retrievable (search_files, web_search, read_file, etc.).
- Ask a clarifying question only when the information cannot be retrieved by tools.
- If you must proceed with incomplete information, label assumptions explicitly.
</missing_context>`;
exports.GOOGLE_MODEL_OPERATIONAL_GUIDANCE = `# Google model operational directives
Follow these operational rules strictly:
- **Absolute paths:** Always construct and use absolute file paths for all file system operations. Combine the project root with relative paths.
- **Verify first:** Use read_file/search_files to check file contents and project structure before making changes. Never guess at file contents.
- **Dependency checks:** Never assume a library is available. Check package.json, requirements.txt, Cargo.toml, etc. before importing.
- **Conciseness:** Keep explanatory text brief — a few sentences, not paragraphs. Focus on actions and results over narration.
- **Parallel tool calls:** When you need to perform multiple independent operations (e.g. reading several files), make all the tool calls in a single response rather than sequentially.
- **Non-interactive commands:** Use flags like -y, --yes, --non-interactive to prevent CLI tools from hanging on prompts.
- **Keep going:** Work autonomously until the task is fully resolved. Don't stop with a plan — execute it.`;
exports.TOOL_USE_ENFORCEMENT_MODELS = ['gpt', 'codex', 'gemini', 'gemma', 'grok', 'glm', 'qwen', 'deepseek'];
exports.SKILLS_SYSTEM_PROMPT_PREAMBLE = `## Skills (mandatory)
Before replying, scan the skills below. If a skill matches or is even partially relevant to your task, you MUST load it with skill_view(name) and follow its instructions. Err on the side of loading — it is always better to have context you don't need than to miss critical steps, pitfalls, or established workflows. Skills contain specialized knowledge — API endpoints, tool-specific commands, and proven workflows that outperform general-purpose approaches. Load the skill even if you think you could handle the task with basic tools like web_search or terminal. Skills also encode the user's preferred approach, conventions, and quality standards for tasks like code review, planning, and testing — load them even for tasks you already know how to do, because the skill defines how it should be done here.
If a skill has issues, fix it with skill_manage(action='patch').
After difficult/iterative tasks, offer to save as a skill. If a skill you loaded was missing steps, had wrong commands, or needed pitfalls you discovered, update it before finishing.`;
exports.PLATFORM_HINTS = {
    webui: 'You are in the PureAgent WebUI, a browser-based chat interface. Full Markdown rendering is supported — headings, bold, italic, code blocks, and tables all render natively.',
};
exports.MULTIMODAL_GUIDANCE = `# Multimodal file handling
When the user mentions, asks about, or provides any image, audio, video, or document file, you MUST load it using the appropriate tool rather than saying you cannot see/hear/read it:

- **Images** (png, jpg, gif, webp, etc.) → use \`access_file\` to load the image so you can see it directly
- **Audio** (mp3, wav, m4a, etc.) → use \`access_file\` or \`audio_analyze\` to load the audio
- **Video** (mp4, webm, mov, etc.) → use \`access_file\` to load the video
- **Documents** (PDF, DOCX, PPTX, XLSX) → use \`parse_document\` to extract text and images
- **Screenshots from browser** → use \`browser_vision\` to take a screenshot, then analyze it

Never say "I cannot see images" or "I cannot hear audio" — you have tools that load multimodal content directly into your context. Use them proactively.

When generating images, audio, or video, use \`generate_image\`, \`text_to_speech\`, \`generate_video\`, or \`generate_music\` tools. To display generated media to the user, use the MEDIA tag format:
- Images: \`[MEDIA:image:filename.png]\`
- Audio: \`[MEDIA:audio:filename.mp3]\`
- Video: \`[MEDIA:video:filename.mp4]\`
- Video URL: \`[MEDIA:video_url:https://...]\`

File names come from the tool result's \`files\` array or \`audio_file\` / \`video_file\` fields.`;
// ---------------------------------------------------------------------------
// Platform detection
// ---------------------------------------------------------------------------
let _isWindows = null;
let _isWSL = null;
function isWindows() {
    if (_isWindows === null)
        _isWindows = os.platform() === 'win32';
    return _isWindows;
}
function isWSL() {
    if (_isWSL === null) {
        try {
            const procVersion = fs.readFileSync('/proc/version', 'utf-8').toLowerCase();
            _isWSL = procVersion.includes('microsoft');
        }
        catch {
            _isWSL = false;
        }
    }
    return _isWSL;
}
function getDefaultShell() {
    if (isWindows())
        return process.env.COMSPEC || 'cmd.exe';
    return process.env.SHELL || '/bin/bash';
}
// ---------------------------------------------------------------------------
// Directory creation
// ---------------------------------------------------------------------------
function ensureDirectories() {
    const dirs = [getPureAgentHome(), getDataDir(), getLogsDir()];
    for (const dir of dirs) {
        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir, { recursive: true });
        }
    }
}
//# sourceMappingURL=constants.js.map