src/config/config.ts
9 KB - Ver el archivo original
// Steward configuration: one JSON file, validated with Zod at startup.
//
// Lookup order (first match wins):
// 1. the --config <file> CLI flag
// 2. the STEWARD_CONFIG environment variable
// 3. config/steward.json (your local copy, git-ignored)
// 4. config/steward.example.json (the defaults that ship with the lab)
//
// Relative paths inside the file (persona, rules, dataDir) resolve against the folder that
// holds the config file. Environment overrides (handy for tests and containers):
// STEWARD_DATA_DIR paths.dataDir
// STEWARD_WORKSPACE paths.workspace
// STEWARD_WEB_HOST web.host (a container listens on 0.0.0.0 behind a localhost port map)
import { existsSync, readFileSync } from 'node:fs';
import { homedir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { z } from 'zod';
const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'] as const;
export const DECISIONS = ['allow', 'ask', 'deny'] as const;
// USD per million tokens. cacheWrite is the 5-minute cache write price (lab 03).
const Rates = z.object({
input: z.number().nonnegative(),
output: z.number().nonnegative(),
cacheRead: z.number().nonnegative(),
cacheWrite: z.number().nonnegative(),
});
const Price = Rates.extend({
// Some models (Claude Haiku 5.5) charge more for a request whose prompt (input + cache reads +
// cache writes) is over a threshold. The whole request then uses these rates.
longContext: Rates.extend({ overTokens: z.number().int().positive() }).optional(),
});
export const PolicyRule = z.object({
tool: z.string().min(1),
// For run_program only: a command pattern such as "git log **" (see src/security/policy.ts).
command: z.string().min(1).optional(),
decision: z.enum(DECISIONS),
});
export type PolicyRule = z.infer<typeof PolicyRule>;
export const JobConfig = z
.object({
id: z.string().regex(/^[a-z0-9][a-z0-9-]{0,40}$/, 'lowercase letters, digits, and dashes'),
// Five-field cron in the owner's time zone ("30 7 * * *"), or a one-off ISO time in "at".
cron: z.string().optional(),
at: z.string().optional(),
prompt: z.string().min(3),
enabled: z.boolean().default(true),
})
.refine((job) => Boolean(job.cron) !== Boolean(job.at), 'give exactly one of "cron" or "at"');
export type JobConfig = z.infer<typeof JobConfig>;
export const ConfigSchema = z.object({
assistant: z.object({
name: z.string().min(1).default('Steward'),
}),
model: z.object({
main: z.string().min(1),
subagent: z.string().min(1),
effort: z.enum(EFFORTS).default('medium'),
maxTokens: z.number().int().positive().default(16000),
// Re-run a declined request on a fallback model inside the same API call.
refusalFallbacks: z.boolean().default(true),
// Safety stop for one turn: model calls per user message.
maxStepsPerTurn: z.number().int().positive().default(12),
}),
paths: z.object({
dataDir: z.string().min(1),
persona: z.string().min(1),
rules: z.string().min(1),
// System prompt of the research helper (lab 10).
subagent: z.string().min(1).default('subagent.md'),
// The only folder file tools and programs may touch (lab 04).
workspace: z.string().min(1).default('~/steward-workspace'),
}),
owner: z.object({
name: z.string().min(1),
// IANA time zone such as "Europe/Berlin", or "auto" for the machine's zone.
timezone: z.string().min(1).default('auto'),
// Who counts as the owner, as "<channel>:<sender>" (lab 08). Messages from anyone else are
// refused. Listing one person on several channels links those identities.
identities: z.array(z.string().min(3)).default(['terminal:owner', 'web:owner']),
}),
// USD per million tokens, per model id (lab 03). Check the current price list before
// relying on the numbers; unknown models are shown without a cost.
pricing: z.record(z.string(), Price).prefault({}),
// Long conversations (lab 07).
context: z
.object({
compaction: z
.object({
enabled: z.boolean().default(true),
// Summarize earlier turns once a request reaches this many input tokens.
triggerTokens: z.number().int().min(50_000).default(150_000),
// Optional: what the summary must keep. Empty means the API default.
instructions: z.string().default(''),
})
.prefault({}),
clearToolResults: z
.object({
enabled: z.boolean().default(true),
// Start clearing old tool results once a request reaches this many input tokens.
triggerTokens: z.number().int().positive().default(60_000),
// Always keep the most recent tool calls and results.
keepRecent: z.number().int().nonnegative().default(4),
})
.prefault({}),
})
.prefault({}),
// Limits for built-in tools (lab 04).
tools: z
.object({
maxOutputChars: z.number().int().positive().default(12_000),
programTimeoutMs: z.number().int().positive().default(15_000),
})
.prefault({}),
// Which tool calls run, ask first, or never run (labs 04-05).
policy: z
.object({
default: z.enum(DECISIONS).default('ask'),
rules: z.array(PolicyRule).default([]),
})
.prefault({}),
// How channel messages map to sessions (lab 08): one shared conversation, or one per channel.
gateway: z.object({ scope: z.enum(['main', 'per-channel']).default('main') }).prefault({}),
// The local web chat (lab 08). It listens on localhost only and needs the token.
web: z
.object({
enabled: z.boolean().default(true),
host: z.string().default('127.0.0.1'),
port: z.number().int().min(1).max(65535).default(8787),
// Empty: use STEWARD_WEB_TOKEN, or generate one at startup and print it.
token: z.string().default(''),
})
.prefault({}),
// Scheduled jobs (lab 09). Jobs listed here are owned by you; the assistant can add its own.
scheduler: z
.object({
enabled: z.boolean().default(true),
// After downtime, run a missed job once if it was due less than this many hours ago.
catchUpHours: z.number().nonnegative().default(12),
jobs: z.array(JobConfig).default([]),
})
.prefault({}),
// Sub-agents (lab 10).
subagents: z
.object({
maxSteps: z.number().int().positive().default(8),
// Token budget the sub-agent paces itself against (minimum 20000).
taskBudgetTokens: z.number().int().min(20_000).default(40_000),
maxResultChars: z.number().int().positive().default(6_000),
})
.prefault({}),
// Spending guard (lab 12). 0 turns it off.
limits: z.object({ dailyUsd: z.number().nonnegative().default(5) }).prefault({}),
});
export type StewardConfig = z.infer<typeof ConfigSchema> & {
/** Absolute path of the file this config was loaded from. */
source: string;
};
const LAB_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
export function findConfigFile(explicit?: string): string {
const candidates = [
explicit,
process.env.STEWARD_CONFIG,
path.join(LAB_ROOT, 'config', 'steward.json'),
path.join(LAB_ROOT, 'config', 'steward.example.json'),
].filter((p): p is string => typeof p === 'string' && p.length > 0);
for (const candidate of candidates) {
const absolute = path.resolve(candidate);
if (existsSync(absolute)) return absolute;
}
throw new Error(`No config file found. Tried: ${candidates.join(', ')}`);
}
export function expandHome(p: string): string {
if (p === '~') return homedir();
if (p.startsWith('~/')) return path.join(homedir(), p.slice(2));
return p;
}
export function loadConfig(explicitPath?: string): StewardConfig {
const source = findConfigFile(explicitPath);
let raw: unknown;
try {
raw = JSON.parse(readFileSync(source, 'utf8'));
} catch (err) {
throw new Error(`Config file ${source} is not valid JSON: ${(err as Error).message}`, {
cause: err,
});
}
const parsed = ConfigSchema.safeParse(raw);
if (!parsed.success) {
const problems = parsed.error.issues
.map((issue) => ` - ${issue.path.join('.') || '(root)'}: ${issue.message}`)
.join('\n');
throw new Error(`Config file ${source} is invalid:\n${problems}`);
}
const base = path.dirname(source);
const resolve = (p: string) => path.resolve(base, expandHome(p));
const config = parsed.data;
const dataDirOverride = process.env.STEWARD_DATA_DIR;
return {
...config,
paths: {
dataDir: dataDirOverride
? path.resolve(expandHome(dataDirOverride))
: resolve(config.paths.dataDir),
persona: resolve(config.paths.persona),
rules: resolve(config.paths.rules),
subagent: resolve(config.paths.subagent),
workspace: process.env.STEWARD_WORKSPACE
? path.resolve(expandHome(process.env.STEWARD_WORKSPACE))
: resolve(config.paths.workspace),
},
web: { ...config.web, host: process.env.STEWARD_WEB_HOST || config.web.host },
owner: {
...config.owner,
timezone:
config.owner.timezone === 'auto'
? Intl.DateTimeFormat().resolvedOptions().timeZone
: config.owner.timezone,
},
source,
};
}