UNPKG

@code-yeongyu/senpi

Version:

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

273 lines • 12.2 kB
import { existsSync, readFileSync, realpathSync } from "node:fs"; import { homedir } from "node:os"; import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; import { CONFIG_DIR_NAME, getAgentDir } from "../../../../config.js"; import { PROJECT_RULES_END_MARKER, PROJECT_RULES_HEADING, PROJECT_RULES_REGION_END_MARKER, PROJECT_RULES_REGION_START_MARKER, PROJECT_RULES_START_MARKER, } from "../rules/rules/constants.js"; import { sdkModelId } from "./context-window.js"; import { presetAppendDeprecationGuidance } from "./guidance.js"; import { claudeCodeQueryEnvironment } from "./query-environment.js"; import { requireAnthropicSubscriptionCwd } from "./session-cwd.js"; import { loadAnthropicSubscriptionProviderSettingsFromDisk, resolveCompactionOwner, resolveSystemPromptMode, } from "./settings.js"; import { loadOverrideSystemPrompt, resolveCustomSystemPrompt } from "./system-prompt.js"; import { BUILTIN_SDK_TOOLS, canUseTool, HOST_TOOL_DENIAL_HOOKS } from "./tools.js"; const ADAPTIVE_THINKING_MODEL_MARKERS = [ "opus-4-6", "opus-4.6", "opus-4-7", "opus-4.7", "opus-4-8", "opus-4.8", "opus-5", "sonnet-4-6", "sonnet-4.6", "sonnet-5", "fable-5", "mythos-5", ]; const NATIVE_XHIGH_EFFORT_MODEL_MARKERS = [ "opus-4-7", "opus-4-8", "opus-5", "sonnet-5", "fable-5", "mythos-5", ]; const DEFAULT_THINKING_BUDGETS = { minimal: 2048, low: 8192, medium: 16384, high: 31999, max: 63999, }; function includesModelMarker(model, markers) { const id = model.id.toLowerCase(); return markers.some((marker) => id.includes(marker)); } function forcedAdaptiveThinking(model) { const compat = model.compat; if (!compat || !("forceAdaptiveThinking" in compat)) return undefined; return typeof compat.forceAdaptiveThinking === "boolean" ? compat.forceAdaptiveThinking : undefined; } function supportsAdaptiveThinking(model) { return forcedAdaptiveThinking(model) ?? includesModelMarker(model, ADAPTIVE_THINKING_MODEL_MARKERS); } function supportsNativeXhighEffort(model) { return includesModelMarker(model, NATIVE_XHIGH_EFFORT_MODEL_MARKERS); } function isEffortLevel(value) { return value === "low" || value === "medium" || value === "high" || value === "xhigh" || value === "max"; } function mapThinkingLevelToEffort(model, level) { const mapped = model.thinkingLevelMap?.[level]; if (typeof mapped === "string" && isEffortLevel(mapped)) return mapped; switch (level) { case "minimal": case "low": return "low"; case "medium": return "medium"; case "high": return "high"; case "xhigh": return supportsNativeXhighEffort(model) ? "xhigh" : "max"; case "max": return "max"; } } function mapThinkingTokens(reasoning, thinkingBudgets) { const budgetLevel = reasoning === "xhigh" ? "high" : reasoning; const customBudget = thinkingBudgets?.[budgetLevel]; return typeof customBudget === "number" && Number.isFinite(customBudget) && customBudget > 0 ? customBudget : DEFAULT_THINKING_BUDGETS[budgetLevel]; } function findAgentsMdInParents(cwd) { let current = resolve(cwd); while (true) { const candidate = join(current, "AGENTS.md"); if (existsSync(candidate)) return candidate; const parent = dirname(current); if (parent === current) return undefined; current = parent; } } function sanitizeAgentsContent(content) { const configDirectory = CONFIG_DIR_NAME.replace(/^\./, ""); const escapedConfigDirectory = configDirectory.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); return content .replace(new RegExp(`~/${escapedConfigDirectory}\\b`, "gi"), "~/.claude") .replace(new RegExp(`(^|[\\s'"\`])\\.${escapedConfigDirectory}/`, "g"), "$1.claude/") .replace(new RegExp(`\\b${escapedConfigDirectory}\\b`, "gi"), "environment"); } function extractAgentsAppend(cwd) { const agentsPath = findAgentsMdInParents(cwd) ?? join(getAgentDir(), "AGENTS.md"); if (!existsSync(agentsPath)) return undefined; try { const content = sanitizeAgentsContent(readFileSync(agentsPath, "utf-8").trim()); return content.length > 0 ? `# CLAUDE.md\n\n${content}` : undefined; } catch { return undefined; } } function claudeSkillsPath(path, cwd) { const targets = [ [join(getAgentDir(), "skills"), "~/.claude/skills"], [join(cwd, CONFIG_DIR_NAME, "skills"), ".claude/skills"], ]; for (const [root, claudeRoot] of targets) { const inside = relative(root, path); if (inside !== "" && (/^\.\.(?:[\\/]|$)/.test(inside) || isAbsolute(inside))) continue; const candidate = inside === "" ? claudeRoot : `${claudeRoot}/${inside.split(sep).join("/")}`; return resolvesToSameFile(candidate, path, cwd, homedir()) ? candidate : path; } return path; } function expandDisplayPath(candidate, cwd, home) { if (candidate === "~") return home; if (candidate.startsWith("~/")) return join(home, candidate.slice(2)); return isAbsolute(candidate) ? candidate : resolve(cwd, candidate); } function resolvesToSameFile(candidate, path, cwd, home) { try { return realpathSync(expandDisplayPath(candidate, cwd, home)) === realpathSync(expandDisplayPath(path, cwd, home)); } catch { return false; } } // The catalog names each skill root once in `<skill_roots>` and locates skills by `rN/` alias, so the roots carry the // paths; a catalog without that table carries absolute `<location>` paths instead. function rewriteSkillsLocations(skillsBlock, cwd) { const withRoots = skillsBlock.replace(/<skill_roots>[\s\S]*?<\/skill_roots>/, (table) => table.replace(/<(r\d+)>([^<]+)<\/\1>/g, (_match, alias, root) => { return `<${alias}>${claudeSkillsPath(root, cwd)}</${alias}>`; })); return withRoots.replace(/<location>([^<]+)<\/location>/g, (_match, location) => { return `<location>${claudeSkillsPath(location, cwd)}</location>`; }); } function extractSkillsAppend(systemPrompt, cwd) { if (!systemPrompt) return undefined; const marker = "The following skills provide specialized instructions for specific tasks."; const start = systemPrompt.indexOf(marker); const end = start === -1 ? -1 : systemPrompt.indexOf("</available_skills>", start); if (end === -1) return undefined; return rewriteSkillsLocations(systemPrompt.slice(start, end + "</available_skills>".length).trim(), cwd); } /** * This lane rebuilds the prompt from the `claude_code` preset plus `append`, so any * region of senpi's composed prompt without an extractor here never reaches the model. * * Located by the rules builtin's opaque region sentinels rather than the model-facing * `<project_rules>` tags, which surrounding prompt content may legitimately contain. * The sentinels are a reserved wire literal but nothing neutralizes them outside the block, so * each candidate is structurally validated and rejected candidates are skipped - otherwise a * context file carrying one would shadow the real block or cross-match its end sentinel. * Fail-closed on a missing end sentinel: never read to end-of-string, or the sections * extensions append after this one get relabelled as project rules. */ function extractProjectRulesAppend(systemPrompt) { if (!systemPrompt) return undefined; let searchFrom = 0; while (searchFrom <= systemPrompt.length) { const sentinelStart = systemPrompt.indexOf(PROJECT_RULES_REGION_START_MARKER, searchFrom); if (sentinelStart === -1) return undefined; const regionStart = sentinelStart + PROJECT_RULES_REGION_START_MARKER.length; const regionEnd = systemPrompt.indexOf(PROJECT_RULES_REGION_END_MARKER, regionStart); if (regionEnd === -1) return undefined; const region = systemPrompt.slice(regionStart, regionEnd).trim(); if (isProjectRulesEnvelope(region)) return region; searchFrom = regionStart; } return undefined; } function isProjectRulesEnvelope(region) { return (region.startsWith(`${PROJECT_RULES_START_MARKER}\n${PROJECT_RULES_HEADING}\n`) && region.endsWith(`\n${PROJECT_RULES_END_MARKER}`)); } function resolveSettingSources(providerSettings, mode, authLane) { if (providerSettings.settingSources !== undefined) return [...providerSettings.settingSources]; if (mode !== "preset-append" || authLane !== "ambient") return []; return ["user", "project"]; } export function buildAnthropicSubscriptionQueryOptions(input) { const cwd = requireAnthropicSubscriptionCwd(input.cwd); const providerSettings = input.providerSettings ?? loadAnthropicSubscriptionProviderSettingsFromDisk(cwd); const appendSystemPrompt = providerSettings.appendSystemPrompt !== false; const resolvedMode = resolveSystemPromptMode(providerSettings); const mode = resolvedMode.mode; if (input.sessionId !== undefined && input.onGuidance !== undefined) { const deprecation = presetAppendDeprecationGuidance({ mode, conflict: resolvedMode.conflict, sessionId: input.sessionId, }); if (deprecation !== undefined) input.onGuidance(deprecation); } const authLane = input.authLane ?? providerSettings.tokenInjection ?? "ambient"; const append = mode === "preset-append" ? [ extractAgentsAppend(cwd), extractSkillsAppend(input.context.systemPrompt, cwd), extractProjectRulesAppend(input.context.systemPrompt), ].filter((part) => part !== undefined) : []; const systemPrompt = mode === "preset-append" ? { type: "preset", preset: "claude_code", append: append.join("\n\n") || undefined } : mode === "override" ? loadOverrideSystemPrompt(providerSettings.systemPromptFile) : resolveCustomSystemPrompt(input.context.systemPrompt); const toolLessRequest = input.streamOptions?.toolChoice === "none"; const emptyToolContext = (input.context.tools?.length ?? 0) === 0; const strictMcpConfig = toolLessRequest || (providerSettings.strictMcpConfig ?? !appendSystemPrompt); const senpiOwnsCompaction = resolveCompactionOwner(providerSettings) === "senpi"; const queryOptions = { cwd, model: sdkModelId(input.model), tools: toolLessRequest || emptyToolContext ? [] : input.tools ? [...input.tools] : [...BUILTIN_SDK_TOOLS], permissionMode: "dontAsk", includePartialMessages: true, canUseTool, hooks: HOST_TOOL_DENIAL_HOOKS, systemPrompt, // Exactly one compaction owner: senpi by default, so Claude Code's native auto-compact is off // (senpi's overflow recovery covers the hard limit); `compactionOwner: "sdk"` hands it back. // configFingerprint hashes `settings`, so an owner change restarts the resident process. settings: { autoCompactEnabled: !senpiOwnsCompaction }, settingSources: resolveSettingSources(providerSettings, mode, authLane), }; queryOptions.env = claudeCodeQueryEnvironment(input.model, senpiOwnsCompaction); if (input.pathToClaudeCodeExecutable) queryOptions.pathToClaudeCodeExecutable = input.pathToClaudeCodeExecutable; if (toolLessRequest) queryOptions.maxTurns = 1; if (strictMcpConfig) queryOptions.extraArgs = { "strict-mcp-config": null }; const reasoning = input.streamOptions?.reasoning; if (reasoning && supportsAdaptiveThinking(input.model)) { queryOptions.thinking = { type: "adaptive", display: "summarized" }; queryOptions.effort = mapThinkingLevelToEffort(input.model, reasoning); } else if (reasoning) { queryOptions.maxThinkingTokens = mapThinkingTokens(reasoning, input.streamOptions?.thinkingBudgets); } return queryOptions; } //# sourceMappingURL=options.js.map