UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

234 lines • 7.61 kB
import { compileRuleCondition } from "./rule-condition.js"; export { compileRuleCondition } from "./rule-condition.js"; import { parse as parseYaml } from "yaml"; import { hasReachableScope, parseScope } from "./scope.js"; const FRONTMATTER_FENCE = "---"; const CLOSING_FENCE_PATTERN = "\n---"; const FALLBACK_KEY_VALUE = /^([\w-]+):\s*(.*)$/; const CONDITION_GLOB_SCOPE_TOOLS = ["edit", "write"]; const CATCH_ALL_CONDITION = ".*"; const REGEX_META_CHARS = /[\\^$+|()]/; const GLOB_META_CHARS = /[?*[\]{}]/; const EXTENSION_GLOB = /^\*\.[^\s/]+$/; function isRecord(value) { return value !== null && typeof value === "object" && !Array.isArray(value); } function parseFallbackFields(metadata) { const fields = {}; for (const line of metadata.split("\n")) { const match = FALLBACK_KEY_VALUE.exec(line); const key = match?.[1]; if (key === undefined) { continue; } const raw = (match?.[2] ?? "").trim(); if (raw.length === 0) { fields[key] = raw; continue; } try { const parsed = parseYaml(raw); if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) { fields[key] = parsed; } else { fields[key] = raw; } } catch { fields[key] = raw; } } return fields; } function parseFrontmatterFields(metadata) { try { const loaded = parseYaml(metadata); return isRecord(loaded) ? loaded : {}; } catch { return parseFallbackFields(metadata); } } function splitFrontmatter(markdown) { const normalized = markdown.replace(/\r\n?/g, "\n"); if (!normalized.startsWith(FRONTMATTER_FENCE)) { return { fields: {}, body: normalized }; } const endIndex = normalized.indexOf(CLOSING_FENCE_PATTERN, FRONTMATTER_FENCE.length); if (endIndex === -1) { return { fields: {}, body: normalized }; } const metadata = normalized.slice(FRONTMATTER_FENCE.length + 1, endIndex); const body = normalized.slice(endIndex + CLOSING_FENCE_PATTERN.length).trim(); return { fields: parseFrontmatterFields(metadata), body }; } function normalizeStringList(value) { if (typeof value === "string") { const token = value.trim(); return token.length > 0 ? [token] : undefined; } if (!Array.isArray(value)) { return undefined; } const tokens = value .filter((item) => typeof item === "string") .map((item) => item.trim()) .filter((item) => item.length > 0); if (tokens.length === 0) { return undefined; } return Array.from(new Set(tokens)); } function splitScopeTokens(value) { const tokens = []; let current = ""; let parenDepth = 0; let bracketDepth = 0; let braceDepth = 0; let quote; for (let index = 0; index < value.length; index++) { const char = value.charAt(index); if (quote !== undefined) { current += char; if (char === quote && value.charAt(index - 1) !== "\\") { quote = undefined; } continue; } if (char === '"' || char === "'") { quote = char; current += char; continue; } if (char === "(") { parenDepth += 1; } else if (char === ")") { parenDepth = Math.max(0, parenDepth - 1); } else if (char === "[") { bracketDepth += 1; } else if (char === "]") { bracketDepth = Math.max(0, bracketDepth - 1); } else if (char === "{") { braceDepth += 1; } else if (char === "}") { braceDepth = Math.max(0, braceDepth - 1); } else if (char === "," && parenDepth === 0 && bracketDepth === 0 && braceDepth === 0) { const token = current.trim(); if (token.length > 0) { tokens.push(token); } current = ""; continue; } current += char; } const tail = current.trim(); if (tail.length > 0) { tokens.push(tail); } return tokens; } function stripSurroundingQuotes(token) { const first = token.charAt(0); if (token.length >= 2 && (first === '"' || first === "'") && token.charAt(token.length - 1) === first) { return token.slice(1, -1).trim(); } return token; } function normalizeScopeField(value) { const normalized = normalizeStringList(value); if (normalized === undefined) { return undefined; } const tokens = normalized .flatMap(splitScopeTokens) .map(stripSurroundingQuotes) .filter((item) => item.length > 0); if (tokens.length === 0) { return undefined; } return Array.from(new Set(tokens)); } function isLikelyFileGlob(value) { const token = value.trim(); if (token.length === 0) { return false; } if (REGEX_META_CHARS.test(token)) { return false; } if (!GLOB_META_CHARS.test(token)) { return false; } if (token.includes("/")) { return true; } return EXTENSION_GLOB.test(token); } export function parseRuleFile(markdown, meta) { const { fields, body } = splitFrontmatter(markdown); const rawCondition = fields.condition ?? fields.ttsr_trigger ?? fields.ttsrTrigger; const parsedCondition = normalizeStringList(rawCondition); const parsedScope = normalizeScopeField(fields.scope); const inferredScopeTokens = []; const condition = []; for (const token of parsedCondition ?? []) { if (isLikelyFileGlob(token)) { for (const toolName of CONDITION_GLOB_SCOPE_TOOLS) { inferredScopeTokens.push(`tool:${toolName}(${token})`); } continue; } condition.push(token); } if (condition.length === 0 && inferredScopeTokens.length > 0) { condition.push(CATCH_ALL_CONDITION); } if (condition.length === 0) { return { skipped: true, name: meta.name, warning: `rule "${meta.name}" has no condition or legacy ttsr_trigger alias, skipping`, }; } for (const pattern of condition) { const compiled = compileRuleCondition(pattern); if (compiled.regex === null) { return { skipped: true, name: meta.name, warning: `rule "${meta.name}" skipped: ${compiled.warning ?? "invalid condition"}`, }; } } const scope = parseScope([...(parsedScope ?? []), ...inferredScopeTokens]); if (!hasReachableScope(scope)) { return { skipped: true, name: meta.name, warning: `rule "${meta.name}" scope excludes every stream, skipping`, }; } const description = typeof fields.description === "string" ? fields.description : undefined; const globs = normalizeStringList(fields.globs); const interruptMode = fields.interruptMode === "never" ? "never" : "always"; return { name: meta.name, ...(meta.path !== undefined ? { path: meta.path } : {}), content: body, ...(description !== undefined ? { description } : {}), ...(globs !== undefined ? { globs } : {}), condition: Array.from(new Set(condition)), scope, interruptMode, source: meta.source, }; } //# sourceMappingURL=rule-parser.js.map