@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
2,132 lines • 90.9 kB
JavaScript
import { DEFAULT_MAX_AGENT_RETRY_DELAY_MS, LEGACY_PROVIDER_IDS, normalizeModelRef, normalizeProviderId, readByProviderId, } from "@earendil-works/pi-ai";
import { SENPI_DEFAULT_RETRY_PROFILE } from "@earendil-works/pi-ai/utils/retry-profile/profiles";
import { createHash, randomUUID } from "crypto";
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "fs";
import { mkdir, readFile, rename, rm, writeFile } from "fs/promises";
import { homedir } from "os";
import { dirname, join } from "path";
import lockfile from "proper-lockfile";
import { isDeepStrictEqual } from "util";
import { CONFIG_DIR_NAME, getAgentDir } from "../config.js";
import { findNearestParentConfigDir } from "../nearest-parent-config.js";
import { normalizePath, resolvePath } from "../utils/paths.js";
import { envValue } from "./brand.js";
import { compactionEnabled, compactionKeepRecentTokens, compactionReserveTokens, } from "./compaction-settings-access.js";
import { resolveCompactionSettings } from "./compaction-settings-resolver.js";
import { MAX_ENGINE_TURNS_PER_RESUME_WINDOW, MAX_ENGINE_TURNS_PER_USER_INPUT, MAX_TOOL_FREE_ENGINE_TURNS_PER_WINDOW, } from "./engine-turn-limit.js";
import { lockWithLossHandling } from "./file-lock.js";
import { DEFAULT_HTTP_IDLE_TIMEOUT_MS, parseHttpIdleTimeoutMs } from "./http-dispatcher.js";
import { CredentialStoreBusyError, FILE_STORAGE_LOCK_OPTIONS, FILE_STORAGE_LOCK_RETRY_BUDGET_MS, FILE_STORAGE_LOCK_RETRY_MAX_DELAY_MS, FILE_STORAGE_LOCK_RETRY_MIN_DELAY_MS, FILE_STORAGE_SYNC_LOCK_BUDGET_MS, isLockError, } from "./lockfile-policy.js";
import { resolveFallbackCircuitSettings, } from "./retry-fallback/circuit.js";
import { validateRetryProviderOverrides } from "./retry-fallback/profile-override.js";
import { resolveAbortServerSideFallback, resolveHintPolicySettings, resolveRetryFallbackSettings, } from "./retry-fallback/settings.js";
import { parseSettingsJson } from "./settings-json.js";
import { withoutOverride } from "./settings-overrides.js";
import { removeRetiredSettingsKeys, writeRawScopedSettings } from "./settings-retired-keys.js";
import { ASK_USER_DEFAULT_TIMEOUT_MINUTES, ASK_USER_MAX_TIMEOUT_MINUTES, ASK_USER_MIN_TIMEOUT_MINUTES, JOB_WIDGETS_DEFAULT_AUTHOR_AFTER_MS, } from "./settings-shapes.js";
import { logStateError, migrateSettingsState, parseStateSettings, readSettingsState, STATE_KEYS, } from "./settings-state.js";
import { isTerminalMouseMode, } from "./terminal-settings.js";
export const DEFAULT_STREAM_START_TIMEOUT_MS = 300_000;
export const DEFAULT_PROVIDER_STREAM_RETRY_TIMEOUT_MS = 30_000;
/**
* How long keep-alive bytes alone may hold a provider request without content (senpi#4608). Longer than any
* first-token latency observed through relays (a few minutes) and than Anthropic's 10-minute ceiling for a
* non-streaming request, well short of the 60-minute turn inactivity lease.
*/
const DEFAULT_STREAM_KEEP_ALIVE_TIMEOUT_MS = 900_000;
/** Warn threshold for a single `session_shutdown` extension handler. */
export const DEFAULT_SESSION_SHUTDOWN_HANDLER_WARN_MS = 2_000;
/**
* Hard cap for a single `session_shutdown` extension handler. Higher than the
* 2s warning because several extensions persist durable state at shutdown; a
* hung handler still must not hold quit/reload/new/resume hostage.
*/
export const DEFAULT_SESSION_SHUTDOWN_HANDLER_TIMEOUT_MS = 10_000;
/**
* Total wait across every `session_shutdown` handler when the process quits (senpi#3711). Above the OmO memory
* extension's own 1500 ms shutdown drain, whose first step flushes the memory journal.
*/
export const DEFAULT_SESSION_SHUTDOWN_QUIT_BUDGET_MS = 2_000;
/** Warn threshold for one handler of an agent lifecycle event the session awaits before persisting (senpi#3650). */
export const DEFAULT_EXTENSION_EVENT_HANDLER_WARN_MS = 60_000;
/**
* Hard cap for one such handler. Above the 15 min summarization budget a blocking compaction in a `message_end`
* handler may legitimately use; past it the host stops waiting so the turn is persisted and queued input delivered.
*/
export const DEFAULT_EXTENSION_EVENT_HANDLER_TIMEOUT_MS = 1_200_000;
const THINKING_LEVEL_VALUES = new Set([
"off",
"minimal",
"low",
"medium",
"high",
"xhigh",
"max",
]);
const MODEL_SERVICE_TIER_VALUES = new Set(["auto", "flex", "priority"]);
/** Opaque per-model memory key. Ids may contain `/` and `:`, so keys are never split back apart. */
function modelMemoryKey(provider, modelId) {
return `${provider}/${modelId}`;
}
function readModelMemoryEntry(map, key, allowed) {
if (typeof map !== "object" || map === null || Array.isArray(map))
return undefined;
const value = map[key];
return typeof value === "string" && allowed.has(value) ? value : undefined;
}
function isMergeableObject(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function deepMergeObjects(base, overrides) {
const result = { ...base };
for (const key of Object.keys(overrides)) {
const overrideValue = overrides[key];
if (overrideValue === undefined) {
continue;
}
const baseValue = base[key];
result[key] =
isMergeableObject(baseValue) && isMergeableObject(overrideValue)
? deepMergeObjects(baseValue, overrideValue)
: overrideValue;
}
return result;
}
/** Tools enabled at startup when `defaultTools` does not change them (the fork default includes `grep`). */
export const DEFAULT_TOOL_NAMES = ["read", "bash", "edit", "write", "grep"];
function isToolModifier(entry) {
return typeof entry === "string" && (entry.startsWith("+") || entry.startsWith("-"));
}
/**
* Merge `defaultTools` of two settings layers. A list with plain tool names replaces the inherited
* one; a list of only `+name`/`-name` entries is appended, so it modifies the inherited selection.
*/
function mergeDefaultTools(base, overrides) {
if (overrides === undefined)
return base;
// Settings files are not validated; a malformed value replaces instead of throwing here.
if (!Array.isArray(base) || !Array.isArray(overrides) || !overrides.every(isToolModifier))
return overrides;
return [...base, ...overrides];
}
/**
* Resolve a merged `defaultTools` list: plain names replace `DEFAULT_TOOL_NAMES`, then `+name` adds
* and `-name` removes a tool, in list order.
*/
function resolveDefaultTools(entries) {
const plain = entries.filter((entry) => !isToolModifier(entry));
const tools = plain.length > 0 || entries.length === 0 ? plain : [...DEFAULT_TOOL_NAMES];
for (const entry of entries) {
if (!isToolModifier(entry))
continue;
const name = entry.slice(1);
const index = tools.indexOf(name);
if (entry.startsWith("+") && index === -1 && name)
tools.push(name);
else if (entry.startsWith("-") && index !== -1)
tools.splice(index, 1);
}
return tools;
}
/** Deep merge settings: project/overrides take precedence, nested objects merge recursively */
function deepMergeSettings(base, overrides) {
const merged = deepMergeObjects(base, overrides);
if (overrides.retry?.fallbackChains !== undefined) {
merged.retry = {
...merged.retry,
fallbackChains: structuredClone(overrides.retry.fallbackChains),
};
}
const defaultTools = mergeDefaultTools(base.defaultTools, overrides.defaultTools);
return defaultTools === undefined ? merged : { ...merged, defaultTools };
}
function resolveAskUserTimeoutMinutes(value) {
if (typeof value !== "number" || !Number.isFinite(value)) {
return ASK_USER_DEFAULT_TIMEOUT_MINUTES;
}
return Math.min(ASK_USER_MAX_TIMEOUT_MINUTES, Math.max(ASK_USER_MIN_TIMEOUT_MINUTES, Math.floor(value)));
}
function parseTimeoutSetting(value, settingName) {
const timeoutMs = parseHttpIdleTimeoutMs(value);
if (timeoutMs !== undefined) {
return timeoutMs;
}
if (value !== undefined) {
throw new Error(`Invalid ${settingName} setting: ${String(value)}`);
}
return undefined;
}
export { parseSettingsJson };
const SELF_WRITE_TTL_MS = 15_000;
const MAX_SELF_WRITES_PER_PATH = 8;
const selfWritesByPath = new Map();
let selfWriteClock = Date.now;
function recordSelfWrite(absPath, content) {
const now = selfWriteClock();
const writes = selfWritesByPath.get(absPath) ?? new Map();
for (const [hash, recordedAt] of writes) {
if (now - recordedAt > SELF_WRITE_TTL_MS) {
writes.delete(hash);
}
}
const hash = createHash("sha256").update(content).digest("hex");
writes.delete(hash);
writes.set(hash, now);
while (writes.size > MAX_SELF_WRITES_PER_PATH) {
const oldestHash = writes.keys().next().value;
if (oldestHash === undefined) {
break;
}
writes.delete(oldestHash);
}
selfWritesByPath.set(absPath, writes);
}
/**
* Returns whether a settings content hash was recently written by this process.
* A matching entry is consumed so a later identical external edit is not suppressed.
*/
export function wasSelfWrite(absPath, hash) {
const writes = selfWritesByPath.get(absPath);
if (!writes) {
return false;
}
const now = selfWriteClock();
for (const [trackedHash, recordedAt] of writes) {
if (now - recordedAt > SELF_WRITE_TTL_MS) {
writes.delete(trackedHash);
}
}
if (!writes.delete(hash)) {
if (writes.size === 0) {
selfWritesByPath.delete(absPath);
}
return false;
}
if (writes.size === 0) {
selfWritesByPath.delete(absPath);
}
return true;
}
/** Test-only hook for isolating process-wide self-write tracker state. */
export function __resetSelfWriteTrackerForTests() {
selfWritesByPath.clear();
}
/** Test-only hook for deterministically advancing the self-write tracker clock. */
export function __setSelfWriteTrackerClockForTests(clock = undefined) {
selfWriteClock = clock ?? Date.now;
}
function getSettingsDirectory(cwd, agentDir, scope, homeDir) {
if (scope === "global")
return resolvePath(agentDir);
const resolvedCwd = resolvePath(cwd);
return findNearestParentConfigDir(resolvedCwd, homeDir, CONFIG_DIR_NAME) ?? join(resolvedCwd, CONFIG_DIR_NAME);
}
/** Resolve the existing settings source, preferring JSONC when both formats exist. */
export function resolveSettingsSource(cwd, agentDir, scope, homeDir = homedir()) {
const directory = getSettingsDirectory(cwd, agentDir, scope, homeDir);
const jsoncPath = join(directory, "settings.jsonc");
if (existsSync(jsoncPath)) {
return {
path: jsoncPath,
format: "jsonc",
reason: "explicit-jsonc",
scope,
};
}
const jsonPath = join(directory, "settings.json");
if (existsSync(jsonPath)) {
return { path: jsonPath, format: "json", reason: "json-only", scope };
}
return undefined;
}
/** Returns the selected settings path, or the legacy JSON write target when no source exists. */
export function getSettingsPath(cwd, agentDir, scope, homeDir = homedir()) {
return (resolveSettingsSource(cwd, agentDir, scope, homeDir)?.path ??
join(getSettingsDirectory(cwd, agentDir, scope, homeDir), "settings.json"));
}
/** Returns the stable virtual path used to identify in-memory settings storage writes. */
export function getInMemorySettingsPath(scope) {
return scope === "global" ? "/__senpi_in_memory__/settings.json" : "/__senpi_in_memory__/.senpi/settings.json";
}
function toSettingsError(scope, error, path) {
return {
scope,
...(path ? { path } : {}),
error: error instanceof Error ? error : new Error(String(error)),
};
}
class SettingsLockBusy extends Error {
}
export class FileSettingsStorage {
constructor(cwd, agentDir, homeDir = homedir()) {
this.cwd = cwd;
this.agentDir = agentDir;
this.homeDir = homeDir;
this.globalSettingsPath = getSettingsPath(cwd, agentDir, "global", homeDir);
this.projectSettingsPath = getSettingsPath(cwd, agentDir, "project", homeDir);
}
selectSource(scope) {
const source = resolveSettingsSource(this.cwd, this.agentDir, scope, this.homeDir);
const path = source?.path ?? join(getSettingsDirectory(this.cwd, this.agentDir, scope, this.homeDir), "settings.json");
if (scope === "global")
this.globalSettingsPath = path;
else
this.projectSettingsPath = path;
return source;
}
tryAcquireLockSync(path) {
try {
return lockfile.lockSync(path, { ...FILE_STORAGE_LOCK_OPTIONS, retries: 0 });
}
catch (error) {
if (isLockError(error))
throw new SettingsLockBusy();
throw error;
}
}
acquireLockSyncWithRetry(path) {
const startedAt = Date.now();
let attempt = 0;
while (true) {
try {
return lockfile.lockSync(path, { ...FILE_STORAGE_LOCK_OPTIONS, retries: 0 });
}
catch (error) {
if (!isLockError(error))
throw error;
const waitedMs = Date.now() - startedAt;
if (waitedMs >= FILE_STORAGE_SYNC_LOCK_BUDGET_MS) {
throw new CredentialStoreBusyError(path, waitedMs, error);
}
const delayMs = Math.min(FILE_STORAGE_LOCK_RETRY_MIN_DELAY_MS * 2 ** attempt, FILE_STORAGE_LOCK_RETRY_MAX_DELAY_MS, FILE_STORAGE_SYNC_LOCK_BUDGET_MS - waitedMs);
attempt++;
const sleeper = new Int32Array(new SharedArrayBuffer(4));
Atomics.wait(sleeper, 0, 0, delayMs);
}
}
}
async acquireLockWithRetry(path) {
const startedAt = Date.now();
let attempt = 0;
while (true) {
try {
return await lockWithLossHandling(path, { ...FILE_STORAGE_LOCK_OPTIONS, retries: 0 });
}
catch (error) {
if (!isLockError(error))
throw error;
const waitedMs = Date.now() - startedAt;
if (waitedMs >= FILE_STORAGE_LOCK_RETRY_BUDGET_MS) {
throw new CredentialStoreBusyError(path, waitedMs, error);
}
const delayMs = Math.min(FILE_STORAGE_LOCK_RETRY_MIN_DELAY_MS * 2 ** attempt, FILE_STORAGE_LOCK_RETRY_MAX_DELAY_MS, FILE_STORAGE_LOCK_RETRY_BUDGET_MS - waitedMs);
attempt++;
await new Promise((resolve) => setTimeout(resolve, delayMs));
}
}
}
/**
* `withLock` for queued saves. Waiting on a busy lock used `Atomics.wait` on the UI thread: a
* settings write per turn (tip history) froze typing for up to a second whenever the lock was
* held elsewhere. The protocol is unchanged: lock-free read, merge, re-merge under the lock if
* another writer won, then publish through a same-directory temp file and rename.
*/
async withLockAsync(scope, fn, underLock) {
const path = scope === "global" ? this.globalSettingsPath : this.projectSettingsPath;
return this.withPathLockAsync(path, fn, underLock);
}
withStateLockAsync(fn) {
return this.withPathLockAsync(join(resolvePath(this.agentDir), "state.json"), fn);
}
async withPathLockAsync(path, fn, underLock) {
const readCurrent = async () => {
try {
return await readFile(path, "utf-8");
}
catch (error) {
if (error.code === "ENOENT")
return undefined;
throw error;
}
};
const current = await readCurrent();
let next = fn(current);
if (next === undefined)
return;
await mkdir(dirname(path), { recursive: true });
const lock = await this.acquireLockWithRetry(path);
try {
// The wait may have outlived the caller's permission to write (e.g. project trust revoked).
underLock?.();
const lockedContent = await readCurrent();
if (lockedContent !== current)
next = fn(lockedContent);
if (next !== undefined) {
const tempPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
try {
await writeFile(tempPath, next, "utf-8");
lock.assertHeld();
await rename(tempPath, path);
// After the rename: a failed publish must not mark identical content as our own write.
recordSelfWrite(path, next);
}
catch (error) {
await rm(tempPath, { force: true });
throw error;
}
}
}
finally {
await lock.release();
}
}
tryWithLock(scope, fn) {
try {
this.withLock(scope, fn, false);
return true;
}
catch (error) {
if (error instanceof SettingsLockBusy)
return false;
throw error;
}
}
withLock(scope, fn, waitForLock = true) {
const path = scope === "global" ? this.globalSettingsPath : this.projectSettingsPath;
this.withPathLock(path, fn, waitForLock);
}
withStateLock(fn) {
this.withPathLock(join(resolvePath(this.agentDir), "state.json"), fn);
}
tryWithStateLock(fn) {
try {
this.withPathLock(join(resolvePath(this.agentDir), "state.json"), fn, false);
return true;
}
catch (error) {
if (error instanceof SettingsLockBusy)
return false;
throw error;
}
}
withPathLock(path, fn, waitForLock = true) {
const dir = dirname(path);
// Read without the lock: writers publish atomically via temp+rename below, so
// a reader can never observe partial content. Read-only callers therefore skip
// lock acquisition entirely (no lock churn, no lock-dir filesystem events).
const current = existsSync(path) ? readFileSync(path, "utf-8") : undefined;
let next = fn(current);
if (next === undefined) {
return;
}
// Only create directory when we actually need to write
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true });
}
const release = waitForLock ? this.acquireLockSyncWithRetry(path) : this.tryAcquireLockSync(path);
try {
const underLock = existsSync(path) ? readFileSync(path, "utf-8") : undefined;
if (underLock !== current) {
// Lost a write race: re-merge against the winner's content under the lock.
next = fn(underLock);
}
if (next !== undefined) {
// Publish atomically: write a same-directory temp file, then rename over
// the settings path so lock-free readers never see a torn write.
const tempPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
try {
writeFileSync(tempPath, next, "utf-8");
recordSelfWrite(path, next);
renameSync(tempPath, path);
}
catch (error) {
rmSync(tempPath, { force: true });
throw error;
}
}
}
finally {
release();
}
}
}
export class InMemorySettingsStorage {
withStateLock(fn) {
const next = fn(this.state);
if (next !== undefined)
this.state = next;
}
withLock(scope, fn) {
const current = scope === "global" ? this.global : this.project;
const next = fn(current);
if (next !== undefined) {
if (scope === "global") {
this.global = next;
}
else {
this.project = next;
}
recordSelfWrite(getInMemorySettingsPath(scope), next);
}
}
}
export class SettingsManager {
constructor(storage, initialGlobal, initialProject, globalLoadError = null, projectLoadError = null, initialErrors = [], projectTrusted = true, initialSources = [], settingsPaths = {}) {
/** CLI/SDK overrides (`applyOverrides`): never persisted, re-applied on every recompute. */
this.runtimeOverrides = {};
this.modifiedFields = new Set(); // Track global fields modified during session
this.modifiedNestedFields = new Map(); // Track global nested field modifications
this.modifiedProjectFields = new Set(); // Track project fields modified during session
this.modifiedProjectNestedFields = new Map(); // Track project nested field modifications
this.globalSettingsLoadError = null; // Track if global settings file had parse errors
this.projectSettingsLoadError = null; // Track if project settings file had parse errors
this.writeQueue = Promise.resolve();
this.selectedSources = new Map();
this.sourceListeners = [];
this.providerSettingsListeners = new Set();
this.projectTrustLocked = false;
/**
* True when this session's project trust came only from its Full access preset (never asked, never
* saved): leaving Full access withdraws it, and going back restores it (senpi#3414, #3420).
*/
this.trustFromFullAccess = false;
/** Counts project-trust changes; a reload compares it before installing what it loaded (#3420). */
this.trustEpoch = 0;
this.storage = storage;
this.globalSettings = initialGlobal;
this.projectSettings = initialProject;
this.projectTrusted = projectTrusted;
this.globalSettingsLoadError = globalLoadError;
this.projectSettingsLoadError = projectLoadError;
this.errors = [...initialErrors];
this.settingsPaths = settingsPaths;
for (const source of initialSources)
this.selectedSources.set(source.scope, source);
this.settings = deepMergeSettings(this.globalSettings, this.projectSettings);
}
/** Create a SettingsManager that loads from files */
static create(cwd, agentDir = getAgentDir(), options = {}) {
const storage = new FileSettingsStorage(cwd, agentDir);
return SettingsManager.fromStorage(storage, options);
}
/** Create a SettingsManager from an arbitrary storage backend */
static fromStorage(storage, options = {}) {
const projectTrusted = options.projectTrusted ?? true;
const initialSources = [];
const settingsPaths = {};
const globalSource = storage.selectSource?.("global");
if (globalSource) {
initialSources.push(globalSource);
settingsPaths.global = globalSource.path;
}
const globalLoad = SettingsManager.tryLoadFromStorage(storage, "global");
const projectSource = projectTrusted ? storage.selectSource?.("project") : undefined;
if (projectSource) {
initialSources.push(projectSource);
settingsPaths.project = projectSource.path;
}
const projectLoad = SettingsManager.tryLoadFromStorage(storage, "project", projectTrusted);
const initialErrors = [];
if (globalLoad.error) {
initialErrors.push(toSettingsError("global", globalLoad.error, settingsPaths.global));
}
if (projectLoad.error) {
initialErrors.push(toSettingsError("project", projectLoad.error, settingsPaths.project));
}
const manager = new SettingsManager(storage, globalLoad.settings, projectLoad.settings, globalLoad.error, projectLoad.error, initialErrors, projectTrusted, initialSources, settingsPaths);
manager.trustFromFullAccess = options.trustFromFullAccess === true;
manager.projectTrustLocked = options.projectTrustLocked === true;
return manager;
}
/** Create an in-memory SettingsManager (no file I/O) */
static inMemory(settings = {}, options = {}) {
const storage = new InMemorySettingsStorage();
const initialSettings = SettingsManager.migrateSettings(structuredClone(settings));
storage.withLock("global", () => JSON.stringify(initialSettings, null, 2));
return SettingsManager.fromStorage(storage, options);
}
static loadFromStorage(storage, scope, projectTrusted = true) {
if (scope === "project" && !projectTrusted) {
return {};
}
let content;
storage.withLock(scope, (current) => {
content = current;
return undefined;
});
const raw = content ? parseSettingsJson(content) : {};
// A project file belongs to the user's repository: its retired keys are ignored, never rewritten.
if (removeRetiredSettingsKeys(raw) && scope === "global")
writeRawScopedSettings(storage, scope);
if (scope === "global" && storage.withStateLock) {
// TODO(PR #3213 follow-up: state-fallback-removal): remove config fallback after the first migration release.
if ([...STATE_KEYS].some((key) => Object.hasOwn(raw, key)))
migrateSettingsState(storage);
Object.assign(raw, readSettingsState(storage));
}
return SettingsManager.migrateSettings(raw);
}
static tryLoadFromStorage(storage, scope, projectTrusted = true) {
try {
return {
settings: SettingsManager.loadFromStorage(storage, scope, projectTrusted),
error: null,
};
}
catch (error) {
return { settings: {}, error: error };
}
}
/** Migrate old settings format to new format */
static migrateSettings(settings) {
// Migrate queueMode -> steeringMode
if ("queueMode" in settings && !("steeringMode" in settings)) {
settings.steeringMode = settings.queueMode;
delete settings.queueMode;
}
// Migrate legacy websockets boolean -> transport enum
if (!("transport" in settings) && typeof settings.websockets === "boolean") {
settings.transport = settings.websockets ? "websocket" : "sse";
delete settings.websockets;
}
// Migrate old skills object format to new array format
if ("skills" in settings &&
typeof settings.skills === "object" &&
settings.skills !== null &&
!Array.isArray(settings.skills)) {
const skillsSettings = settings.skills;
if (skillsSettings.enableSkillCommands !== undefined && settings.enableSkillCommands === undefined) {
settings.enableSkillCommands = skillsSettings.enableSkillCommands;
}
if (Array.isArray(skillsSettings.customDirectories) && skillsSettings.customDirectories.length > 0) {
settings.skills = skillsSettings.customDirectories;
}
else {
delete settings.skills;
}
}
// Migrate retry.maxDelayMs -> retry.provider.maxRetryDelayMs
if ("retry" in settings &&
typeof settings.retry === "object" &&
settings.retry !== null &&
!Array.isArray(settings.retry)) {
const retrySettings = settings.retry;
const providerSettings = typeof retrySettings.provider === "object" && retrySettings.provider !== null
? retrySettings.provider
: undefined;
if (typeof retrySettings.maxDelayMs === "number" &&
(providerSettings?.maxRetryDelayMs === undefined || providerSettings?.maxRetryDelayMs === null)) {
retrySettings.provider = {
...(providerSettings ?? {}),
maxRetryDelayMs: retrySettings.maxDelayMs,
};
}
delete retrySettings.maxDelayMs;
}
// Migrate renamed subscription provider ids (senpi#1989) in place, on first
// parse: the settings block key, defaultProvider, the provider prefix of
// defaultModel, favoriteModels, the `${provider}/${id}` keys of the model
// maps, and retry.fallbackChains keys + the providers named inside rungs.
// Idempotent (normalize is a no-op on canonical ids) and never hard-errors:
// an unrecognised shape is left untouched.
SettingsManager.migrateRenamedProviderIds(settings);
return settings;
}
/** camelCase provider-settings block key, e.g. `claude-sdk-oauth` -> `claudeSdkOauthProvider`. */
static providerSettingsKey(providerId) {
const camel = providerId
.split("-")
.map((part, i) => (i === 0 ? part : part.charAt(0).toUpperCase() + part.slice(1)))
.join("");
return `${camel}Provider`;
}
static migrateRenamedProviderIds(settings) {
// settings block key: <legacyCamel>Provider -> <canonicalCamel>Provider
for (const [legacyId, canonicalId] of Object.entries(LEGACY_PROVIDER_IDS)) {
const legacyKey = SettingsManager.providerSettingsKey(legacyId);
const canonicalKey = SettingsManager.providerSettingsKey(canonicalId);
if (legacyKey in settings && !(canonicalKey in settings)) {
settings[canonicalKey] = settings[legacyKey];
delete settings[legacyKey];
}
}
if (typeof settings.defaultProvider === "string") {
settings.defaultProvider = normalizeProviderId(settings.defaultProvider);
}
if (typeof settings.defaultModel === "string") {
settings.defaultModel = normalizeModelRef(settings.defaultModel);
}
if (Array.isArray(settings.favoriteModels)) {
settings.favoriteModels = settings.favoriteModels.map((entry) => typeof entry === "string" ? normalizeModelRef(entry) : entry);
}
for (const field of ["modelThinkingLevels", "modelServiceTiers", "modelLastOnThinkingLevels"]) {
const map = settings[field];
if (typeof map === "object" && map !== null && !Array.isArray(map)) {
settings[field] = SettingsManager.rekeyByModelRef(map);
}
}
if (typeof settings.retry === "object" && settings.retry !== null && !Array.isArray(settings.retry)) {
const retry = settings.retry;
const chains = retry.fallbackChains;
if (typeof chains === "object" && chains !== null && !Array.isArray(chains)) {
const rekeyed = {};
for (const [key, rungs] of Object.entries(chains)) {
const nextRungs = Array.isArray(rungs)
? rungs.map((rung) => (typeof rung === "string" ? normalizeModelRef(rung) : rung))
: rungs;
rekeyed[normalizeModelRef(key)] = nextRungs;
}
retry.fallbackChains = rekeyed;
}
}
}
/** Rewrite every `${provider}/${id}` key of a model map through normalizeModelRef. */
static rekeyByModelRef(map) {
const out = {};
for (const [key, value] of Object.entries(map))
out[normalizeModelRef(key)] = value;
return out;
}
/** A copy of the effective settings: global and project settings merged, with overrides. */
getSettings() {
return structuredClone(this.settings);
}
getGlobalSettings() {
return structuredClone(this.globalSettings);
}
getProjectSettings() {
return structuredClone(this.projectSettings);
}
/**
* `contextFiles.globalPath` from the user's own layers only: session overrides, then global
* settings. A project's `.senpi/settings.json` never redirects the user's global context file
* (senpi#5567), so the project layer is deliberately skipped.
*/
getGlobalContextFilePath() {
return this.runtimeOverrides.contextFiles?.globalPath ?? this.globalSettings.contextFiles?.globalPath;
}
/** The project settings file at `path` as stored: parsed and migrated like a load, but never gated by trust. */
readProjectSettingsFile(path) {
let content;
try {
this.storage.withLock("project", (current) => {
content = current;
return undefined;
});
if (content === undefined)
return { path, exists: false, settings: null, error: null };
return {
path,
exists: true,
settings: SettingsManager.migrateSettings(parseSettingsJson(content)),
error: null,
};
}
catch (error) {
return { path, exists: content !== undefined, settings: null, error: String(error) };
}
}
/**
* Writes one top-level key of the project settings file (`null` removes it) through the same trusted-only,
* locked, merge-on-write path every project setter uses. Refuses a file that failed to load: that path skips
* the write silently, which an explicit caller must not mistake for success.
*/
async setProjectSetting(key, value) {
this.assertProjectTrustedForWrite();
if (this.projectSettingsLoadError) {
throw new Error(`Project settings file could not be read; refusing to write: ${this.projectSettingsLoadError.message}`);
}
const field = key;
const recordedBefore = new Set(this.errors);
this.updateProjectSettings(field, (settings) => {
if (value === null)
delete settings[field];
else
settings[key] = value;
});
await this.flush();
// The queued write records its failure instead of throwing; an explicit caller is told.
const failure = this.errors.find((entry) => entry.scope === "project" && !recordedBefore.has(entry));
if (failure)
throw failure.error;
}
getProviderSettings() {
return structuredClone(this.settings.providers ?? {});
}
getProviderConcurrencyLimit(providerId) {
// Read boundary (senpi#1989): a `providers` block written by an earlier
// version is keyed by the legacy provider id, so try the canonical key
// first and then the legacy spelling instead of silently detaching the
// user's configured limit.
const value = readByProviderId(this.settings.providers, providerId)?.maxConcurrency;
return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : Infinity;
}
subscribeToProviderSettings(listener) {
this.providerSettingsListeners.add(listener);
return () => this.providerSettingsListeners.delete(listener);
}
updateSettings(settings) {
this.settings = settings;
for (const listener of this.providerSettingsListeners)
listener();
}
getPromptCacheGoalBackstopMaxSeconds() {
return (this.projectSettings.promptCache?.goalBackstopMaxSeconds ??
this.globalSettings.promptCache?.goalBackstopMaxSeconds ??
270);
}
getPromptCacheSessionAffinity() {
return this.settings.promptCache?.sessionAffinity ?? true;
}
getPromptCacheKeepAliveSettings() {
const configured = this.settings.promptCache?.keepAlive;
return {
enabled: configured?.enabled ?? false,
maxRequestsPerSession: configured?.maxRequestsPerSession ?? 3,
maxCostUsdPerSession: configured?.maxCostUsdPerSession ?? 0.05,
marginSeconds: configured?.marginSeconds ?? 60,
};
}
getAskUserSettings() {
const configured = this.settings.askUser;
return {
enabled: typeof configured?.enabled === "boolean" ? configured.enabled : true,
timeoutMinutes: resolveAskUserTimeoutMinutes(configured?.timeoutMinutes),
bell: typeof configured?.bell === "boolean" ? configured.bell : true,
};
}
getJobWidgetsSettings() {
const configured = this.settings.jobWidgets;
const model = typeof configured?.model === "string" ? configured.model.trim() : "";
const after = configured?.authorAfterMs;
return {
enabled: typeof configured?.enabled === "boolean" ? configured.enabled : true,
model: model.length > 0 ? model : undefined,
authorAfterMs: typeof after === "number" && Number.isFinite(after) && after >= 0
? Math.trunc(after)
: JOB_WIDGETS_DEFAULT_AUTHOR_AFTER_MS,
};
}
getEngineTurnSettings() {
const configured = this.settings.engineTurns;
const limit = (value, fallback) => typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : fallback;
return {
maxPerUserInput: limit(configured?.maxPerUserInput, MAX_ENGINE_TURNS_PER_USER_INPUT),
maxPerResumeWindow: limit(configured?.maxPerResumeWindow, MAX_ENGINE_TURNS_PER_RESUME_WINDOW),
maxToolFreePerMinute: limit(configured?.maxToolFreePerMinute, MAX_TOOL_FREE_ENGINE_TURNS_PER_WINDOW),
};
}
getTurnInactivityMs() {
return this.settings.turn_inactivity_ms;
}
getTurnMaxRuntimeMs() {
return this.settings.turn_max_runtime_ms;
}
/** The user's thread chain count limit (`threads.chainCountLimit`, K8): a non-negative integer, else unlimited. */
getThreadChainCountLimit() {
const configured = this.settings.threads?.chainCountLimit;
return typeof configured === "number" && Number.isSafeInteger(configured) && configured >= 0
? configured
: undefined;
}
/** The user's `todo.firstTurnPlan`, else `fallback`: the default the active prompt preset declares. */
getTodoFirstTurnPlan(fallback = "force") {
const configured = this.settings.todo?.firstTurnPlan;
return configured === "force" || configured === "remind" || configured === "off" ? configured : fallback;
}
getTodoTurnEndBackstop() {
const configured = this.settings.todo?.turnEndBackstop;
return typeof configured === "boolean" ? configured : true;
}
isProjectTrusted() {
return this.projectTrusted;
}
/** True when the launch named the project trust explicitly; a trust decision saved in the session cannot apply. */
isProjectTrustLocked() {
return this.projectTrustLocked;
}
isTrustFromFullAccess() {
return this.trustFromFullAccess && this.projectTrusted;
}
/** True when a Full-access-only trust was withdrawn in this session and Full access may restore it. */
canRestoreFullAccessTrust() {
return this.trustFromFullAccess && !this.projectTrusted;
}
getTrustEpoch() {
return this.trustEpoch;
}
setProjectTrusted(trusted) {
if (this.projectTrusted === trusted) {
return;
}
this.projectTrusted = trusted;
this.trustEpoch += 1;
this.modifiedProjectFields.clear();
this.modifiedProjectNestedFields.clear();
if (!trusted) {
this.projectSettings = {};
this.projectSettingsLoadError = null;
this.updateSettings(this.mergedSettings());
return;
}
this.selectAndPublishSource("project");
const projectLoad = SettingsManager.tryLoadFromStorage(this.storage, "project", trusted);
this.projectSettings = projectLoad.settings;
this.projectSettingsLoadError = projectLoad.error;
if (projectLoad.error) {
this.recordError("project", projectLoad.error);
}
this.updateSettings(this.mergedSettings());
}
async reload() {
await this.writeQueue;
this.selectAndPublishSource("global");
const globalLoad = SettingsManager.tryLoadFromStorage(this.storage, "global");
if (!globalLoad.error) {
this.globalSettings = globalLoad.settings;
this.globalSettingsLoadError = null;
}
else {
this.globalSettingsLoadError = globalLoad.error;
this.recordError("global", globalLoad.error);
}
this.modifiedFields.clear();
this.modifiedNestedFields.clear();
this.modifiedProjectFields.clear();
this.modifiedProjectNestedFields.clear();
if (this.projectTrusted)
this.selectAndPublishSource("project");
const projectLoad = SettingsManager.tryLoadFromStorage(this.storage, "project", this.projectTrusted);
if (!projectLoad.error) {
this.projectSettings = projectLoad.settings;
this.projectSettingsLoadError = null;
}
else {
this.projectSettingsLoadError = projectLoad.error;
this.recordError("project", projectLoad.error);
}
this.updateSettings(this.mergedSettings());
}
getSelectedSettingsSources() {
return [...this.selectedSources.values()].map((source) => ({ ...source }));
}
subscribeToSourceSelection(listener) {
this.sourceListeners.push(listener);
return () => {
const index = this.sourceListeners.indexOf(listener);
if (index !== -1)
this.sourceListeners.splice(index, 1);
};
}
selectAndPublishSource(scope) {
const source = this.storage.selectSource?.(scope);
if (!source) {
this.selectedSources.delete(scope);
return;
}
this.selectedSources.set(scope, source);
for (const listener of this.sourceListeners)
listener({ ...source });
}
/** Apply additional overrides on top of current settings */
applyOverrides(overrides) {
this.runtimeOverrides = deepMergeSettings(this.runtimeOverrides, overrides);
this.updateSettings(this.mergedSettings());
}
/** Persisted global+project settings with the session-only override layer on top. */
mergedSettings() {
return deepMergeSettings(deepMergeSettings(this.globalSettings, this.projectSettings), this.runtimeOverrides);
}
/** Mark a global field as modified during this session */
markModified(field, nestedKey) {
this.runtimeOverrides = withoutOverride(this.runtimeOverrides, field, nestedKey);
this.modifiedFields.add(field);
if (nestedKey) {
if (!this.modifiedNestedFields.has(field)) {
this.modifiedNestedFields.set(field, new Set());
}
this.modifiedNestedFields.get(field).add(nestedKey);
}
}
/** Mark a project field as modified during this session */
markProjectModified(field, nestedKey) {
this.runtimeOverrides = withoutOverride(this.runtimeOverrides, field, nestedKey);
this.modifiedProjectFields.add(field);
if (nestedKey) {
if (!this.modifiedProjectNestedFields.has(field)) {
this.modifiedProjectNestedFields.set(field, new Set());
}
this.modifiedProjectNestedFields.get(field).add(nestedKey);
}
}
assertProjectTrustedForWrite() {
if (!this.projectTrusted) {
throw new Error("Project is not trusted; refusing to write project settings");
}
}
recordError(scope, error) {
const normalizedError = error instanceof Error ? error : new Error(String(error));
this.errors.push(toSettingsError(scope, normalizedError, this.settingsPaths[scope]));
}
clearModifiedScope(scope) {
if (scope === "global") {
this.modifiedFields.clear();
this.modifiedNestedFields.clear();
return;
}
this.modifiedProjectFields.clear();
this.modifiedProjectNestedFields.clear();
}
enqueueWrite(scope, task) {
this.writeQueue = this.writeQueue
.then(async () => {
if (scope === "project") {
this.assertProjectTrustedForWrite();
}
await task();
this.clearModifiedScope(scope);
})
.catch((error) => {
this.recordError(scope, error);
});
}
cloneModifiedNestedFields(source) {
const snapshot = new Map();
for (const [key, value] of source.entries()) {
snapshot.set(key, new Set(value));
}
return snapshot;
}
persistScopedSettings(scope, snapshotSettings, modifiedFields, modifiedNestedFields, state = false) {
const merge = (current) => {
const raw = state ? parseStateSettings(this.storage, current) : current ? parseSettingsJson(current) : {};
const currentFileSettings = SettingsManager.migrateSettings(structuredClone(raw));
const mergedSettings = { ...currentFileSettings };
for (const field of modifiedFields) {
const value = snapshotSettings[field];
if (modifiedNestedFields.has(field) && typeof value === "object" && value !== null) {
const nestedModified = modifiedNestedFields.get(field);
const baseNested = currentFileSettings[field] ?? {};
const inMemoryNested = value;
const mergedNested = { ...baseNested };
for (const nestedKey of nestedModified) {
if (inMemoryNested[nestedKey] === undefined)
delete mergedNested[nestedKey];
else
mergedNested[nestedKey] = inMemoryNested[nestedKey];
}
mergedSettings[field] = mergedNested;
}
else if (value === undefined) {
delete mergedSettings[field];
}
else {
mergedSettings[field] = value;
}
}
// Compare parsed values, not serialized formatting: no-op saves preserve JSONC and whitespace.
return isDeepStrictEqual(currentFileSettings, mergedSettings)
? undefined
: JSON.stringify(mergedSettings, null, 2);
};
const storage = this.storage;
if (state && storage.withStateLock) {
if (!storage.withStateLockAsync || !storage.tryWithStateLock) {
storage.withStateLock(merge);
return;
}
if (storage.tryWithStateLock(merge))
return;
return storage.withStateLockAsync(merge);
}
if (!storage.withLockAsync || !storage.tryWithLock) {
storage.withLock(scope, merge);
return;
}
// Uncontended (the normal case): written before save() returns, as callers expect. Only when
// another writer holds the lock does the wait move off the UI thread.
if (storage.tryWithLock(scope, merge))
return;
return storage.withLockAsync(scope, merge, scope === "project" ? () => this.assertProjectTrustedForWrite() : undefined);
}
save() {
this.updateSettings(this.mergedSettings());
if (this.globalSettingsLoadError) {
return;
}
const snapshotGlobalSettings = structuredClone(this.globalSettings);
const modifiedFields = new Set(this.modifiedFields);
const modifiedNestedFields = this.cloneModifiedNestedFields(this.modifiedNestedFields);
this.enqueueWrite("global", async () => {
if (this.storage.withStateLock) {
const stateFields = new Set([...modifiedFields].filter((key) => STATE_KEYS.has(key)));
if (stateFields.size > 0) {
try {
await this.persistScopedSettings("global", snapshotGlobalSettings, stateFields, modifiedNestedFields, true);
}
catch (error) {
logStateError(this.storage, error);
}
}
for (const key of STATE_KEYS)
modifiedFields.delete(key);
}
if (modifiedFields.size > 0) {
await this.persistScopedSettings("global", snapshotGlobalSettings, modifiedFields, modifiedNestedFields);
}
});
}
saveProjectSettings(settings) {
this.assertProjectTrustedForWrite();
this.projectSettings = structuredClone(settings);
this.updateSettings(this.mergedSettings());
if (this.projectSettingsLoadError) {
return;
}
const snapshotProjectSettings = structuredClone(this.projectSettings);
const modifiedFields = new Set(this.modifiedProjectFields);
const modifiedNestedFields = this.cloneModifiedNestedFields(this.modifiedProjectNestedFields);
this.enqueueWrite("project", () => this.persistScopedSettings("project", snapshotProjectSettings, modifiedFields, modifiedNestedFields));
}
updateProjectSettings(field, update) {
this.assertProjectTrustedForWrite();
const projectSettings = structuredClone(this.projectSettings);
update(projectSettings);
this.markProjectModified(field);
this.saveProjectSettings(projectSettings);
}
async flush() {
await this.writeQueue;
}
drainErrors() {
const drained = [...this.errors];
this.errors = [];
return drained;
}
getLastChangelogVersion() {
return this.settings.lastChangelogVersion;
}
setLastChangelogVersion(version) {
this.globalSettings.lastChangelogVersion = version;
this.markModified("lastChangelogVersion");
this.save();
}
getChangelogSeen(source = "engine") {
return (this.settings.changelogSeen?.[source] ?? (source === "engine" ? this.settings.lastChangelogVersion : undefined));
}
setChangelogSeen(source, version) {
if (!source || this.globalSettings.changelogSeen?.[source] === version)
return;
this.globalSettings.changelogSeen = { ...(this.globalSettings.changelogSeen ?? {}), [source]: version };
this.markModified("changelogSeen", source);
this.save();
}
getSessionDir() {
const sessionDir = this.settings.sessionDir;
return sessionDir ? normalizePath(sessionDir) : sessionDir;
}
getDefaultProvider() {
return this.settings.defaultProvider;
}
getDefaultModel() {
return this.settings.defaultModel;
}
setDefaultProvider(provider) {
this.globalSettings.defaultProvider = provider;
this.markModified("defaultProvider");
this.save();
}
setDefaultModel(modelId) {
this.globalSettings.defaultModel = modelId;
this.markModified("defaultModel");
this.save();
}
setDefaultModelAndProvider(provider, modelId) {
this.globalSettings.defaultProvider = provider;
this.globalSettings.defaultModel = modelId;
this.markModified("defaultProvider");
this.markModified("defaultModel");
this.save();
}
getSteeringMode() {
return this.settings.steeringMode || "all";
}
setSteeringMode(mode) {
this.globalSettings.steeringMode = mode;
this.markModified("steeringMode");
this.save();
}
getFollowUpMode() {
return this.settings.followUpMode || "one-at-a-time";
}
setFollowUpMode(mode) {
this.globalSettings.followUpMode = mode;
this.markModified("followUpMode");
this.save();
}
getThemeSetting() {
const value = this.settings.theme;
if (typeof value === "string")
return value;
return undefined;
}
getTheme() {
const theme = this.getThemeSetting();
return theme?.includes("/") ? undefined : theme;
}
setTheme(theme) {
this.globalSettings.theme = theme;
this.markModified("theme");
this.save();
}
getDefaultThinkingLevel() {
return this.settings.defaultThinkingLevel;
}
setDefaultThinkingLevel(level) {
this.globalSettings.defaultThinkingLevel = level;
this.markModified("defaultThinkingLevel");
this.save();
}
getAllModelThinkingLevels() {
return { ...(this.settings.modelThinkingLevels ?? {}) };
}
/** Thinking level last set for this exact model, or undefined when unknown/invalid on disk. */
getModelThinkingLevel(provider, modelId) {
return readModelMemoryEntry(this.settings.modelThinkingLevels, modelMemoryKey(provider, modelId), THINKING_LEVEL_VALUES);
}
/** Remember (or with `undefined`, forget) this model's effective thinking level in GLOBAL settings. */
setModelThinkingLevel(provider, modelId, level, options = {}) {
const key = modelMemoryKey(provider, modelId);
const existing = this.globalSettings.modelThinkingLevels;
const map = typeof existing === "object" && existing !== null && !Array.isArray(existing) ? { ...existing } : {};
if (level === undefined) {
delete map[key];
}
else {
map[key] = level;
}
this.globalSettings.modelThinkingLevels = map;
// Nested key only: concurrent sessions writing OTHER models must survive the merge.
this.markModified("modelThinkingLevels", key);
// `off` is durable effective state, but it must not erase the level `/reasoning on` restores.
if (level !== "off" && !options.preserveLastOn) {
this.updateModelLastOnThinkingLevel(key, level);
}
this.save();
}
/** Last non-off thinking level for this exact model, or undefined when unknown/invalid on disk. */
getModelLastOnThinkingLevel(provider, modelId) {
const level = readModelMemoryEntry(this.settings.modelLastOnThinkingLevels, modelMemoryKey(provider, modelId), THINKING_LEVEL_VALUES);
return level === "off" ? undefined : level;
}
/** Remember (or with `undefined`, forget) this model's last non-off level in GLOBAL settings. */
setModelLastOnThinkingLevel(provider, modelId, level) {
this.updateModelLastOnThinkingLevel(modelMemoryKey(provider, modelId), level === "off" ? undefined : level);
this.save();
}
updateModelLastOnThinkingLevel(key, level) {
const existing = this.globalSettings.modelLastOnThinkingLevels;
const map = typeof existing === "object" && existing !== null && !Array.isArray(existing) ? { ...existing } : {};
if (level === undefined) {
delete map[key];
}
else {
map[key] = level;
}
this.globalSettings.modelLastOnThinkingLevels = map;
this.markModified("modelLastOnThinkingLevels", key);
}
/** Service tier last set for this exact model, or undefined when unknown/invalid on disk. */
getModelServiceTier(provider, modelId) {
return readModelMemoryEntry(this.settings.modelServiceTiers, modelMemoryKey(provider, modelId), MODEL_SERVICE_TIER_VALUES);
}
/** Remember (or with `undefined`, forget) this model's service tier in GLOBAL settings. */
setModelServiceTier(provider, modelId, tier) {
const key = modelMemoryKey(provider, modelId);
const existing = this.globalSettings.modelServiceTiers;
const map = typeof existing === "object" && existing !== null && !Array.isArray(existing) ? { ...existing } : {};
if (tier === undefined) {
delete map[key];
}
else {
map[key] = tier;
}
this.globalSettings.modelServiceTiers = map;
this.markModified("modelServiceTiers", key);
this.save();
}
getTransport() {
return this.settings.transport ?? "auto";
}
getOpenAIServiceTier() {
return this.settings.openai?.serviceTier;
}
setTransport(transport) {
this.globalSettings.transport = transport;
this.markModified("transport");
this.save();
}
getCompactionEnabled() {
return compactionEnabled(this.settings.compaction);
}
setCompactionEnabled(enabled) {
if (!this.globalSettings.compaction) {
this.globalSettings.compaction = {};
}
this.globalSettings.compaction.enabled = enabled;
this.markModified("compaction", "enabled");
this.save();
}
/**
* Token budgets resolve through the per-model override table (`compaction.modelOverrides`,
* exact `provider/modelId` keys) before the ordinary setting and the built-in default.
*/
getCompactionReserveTokens(forModel) {
return compactionReserveTokens(this.settings.compaction, forModel);
}
getCompactionKeepRecentTokens(forModel) {
return compactionKeepRecentTokens(this.settings.compaction, forModel);
}
getCompactionSettings(forModel) {
return {
...resolveCompactionSettings(this.settings.compaction, forModel),
// `compaction.model` is the summarization model, a different concept from the
// session model whose per-model token budgets `forModel` resolves.
model: this.settings.compaction?.model,
};
}
getBranchSummarySettings() {
return {
reserveTokens: this.settings.branchSummary?.reserveTokens ?? 16384,
skipPrompt: this.settings.branchSummary?.skipPrompt ?? false,
};
}
getBranchSummarySkipPrompt() {
return this.settings.branchSummary?.skipPrompt ?? false;
}
getRetryEnabled() {
return this.settings.retry?.enabled ?? true;
}
setRetryEnabled(enabled) {
if (!this.globalSettings.retry) {
this.globalSettings.retry = {};
}
this.globalSettings.retry.enabled = enabled;
this.markModified("retry", "enabled");
this.save();
}
/** True when the user explicitly configured retry.maxAgentDelayMs in settings (not the shipped default). */
isRetryMaxAgentDelayMsConfigured() {
return this.settings.retry?.maxAgentDelayMs !== undefined;
}
getRetrySettings() {
return {
enabled: this.getRetryEnabled(),
// Derived, not duplicated: the one `retry.maxRetries` key must mean the
// same budget on every consumer, so the default tracks the shipped profile.
maxRetries: this.settings.retry?.maxRetries ?? SENPI_DEFAULT_RETRY_PROFILE.turn.maxRetries,
baseDelayMs: this.settings.retry?.baseDelayMs ?? 2000,
maxAgentDelayMs: this.settings.retry?.maxAgentDelayMs ?? DEFAULT_MAX_AGENT_RETRY_DELAY_MS,
};
}
/**
* Abort a turn when the provider silently substitutes the requested model
* after a classifier decline, so model choice stays with the configured
* fallback chain instead of the provider. Defaults to enabled.
*/
getAbortServerSideFallback() {
return resolveAbortServerSideFallback(this.settings.retry);
}
/** Raw retry.fallbackChains value before sanitization, for startup validation warnings. */
getRawFallbackChains() {
return this.settings.retry?.fallbackChains;
}
/**
* Which scope supplied `retry.fallbackChains`, so a validation warning can name
* the file to open. Project scope wins because it replaces the global chain map
* wholesale. Returns undefined when no scope configured chains and the resolved
* map is therefore the shipped defaults.
*/
getFallbackChainsScope() {
if (this.projectSettings.retry?.fallbackChains !== undefined)
return "project";
if (this.globalSettings.retry?.fallbackChains !== undefined)
return "global";
return undefined;
}
getRetryFallbackSettings() {
// Chains in the session-only override layer (applyRetryFallbackProfile, or an SDK applyOverrides call) are the session's whole policy.
return resolveRetryFallbackSettings(this.settings.retry, {
sessionPolicy: this.runtimeOverrides.retry?.fallbackChains !== undefined,
});
}
getFallbackCircuitSettings() {
return resolveFallbackCircuitSettings(this.settings.fallback);
}
getHintPolicySettings() {
return resolveHintPolicySettings(this.settings.retry);
}
setFallbackChain(key, entries) {
if (!this.globalSettings.retry) {
this.globalSettings.retry = {};
}
const chains = this.getGlobalFallbackChains();
this.globalSettings.retry.fallbackChains = {
...chains,
[key]: [...entries],
};
this.markModified("retry", "fallbackChains");
this.save();
}
removeFallbackChain(key) {
const chains = this.getGlobalFallbackChains();
if (!(key in chains)) {
return;
}
if (!this.globalSettings.retry) {
this.globalSettings.retry = {};
}
delete chains[key];
this.globalSettings.retry.fallbackChains = chains;
this.markModified("retry", "fallbackChains");
this.save();
}
setModelFallbackEnabled(enabled) {
if (!this.globalSettings.retry) {
this.globalSettings.retry = {};
}
this.globalSettings.retry.modelFallback = enabled;
this.markModified("retry", "modelFallback");
this.save();
}
setFallbackRevertPolicy(policy) {
if (!this.globalSettings.retry) {
this.globalSettings.retry = {};
}
this.globalSettings.retry.fallbackRevertPolicy = policy;
this.markModified("retry", "fallbackRevertPolicy");
this.save();
}
getGlobalFallbackChains() {
const fallbackChains = this.globalSettings.retry?.fallbackChains;
if (typeof fallbackChains !== "object" || fallbackChains === null || Array.isArray(fallbackChains)) {
return {};
}
const chains = {};
for (const [key, entries] of Object.entries(fallbackChains)) {
if (Array.isArray(entries) && entries.every((entry) => typeof entry === "string")) {
chains[key] = [...entries];
}
}
return chains;
}
getHttpIdleTimeoutMs() {
return parseTimeoutSetting(this.settings.httpIdleTimeoutMs, "httpIdleTimeoutMs") ?? DEFAULT_HTTP_IDLE_TIMEOUT_MS;
}
setHttpIdleTimeoutMs(timeoutMs) {
if (!Number.isFinite(timeoutMs) || timeoutMs < 0) {
throw new Error(`Invalid httpIdleTimeoutMs setting: ${String(timeoutMs)}`);
}
this.globalSettings.httpIdleTimeoutMs = Math.floor(timeoutMs);
this.markModified("httpIdleTimeoutMs");
this.save();
}
/**
* How long one extension's `session_shutdown` handler may run before the host
* warns about it. 0 disables the warning.
*/
getSessionShutdownHandlerWarnMs() {
return (parseTimeoutSetting(this.settings.sessionShutdownHandlerWarnMs, "sessionShutdownHandlerWarnMs") ??
DEFAULT_SESSION_SHUTDOWN_HANDLER_WARN_MS);
}
setSessionShutdownHandlerWarnMs(warnMs) {
if (!Number.isFinite(warnMs) || warnMs < 0) {
throw new Error(`Invalid sessionShutdownHandlerWarnMs setting: ${String(warnMs)}`);
}
this.globalSettings.sessionShutdownHandlerWarnMs = Math.floor(warnMs);
this.markModified("sessionShutdownHandlerWarnMs");
this.save();
}
/**
* Hard cap on one extension's `session_shutdown` handler. On expiry the host
* aborts that handler's `event.signal`, reports an extension error and moves
* on to the next handler. 0 disables the cap (unbounded, pre-budget behavior).
*/
getSessionShutdownHandlerTimeoutMs() {
return (parseTimeoutSetting(this.settings.sessionShutdownHandlerTimeoutMs, "sessionShutdownHandlerTimeoutMs") ??
DEFAULT_SESSION_SHUTDOWN_HANDLER_TIMEOUT_MS);
}
setSessionShutdownHandlerTimeoutMs(timeoutMs) {
if (!Number.isFinite(timeoutMs) || timeoutMs < 0) {
throw new Error(`Invalid sessionShutdownHandlerTimeoutMs setting: ${String(timeoutMs)}`);
}
this.globalSettings.sessionShutdownHandlerTimeoutMs = Math.floor(timeoutMs);
this.markModified("sessionShutdownHandlerTimeoutMs");
this.save();
}
/**
* Total time the host waits on all `session_shutdown` handlers together when the
* process quits; each handler's own cap still applies inside it. 0 disables it.
*/
getSessionShutdownQuitBudgetMs() {
return (parseTimeoutSetting(this.settings.sessionShutdownQuitBudgetMs, "sessionShutdownQuitBudgetMs") ??
DEFAULT_SESSION_SHUTDOWN_QUIT_BUDGET_MS);
}
setSessionShutdownQuitBudgetMs(budgetMs) {
if (!Number.isFinite(budgetMs) || budgetMs < 0) {
throw new Error(`Invalid sessionShutdownQuitBudgetMs setting: ${String(budgetMs)}`);
}
this.globalSettings.sessionShutdownQuitBudgetMs = Math.floor(budgetMs);
this.markModified("sessionShutdownQuitBudgetMs");
this.save();
}
/** How long one agent lifecycle event handler may run before the host reports it as stalled. 0 disables. */
getExtensionEventHandlerWarnMs() {
return (parseTimeoutSetting(this.settings.extensionEventHandlerWarnMs, "extensionEventHandlerWarnMs") ??
DEFAULT_EXTENSION_EVENT_HANDLER_WARN_MS);
}
/** Hard cap on one agent lifecycle event handler; past it the session's event queue moves on. 0 disables. */
getExtensionEventHandlerTimeoutMs() {
return (parseTimeoutSetting(this.settings.extensionEventHandlerTimeoutMs, "extensionEventHandlerTimeoutMs") ??
DEFAULT_EXTENSION_EVENT_HANDLER_TIMEOUT_MS);
}
getProviderRetrySettings() {
return {
timeoutMs: this.settings.retry?.provider?.timeoutMs,
maxRetries: this.settings.retry?.provider?.maxRetries,
maxRetryDelayMs: this.settings.retry?.provider?.maxRetryDelayMs ?? 60000,
};
}
/**
* Resolve the effective retry profile for a provider. Precedence:
* 1) SENPI_DEFAULT_RETRY_PROFILE is the base.
* 2) A provider-declared retryPolicy replaces the base entirely.
* 3) User global retry.maxRetries / retry.baseDelayMs apply ONLY when the
* provider declared NO profile (they must not silently re-tune one).
* 4) Validated retry.providers.<id> patches scheduling knobs last.
* 5) retry.enabled === false is a hard gate: resolved turn.enabled is false.
*/
resolveRetryProfile(provider) {
const base = provider?.retryPolicy ?? SENPI_DEFAULT_RETRY_PROFILE;
const declared = provider?.retryPolicy !== undefined;
const turnBackoff = { ...base.turn.backoff };
if (!declared) {
if (this.settings.retry?.maxRetries !== undefined) {
turnBackoff.baseDelayMs = this.settings.retry.baseDelayMs ?? turnBackoff.baseDelayMs;
}
}
let turnMaxRetries = base.turn.maxRetries;
let turnBaseDelayMs = turnBackoff.baseDelayMs;
if (!declared) {
if (this.settings.retry?.maxRetries !== undefined)
turnMaxRetries = this.settings.retry.maxRetries;
if (this.settings.retry?.baseDelayMs !== undefined)
turnBaseDelayMs = this.settings.retry.baseDelayMs;
}
const providerOverride = this._resolveRetryProviderOverride(provider?.id);
if (providerOverride?.turn?.maxRetries !== undefined)
turnMaxRetries = providerOverride.turn.maxRetries;
if (providerOverride?.turn?.baseDelayMs !== undefined)
turnBaseDelayMs = providerOverride.turn.baseDelayMs;
const turnEnabled = this.getRetryEnabled() ? (providerOverride?.turn?.enabled ?? base.turn.enabled) : false;
const tierStrategy = base.turn.serverHint.mode === "tiered"
? base.turn.serverHint.strategy
: () => {
throw new Error("not tiered");
};
const turn = {
enabled: turnEnabled,
maxRetries: turnMaxRetries,
backoff: { ...base.turn.backoff, baseDelayMs: turnBaseDelayMs },
extractServerHint: base.turn.extractServerHint,
serverHint: base.turn.serverHint.mode === "tiered" ? { mode: "tiered", strategy: tierStrategy } : base.turn.serverHint,
classify: base.turn.classify,
};
return {
id: base.id,
providerRequest: base.providerRequest,
turn,
fallback: base.fallback,
};
}
_resolveRetryProviderOverride(providerId) {
if (providerId === undefined)
return undefined;
const raw = this.settings.retry?.providers;
if (raw === undefined)
return undefined;
const { overrides } = validateRetryProviderOverrides(raw, new Set([providerId]));
return overrides[providerId];
}
/**
* First-request liveness cap for retries of known provider stream/transport
* timeouts. `retry.provider.streamRetryTimeoutMs` overrides the 30s default;
* 0 disables the cap without disabling queue deferral. The retry path clamps
* only already-enabled stream guards, so this setting never re-enables one.
*/
getProviderStreamRetryTimeoutMs() {
const explicit = this.settings.retry?.provider?.streamRetryTimeoutMs;
if (explicit !== undefined) {
return explicit > 0 ? explicit : undefined;
}
return DEFAULT_PROVIDER_STREAM_RETRY_TIMEOUT_MS;
}
/**
* Idle timeout for the agent loop's provider event reader. Defaults to
* httpIdleTimeoutMs so streams that stop delivering events (e.g. a
* connection that silently died after a network change) fail with a
* retryable idle-timeout error instead of hanging the session forever.
* `retry.provider.timeoutMs` overrides it; an httpIdleTimeoutMs of 0
* ("disabled") disables the reader guard as well.
*/
getAgentStreamIdleTimeoutMs() {
const providerTimeoutMs = this.settings.retry?.provider?.timeoutMs;
if (providerTimeoutMs !== undefined) {
return providerTimeoutMs;
}
const httpIdleTimeoutMs = this.getHttpIdleTimeoutMs();
return httpIdleTimeoutMs === 0 ? undefined : httpIdleTimeoutMs;
}
/**
* Bound on the time to the FIRST provider stream event. Providers only emit
* their first event once the HTTP response begins, so a dead upstream that
* accepts the request but never answers is otherwise bounded only by the
* idle timeout (default 5 minutes) — long enough to make a session feel
* permanently stuck. `retry.provider.streamStartTimeoutMs` overrides the
* 300s default (0 disables). The default never exceeds the idle timeout and
* is disabled together with a disabled idle guard.
*/
getAgentStreamStartTimeoutMs() {
const explicit = this.settings.retry?.provider?.streamStartTimeoutMs;
if (explicit !== undefined) {
return explicit > 0 ? explicit : undefined;
}
const idleTimeoutMs = this.getAgentStreamIdleTimeoutMs();
if (idleTimeoutMs === undefined) {
return undefined;
}
return Math.min(DEFAULT_STREAM_START_TIMEOUT_MS, idleTimeoutMs);
}
/**
* Cap on keep-alive-only silence. While a provider keeps sending bytes (SSE pings, comment keep-alives) the
* start and idle bounds do not end the request; this bounds how long that may last without any assistant
* event. `retry.provider.keepAliveTimeoutMs` overrides the 15-minute default; 0 disables the cap.
*/
getAgentStreamKeepAliveTimeoutMs() {
const explicit = this.settings.retry?.provider?.keepAliveTimeoutMs;
if (explicit !== undefined) {
return explicit > 0 ? explicit : undefined;
}
return DEFAULT_STREAM_KEEP_ALIVE_TIMEOUT_MS;
}
getWebSocketConnectTimeoutMs() {
return parseTimeoutSetting(this.settings.websocketConnectTimeoutMs, "websocketConnectTimeoutMs");
}
getHideThinkingBlock() {
return this.settings.hideThinkingBlock ?? false;
}
getSmoothStreaming() {
return this.settings.smoothStreaming ?? true;
}
getSmoothStreamingFps() {
const fps = this.settings.smoothStreamingFps;
if (typeof fps !== "number" || !Number.isFinite(fps)) {
return 60;
}
return Math.min(120, Math.max(30, fps));
}
getShowCacheMissNotices() {
return this.settings.showCacheMissNotices ?? false;
}
getExternalEditorCommand() {
const configuredEditor = this.settings.externalEditor;
if (typeof configuredEditor === "string" && configuredEditor.trim() !== "") {
return configuredEditor;
}
const environmentEditor = process.env.VISUAL || process.env.EDITOR;
if (environmentEditor) {
return environmentEditor;
}
return process.platform === "win32" ? "notepad" : "nano";
}
setHideThinkingBlock(hide) {
this.globalSettings.hideThinkingBlock = hide;
this.markModified("hideThinkingBlock");
this.save();
}
setSmoothStreaming(enabled) {
this.globalSettings.smoothStreaming = enabled;
this.markModified("smoothStreaming");
this.save();
}
setSmoothStreamingFps(fps) {
this.globalSettings.smoothStreamingFps = fps;
this.markModified("smoothStreamingFps");
this.save();
}
setShowCacheMissNotices(show) {
this.globalSettings.showCacheMissNotices = show;
this.markModified("showCacheMissNotices");
this.save();
}
getShellPath() {
const shellPath = this.settings.shellPath;
return shellPath ? normalizePath(shellPath) : shellPath;
}
setShellPath(path) {
this.globalSettings.shellPath = path;
this.markModified("shellPath");
this.save();
}
getQuietStartup() {
const value = this.settings.quietStartup;
return value === true || value === "header" ? value : false;
}
setQuietStartup(quiet) {
this.globalSettings.quietStartup = quiet;
this.markModified("quietStartup");
this.save();
}
getTipsEnabled() {
return this.settings.tips ?? true;
}
getReducedMotion() {
return this.settings.reducedMotion ?? false;
}
getTipsHistory() {
const history = this.settings.tipsHistory;
if (typeof history !== "object" || history === null || Array.isArray(history)) {
return {};
}
return { ...history };
}
setTipsHistory(history) {
this.globalSettings.tipsHistory = history;
this.markModified("tipsHistory");
this.save();
}
setTipShown(tipId, timestamp) {
const history = this.getTipsHistory();
history[tipId] = timestamp;
this.globalSettings.tipsHistory = history;
this.markModified("tipsHistory", tipId);
this.save();
}
getDefaultProjectTrust() {
const value = this.globalSettings.defaultProjectTrust;
return value === "always" || value === "never" ? value : "ask";
}
setDefaultProjectTrust(defaultProjectTrust) {
this.globalSettings.defaultProjectTrust = defaultProjectTrust;
this.markModified("defaultProjectTrust");
this.save();
}
getShellCommandPrefix() {
return this.settings.shellCommandPrefix;
}
getBashRedactSecretsInOutput() {
return this.settings.tools?.bash?.redactSecretsInOutput === true;
}
setShellCommandPrefix(prefix) {
this.globalSettings.shellCommandPrefix = prefix;
this.markModified("shellCommandPrefix");
this.save();
}
getNpmCommand() {
return this.settings.npmCommand ? [...this.settings.npmCommand] : undefined;
}
setNpmCommand(command) {
this.globalSettings.npmCommand = command ? [...command] : undefined;
this.markModified("npmCommand");
this.save();
}
getCollapseChangelog() {
return this.settings.collapseChangelog ?? false;
}
setCollapseChangelog(collapse) {
this.globalSettings.collapseChangelog = collapse;
this.markModified("collapseChangelog");
this.save();
}
getEnableInstallTelemetry() {
return this.settings.enableInstallTelemetry ?? true;
}
setEnableInstallTelemetry(enabled) {
this.globalSettings.enableInstallTelemetry = enabled;
this.markModified("enableInstallTelemetry");
this.save();
}
getEnableSessionShare() {
return this.settings.enableSessionShare ?? true;
}
getEnableAnalytics() {
return this.settings.enableAnalytics ?? false;
}
getTrackingId() {
return this.settings.trackingId;
}
/** Set the analytics opt-in preference; generates a tracking identifier on first opt-in */
setEnableAnalytics(enabled) {
this.globalSettings.enableAnalytics = enabled;
this.markModified("enableAnalytics");
if (enabled && !this.globalSettings.trackingId) {
this.globalSettings.trackingId = randomUUID();
this.markModified("trackingId");
}
this.save();
}
/**
* Stable ID of this installation, e.g. sent to OpenAI as its agent host ID.
* Created on first use. Project settings are ignored so a committed project
* settings file cannot give every clone the same ID.
*/
getOrCreateDeviceId() {
if (!this.globalSettings.deviceId) {
this.globalSettings.deviceId = randomUUID();
this.markModified("deviceId");
this.save();
}
return this.globalSettings.deviceId;
}
getPackages() {
return [...(this.settings.packages ?? [])];
}
getDisabledBuiltinExtensions() {
return [...(this.settings.disabledBuiltinExtensions ?? [])];
}
getEnabledBuiltinExtensions() {
return this.settings.enabledBuiltinExtensions ? [...this.settings.enabledBuiltinExtensions] : undefined;
}
setPackages(packages) {
this.globalSettings.packages = packages;
this.markModified("packages");
this.save();
}
setProjectPackages(packages) {
this.updateProjectSettings("packages", (settings) => {
settings.packages = packages;
});
}
getExtensionPaths() {
return [...(this.settings.extensions ?? [])];
}
setExtensionPaths(paths) {
this.globalSettings.extensions = paths;
this.markModified("extensions");
this.save();
}
setProjectExtensionPaths(paths) {
this.updateProjectSettings("extensions", (settings) => {
settings.extensions = paths;
});
}
getSkillPaths() {
return [...(this.settings.skills ?? [])];
}
setSkillPaths(paths) {
this.globalSettings.skills = paths;
this.markModified("skills");
this.save();
}
setProjectSkillPaths(paths) {
this.updateProjectSettings("skills", (settings) => {
settings.skills = paths;
});
}
getPromptTemplatePaths() {
return [...(this.settings.prompts ?? [])];
}
setPromptTemplatePaths(paths) {
this.globalSettings.prompts = paths;
this.markModified("prompts");
this.save();
}
setProjectPromptTemplatePaths(paths) {
this.updateProjectSettings("prompts", (settings) => {
settings.prompts = paths;
});
}
getThemePaths() {
return [...(this.settings.themes ?? [])];
}
setThemePaths(paths) {
this.globalSettings.themes = paths;
this.markModified("themes");
this.save();
}
setProjectThemePaths(paths) {
this.updateProjectSettings("themes", (settings) => {
settings.themes = paths;
});
}
getEnableSkillCommands() {
return this.settings.enableSkillCommands ?? true;
}
setEnableSkillCommands(enabled) {
this.globalSettings.enableSkillCommands = enabled;
this.markModified("enableSkillCommands");
this.save();
}
getThinkingBudgets() {
return this.settings.thinkingBudgets;
}
getTerminalCapabilityOverrides() {
const terminal = this.settings.terminal;
const imageSetting = terminal?.images;
const imageOverride = imageSetting !== undefined ? imageSetting : envValue("IMAGE_PROTOCOL")?.toLowerCase();
const trueColorSetting = terminal?.trueColor;
const trueColorOverride = trueColorSetting !== undefined ? trueColorSetting : envValue("TRUE_COLOR");
const hyperlinksSetting = terminal?.hyperlinks;
const hyperlinksOverride = hyperlinksSetting !== undefined ? hyperlinksSetting : envValue("HYPERLINKS");
return {
...(imageOverride === "kitty" || imageOverride === "iterm2"
? { images: imageOverride }
: imageOverride === false || imageOverride === "none" || imageOverride === "0"
? { images: null }
: {}),
...(typeof trueColorOverride === "boolean"
? { trueColor: trueColorOverride }
: trueColorOverride === "1" || trueColorOverride === "0"
? { trueColor: trueColorOverride === "1" }
: {}),
...(typeof hyperlinksOverride === "boolean"
? { hyperlinks: hyperlinksOverride }
: hyperlinksOverride === "1" || hyperlinksOverride === "0"
? { hyperlinks: hyperlinksOverride === "1" }
: {}),
};
}
getShowImages() {
return this.settings.terminal?.showImages ?? true;
}
setShowImages(show) {
if (!this.globalSettings.terminal) {
this.globalSettings.terminal = {};
}
this.globalSettings.terminal.showImages = show;
this.markModified("terminal", "showImages");
this.save();
}
getImageWidthCells() {
const width = this.settings.terminal?.imageWidthCells;
if (typeof width !== "number" || !Number.isFinite(width)) {
return 60;
}
return Math.max(1, Math.floor(width));
}
setImageWidthCells(width) {
if (!this.globalSettings.terminal) {
this.globalSettings.terminal = {};
}
this.globalSettings.terminal.imageWidthCells = Math.max(1, Math.floor(width));
this.markModified("terminal", "imageWidthCells");
this.save();
}
getTerminalMouse() {
const value = this.settings.terminal?.mouse;
return isTerminalMouseMode(value) ? value : "whilePending";
}
setTerminalMouse(mouse) {
if (!isTerminalMouseMode(mouse))
throw new TypeError("Invalid terminal.mouse");
this.globalSettings.terminal ??= {};
this.globalSettings.terminal.mouse = mouse;
this.markModified("terminal", "mouse");
this.save();
}
getClearOnShrink() {
// Settings takes precedence, then env var, then default false
if (this.settings.terminal?.clearOnShrink !== undefined) {
return this.settings.terminal.clearOnShrink;
}
return envValue("CLEAR_ON_SHRINK") === "1";
}
setClearOnShrink(enabled) {
if (!this.globalSettings.terminal) {
this.globalSettings.terminal = {};
}
this.globalSettings.terminal.clearOnShrink = enabled;
this.markModified("terminal", "clearOnShrink");
this.save();
}
getShowTerminalProgress() {
return this.settings.terminal?.showTerminalProgress ?? false;
}
setShowTerminalProgress(enabled) {
if (!this.globalSettings.terminal) {
this.globalSettings.terminal = {};
}
this.globalSettings.terminal.showTerminalProgress = enabled;
this.markModified("terminal", "showTerminalProgress");
this.save();
}
getTuiMode() {
return this.settings.tuiMode === "fullscreen" ? "fullscreen" : "regular";
}
setTuiMode(mode) {
this.globalSettings.tuiMode = mode;
this.markModified("tuiMode");
this.save();
}
getFullscreenExitOutput() {
return this.settings.fullscreenExitOutput === "resume-hint" ? "resume-hint" : "transcript";
}
setFullscreenExitOutput(output) {
this.globalSettings.fullscreenExitOutput = output;
this.markModified("fullscreenExitOutput");
this.save();
}
getFullscreenScrollbar() {
const mode = this.settings.fullscreenScrollbar;
return mode === "always" || mode === "hidden" ? mode : "auto";
}
setFullscreenScrollbar(mode) {
this.globalSettings.fullscreenScrollbar = mode;
this.markModified("fullscreenScrollbar");
this.save();
}
getFullscreenCopyOnSelect() {
return this.settings.fullscreenCopyOnSelect ?? true;
}
setFullscreenCopyOnSelect(enabled) {
this.globalSettings.fullscreenCopyOnSelect = enabled;
this.markModified("fullscreenCopyOnSelect");
this.save();
}
getFullscreenWheelScrollLines() {
const lines = this.settings.fullscreenWheelScrollLines;
return typeof lines === "number" && Number.isFinite(lines)
? Math.max(1, Math.min(100, Math.floor(lines)))
: "auto";
}
setFullscreenWheelScrollLines(lines) {
this.globalSettings.fullscreenWheelScrollLines =
lines === "auto" ? lines : Math.max(1, Math.min(100, Math.floor(lines)));
this.markModified("fullscreenWheelScrollLines");
this.save();
}
getImageAutoResize() {
return this.settings.images?.autoResize ?? true;
}
setImageAutoResize(enabled) {
if (!this.globalSettings.images) {
this.globalSettings.images = {};
}
this.globalSettings.images.autoResize = enabled;
this.markModified("images", "autoResize");
this.save();
}
getBlockImages() {
return this.settings.images?.blockImages ?? false;
}
getMaxHistoricalImages() {
const value = this.settings.images?.maxHistoricalImages;
return Number.isInteger(value) && value !== undefined && value >= 0 ? value : undefined;
}
setBlockImages(blocked) {
if (!this.globalSettings.images) {
this.globalSettings.images = {};
}
this.globalSettings.images.blockImages = blocked;
this.markModified("images", "blockImages");
this.save();
}
getEnabledModels() {
return this.settings.enabledModels;
}
getRecommendedModels() {
return this.settings.recommendedModels ? [...this.settings.recommendedModels] : undefined;
}
getFavoriteModels() {
return this.settings.favoriteModels;
}
setFavoriteModels(patterns) {
this.globalSettings.favoriteModels = patterns;
this.markModified("favoriteModels");
this.save();
}
/** The resolved `defaultTools` selection, or undefined when no settings layer sets it. */
getDefaultTools() {
const tools = this.settings.defaultTools;
if (tools === undefined)
return undefined;
return resolveDefaultTools(Array.isArray(tools) ? tools.filter((tool) => typeof tool === "string") : []);
}
setEnabledModels(patterns) {
this.globalSettings.enabledModels = patterns;
this.markModified("enabledModels");
this.save();
}
getDoubleEscapeAction() {
return this.settings.doubleEscapeAction ?? "tree";
}
setDoubleEscapeAction(action) {
this.globalSettings.doubleEscapeAction = action;
this.markModified("doubleEscapeAction");
this.save();
}
getTreeFilterMode() {
const mode = this.settings.treeFilterMode;
const valid = ["default", "no-tools", "user-only", "labeled-only", "all"];
return mode && valid.includes(mode) ? mode : "default";
}
setTreeFilterMode(mode) {
this.globalSettings.treeFilterMode = mode;
this.markModified("treeFilterMode");
this.save();
}
getShowHardwareCursor() {
return this.settings.showHardwareCursor ?? envValue("HARDWARE_CURSOR") === "1";
}
setShowHardwareCursor(enabled) {
this.globalSettings.showHardwareCursor = enabled;
this.markModified("showHardwareCursor");
this.save();
}
getEditorPaddingX() {
return this.settings.editorPaddingX ?? 0;
}
setEditorPaddingX(padding) {
this.globalSettings.editorPaddingX = Math.max(0, Math.min(3, Math.floor(padding)));
this.markModified("editorPaddingX");
this.save();
}
getOutputPad() {
return this.settings.outputPad === 0 ? 0 : 1;
}
setOutputPad(padding) {
this.globalSettings.outputPad = padding;
this.markModified("outputPad");
this.save();
}
getAutocompleteMaxVisible() {
return this.settings.autocompleteMaxVisible ?? 5;
}
setAutocompleteMaxVisible(maxVisible) {
this.globalSettings.autocompleteMaxVisible = Math.max(3, Math.min(20, Math.floor(maxVisible)));
this.markModified("autocompleteMaxVisible");
this.save();
}
getCodeBlockIndent() {
return this.settings.markdown?.codeBlockIndent ?? " ";
}
getMermaidRenderingMode() {
const mode = this.settings.markdown?.mermaid;
return mode === "off" || mode === "final" ? mode : "streaming";
}
setMermaidRenderingMode(mode) {
this.globalSettings.markdown ??= {};
this.globalSettings.markdown.mermaid = mode;
this.markModified("markdown", "mermaid");
this.save();
}
getWarnings() {
return { ...(this.settings.warnings ?? {}) };
}
setWarnings(warnings) {
this.globalSettings.warnings = { ...warnings };
this.markModified("warnings");
this.save();
}
}
//# sourceMappingURL=settings-manager.js.map