import { randomUUID } from "node:crypto"; import { readFile } from "node:fs/promises"; import { resolve } from "node:path"; import Mustache from "mustache"; import YAML from "yaml"; import { matchesSlashPattern, matchesRelativeScriptPattern, normalizeRelativeScriptPattern, validateMcpPattern, } from "./tool-policy.js"; export interface AgentModelConfig { provider: string; name: string; temperature?: number; maxTokens?: number; contextWindow?: number; } export interface AgentLimitsConfig { maxSteps?: number; timeout?: number; } export interface CronJobConfig { schedule: string; task: string; timezone?: string; channel?: string; maxRuns?: number; } export interface AgentFrontmatter { name: string; id?: string; description?: string; model?: AgentModelConfig; limits?: AgentLimitsConfig; allowedTools?: { mcp?: string[]; scripts?: string[]; }; approvalRequired?: { mcp?: string[]; scripts?: string[]; }; compaction?: CompactionConfig; cron?: Record; } export interface CompactionConfig { enabled: boolean; trigger: number; /** * Primary retention unit: number of whole recent *turns* (a user message plus * the assistant/tool messages that follow it) preserved verbatim after the * summary. See `findSafeSplitPointByTurns`. */ keepRecentTurns: number; /** * Fallback retention floor, in messages, used only for the single-giant-turn * case where no turn boundary yields a safe split. */ keepRecentMessages: number; instructions?: string; } export interface ParsedAgent { frontmatter: AgentFrontmatter; body: string; } export interface RuntimeRenderContext { parameters?: Record; runtime?: { workingDir?: string; agentId?: string; runId?: string; environment?: string; }; } const FRONTMATTER_PATTERN = /^---\s*\n([\s\S]*?)\n---\s*\n?([\s\S]*)$/; const asRecord = (value: unknown): Record => typeof value === "object" && value !== null ? (value as Record) : {}; const asNumberOrUndefined = (value: unknown): number | undefined => typeof value === "number" ? value : undefined; const CRON_EXPRESSION_PATTERN = /^(\S+\s+){4}\S+$/; const validateCronExpression = (expr: string, path: string): void => { if (!CRON_EXPRESSION_PATTERN.test(expr.trim())) { throw new Error( `Invalid cron expression at ${path}: "${expr}". Expected 5-field cron format (minute hour day month weekday).`, ); } }; const validateTimezone = (tz: string, path: string): void => { // Delegate to the runtime's Intl resolver rather than checking against // `Intl.supportedValuesOf("timeZone")`. The latter returns only canonical // IANA names (e.g. "Etc/UTC") and rejects common aliases like "UTC" and // "GMT", even though `Intl.DateTimeFormat` accepts them everywhere. try { new Intl.DateTimeFormat("en", { timeZone: tz }); } catch { throw new Error( `Invalid timezone at ${path}: "${tz}". Expected an IANA timezone string (e.g. "America/New_York", "UTC").`, ); } }; const parseCronJobs = ( value: unknown, ): Record | undefined => { const raw = asRecord(value); const keys = Object.keys(raw); if (keys.length === 0) return undefined; const jobs: Record = {}; for (const jobName of keys) { const jobValue = asRecord(raw[jobName]); const path = `AGENT.md frontmatter cron.${jobName}`; if (typeof jobValue.schedule !== "string" || jobValue.schedule.trim() === "") { throw new Error( `Invalid ${path}: "schedule" is required and must be a non-empty string.`, ); } if (typeof jobValue.task !== "string" || jobValue.task.trim() === "") { throw new Error( `Invalid ${path}: "task" is required and must be a non-empty string.`, ); } validateCronExpression(jobValue.schedule, path); const timezone = typeof jobValue.timezone === "string" && jobValue.timezone.trim() ? jobValue.timezone.trim() : undefined; if (timezone) { validateTimezone(timezone, path); } const channel = typeof jobValue.channel === "string" && jobValue.channel.trim() ? jobValue.channel.trim() : undefined; const maxRuns = typeof jobValue.maxRuns === "number" && jobValue.maxRuns > 0 ? Math.max(1, Math.floor(jobValue.maxRuns)) : undefined; jobs[jobName] = { schedule: jobValue.schedule.trim(), task: jobValue.task, timezone, channel, maxRuns, }; } return jobs; }; export const parseAgentMarkdown = (content: string): ParsedAgent => { const match = content.match(FRONTMATTER_PATTERN); if (!match) { throw new Error( "Invalid AGENT.md: expected YAML frontmatter wrapped in --- markers.", ); } const parsedYaml = YAML.parse(match[1]) ?? {}; const parsed = asRecord(parsedYaml); if (typeof parsed.name !== "string" || parsed.name.trim() === "") { throw new Error("Invalid AGENT.md: frontmatter requires a non-empty `name`."); } const KNOWN_PROVIDERS = new Set(["anthropic", "openai", "openai-codex"]); const splitProviderPrefix = (raw: string): { provider?: string; name: string } => { const slashIdx = raw.indexOf("/"); if (slashIdx > 0) { const prefix = raw.slice(0, slashIdx).toLowerCase(); if (KNOWN_PROVIDERS.has(prefix)) { return { provider: prefix, name: raw.slice(slashIdx + 1) }; } } return { name: raw }; }; const modelValue: Record = (() => { if (typeof parsed.model === "string") { const { provider, name } = splitProviderPrefix(parsed.model); return provider ? { provider, name } : { name }; } const rec = asRecord(parsed.model); if (typeof rec.name === "string") { const { provider, name } = splitProviderPrefix(rec.name); rec.name = name; if (provider && typeof rec.provider !== "string") { rec.provider = provider; } } return rec; })(); const limitsValue = asRecord(parsed.limits); const parseTools = ( key: "allowed-tools" | "approval-required", ): { mcp: string[]; scripts: string[] } => { const entries = Array.isArray(parsed[key]) ? parsed[key].filter((item): item is string => typeof item === "string") : []; const mcp: string[] = []; const scripts: string[] = []; for (const [index, entry] of entries.entries()) { if (entry.startsWith("mcp:")) { const withoutPrefix = entry.slice(4); validateMcpPattern(withoutPrefix, `AGENT.md frontmatter ${key}[${index}]`); mcp.push(withoutPrefix); continue; } scripts.push( normalizeRelativeScriptPattern(entry, `AGENT.md frontmatter ${key}[${index}]`), ); } return { mcp, scripts }; }; const allowedTools = parseTools("allowed-tools"); const approvalRequired = parseTools("approval-required"); for (const pattern of approvalRequired.mcp) { const matchesAllowed = allowedTools.mcp.some((allowedPattern) => matchesSlashPattern(pattern, allowedPattern), ); if (!matchesAllowed) { throw new Error( `Invalid AGENT.md frontmatter approval-required: MCP pattern "${pattern}" must be included in allowed-tools.`, ); } } for (const pattern of approvalRequired.scripts) { if (pattern.startsWith("./scripts/")) { continue; } const matchesAllowed = allowedTools.scripts.some((allowedPattern) => matchesRelativeScriptPattern(pattern, allowedPattern), ); if (!matchesAllowed) { throw new Error( `Invalid AGENT.md frontmatter approval-required: script pattern "${pattern}" must be included in allowed-tools when outside ./scripts/.`, ); } } const frontmatter: AgentFrontmatter = { name: parsed.name, id: typeof parsed.id === "string" && parsed.id.trim() ? parsed.id.trim() : undefined, description: typeof parsed.description === "string" ? parsed.description : undefined, model: Object.keys(modelValue).length > 0 ? { provider: typeof modelValue.provider === "string" ? modelValue.provider : "anthropic", name: typeof modelValue.name === "string" ? modelValue.name : "claude-opus-4-5", temperature: asNumberOrUndefined(modelValue.temperature), maxTokens: asNumberOrUndefined(modelValue.maxTokens), } : undefined, limits: Object.keys(limitsValue).length > 0 ? { maxSteps: asNumberOrUndefined(limitsValue.maxSteps), timeout: asNumberOrUndefined(limitsValue.timeout), } : undefined, allowedTools: allowedTools.mcp.length > 0 || allowedTools.scripts.length > 0 ? { mcp: allowedTools.mcp.length > 0 ? allowedTools.mcp : undefined, scripts: allowedTools.scripts.length > 0 ? allowedTools.scripts : undefined, } : undefined, approvalRequired: approvalRequired.mcp.length > 0 || approvalRequired.scripts.length > 0 ? { mcp: approvalRequired.mcp.length > 0 ? approvalRequired.mcp : undefined, scripts: approvalRequired.scripts.length > 0 ? approvalRequired.scripts : undefined, } : undefined, compaction: (() => { const raw = asRecord(parsed.compaction); if (Object.keys(raw).length === 0) return undefined; const enabled = raw.enabled !== false; const trigger = typeof raw.trigger === "number" ? raw.trigger : 0.80; if (trigger < 0.1 || trigger > 1) { throw new Error( "Invalid AGENT.md frontmatter compaction.trigger: must be between 0.1 and 1.", ); } const keepRecentTurns = typeof raw.keepRecentTurns === "number" ? Math.max(1, Math.floor(raw.keepRecentTurns)) : 4; const keepRecentMessages = typeof raw.keepRecentMessages === "number" ? Math.max(2, Math.floor(raw.keepRecentMessages)) : 6; const instructions = typeof raw.instructions === "string" && raw.instructions.trim() ? raw.instructions.trim() : undefined; return { enabled, trigger, keepRecentTurns, keepRecentMessages, instructions }; })(), cron: parseCronJobs(parsed.cron), }; return { frontmatter, body: match[2].trim(), }; }; export const parseAgentFile = async (workingDir: string): Promise => { const filePath = resolve(workingDir, "AGENT.md"); const content = await readFile(filePath, "utf8"); return parseAgentMarkdown(content); }; export const renderAgentPrompt = ( agent: ParsedAgent, context: RuntimeRenderContext = {}, ): string => { const renderContext = { name: agent.frontmatter.name, description: agent.frontmatter.description ?? "", runtime: { workingDir: context.runtime?.workingDir ?? process.cwd(), agentId: context.runtime?.agentId ?? agent.frontmatter.id ?? agent.frontmatter.name, runId: context.runtime?.runId ?? `run_${randomUUID()}`, environment: context.runtime?.environment ?? "development", }, parameters: context.parameters ?? {}, }; return Mustache.render(agent.body, renderContext).trim(); };