src/cli.ts
23 KB - הצגת הקובץ המקורי
#!/usr/bin/env node
// steward - command-line entry point.
//
// steward doctor check config, paths, and credentials (lab 00)
// steward ask "question" one stateless model call (lab 00)
// steward chat --ephemeral chat with tools, memory lost on exit (lab 01)
// steward chat [--session <key>] the full assistant, durable (lab 02+)
// steward sessions list sessions (lab 02)
// steward show [--session <key>] print a session's event log (lab 02)
// steward usage tokens and cost per session (lab 03)
// steward init copy the example study workspace (lab 04)
// steward audit [count] last tool decisions (lab 05)
// steward memory [path] list or print long-term memory (lab 06)
// steward serve [--no-terminal] gateway: web chat, scheduler, terminal (labs 08-12)
// steward jobs [run <id>] list scheduled jobs, or run one now (lab 09)
// steward eval [name] [--repeat N] behavioral evals with the real model (lab 11)
// steward backup [folder] copy the data folder (lab 12)
//
// Every command accepts --config <file>.
import { randomBytes } from 'node:crypto';
import { cp, readdir } from 'node:fs/promises';
import { serve, type ServerType } from '@hono/node-server';
import { existsSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { parseArgs } from 'node:util';
import { createApp } from './app.ts';
import { runTerminalChat, formatUsage, TerminalAdapter } from './channels/terminal.ts';
import { createWebApp, WebAdapter } from './channels/web.ts';
import { Gateway } from './gateway/gateway.ts';
import { loadScenarios, runScenario } from './evals/runner.ts';
import { backupDataDir } from './runtime/backup.ts';
import { LockError, ProcessLock } from './runtime/lock.ts';
import { Scheduler } from './scheduler/scheduler.ts';
import { loadConfig, type StewardConfig } from './config/config.ts';
import { buildSystemPrompt } from './context/system-prompt.ts';
import { cacheHitRate, formatUsd, totalCost } from './context/usage.ts';
import { AnthropicModel } from './core/anthropic-model.ts';
import type { BetaMessageParam } from './core/model.ts';
import { runTurn, type TurnUsage } from './core/turn-loop.ts';
import { MemoryStore } from './memory/memory-store.ts';
import { AuditLog } from './security/audit.ts';
import type { Session } from './sessions/session.ts';
import { SessionStore, sessionKey } from './sessions/session-store.ts';
import { timeTools } from './tools/time-tools.ts';
import { Workspace } from './tools/workspace.ts';
const LAB_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const USAGE = `Usage: steward <command> [options]
Commands:
doctor check config, paths, and credentials
ask "<question>" one stateless model call (no history, no tools)
chat [--ephemeral] chat in the terminal (--ephemeral: time tools only, nothing saved)
sessions list sessions
show print the current session's events
usage tokens and cost per session
init copy the example study workspace (only into an empty workspace)
audit [count] the last tool decisions (default 20)
memory [path] list long-term memory, or print one entry
serve [--no-terminal] web chat + scheduler (+ terminal when interactive)
jobs [run <id>] list scheduled jobs, or run one now
eval [name] [--repeat N] run behavioral evals against the real model (costs money)
backup [folder] copy the data folder to <folder>/steward-backup-<time>
Options:
--config <file> config file (default: config/steward.json, then the example)
--session <key> session key for chat and show (default: steward:main)
`;
async function main(): Promise<void> {
const { values, positionals } = parseArgs({
allowPositionals: true,
options: {
config: { type: 'string' },
session: { type: 'string' },
ephemeral: { type: 'boolean', default: false },
'no-terminal': { type: 'boolean', default: false },
repeat: { type: 'string' },
help: { type: 'boolean', short: 'h', default: false },
},
});
const [command, ...rest] = positionals;
if (!command || values.help) {
console.log(USAGE);
return;
}
const config = loadConfig(values.config);
const key = values.session ?? sessionKey('steward', 'main', 'terminal');
switch (command) {
case 'doctor':
return doctor(config);
case 'ask':
return ask(config, rest.join(' '));
case 'chat':
return values.ephemeral
? chatEphemeral(config)
: run(config, values.session, { web: false, terminal: true });
case 'serve':
return run(config, undefined, {
web: true,
terminal: Boolean(process.stdin.isTTY) && !values['no-terminal'],
});
case 'jobs':
return jobsCommand(config, rest);
case 'eval':
return evalCommand(config, rest[0], Number(values.repeat ?? 1));
case 'backup':
return backupCommand(config, rest[0] ?? '.');
case 'sessions':
return listSessions(config);
case 'show':
return show(config, key);
case 'usage':
return usageReport(config);
case 'init':
return initWorkspace(config);
case 'audit':
return auditTail(config, Number(rest[0] ?? 20));
case 'memory':
return showMemory(config, rest[0]);
default:
console.error(`Unknown command: ${command}\n`);
console.log(USAGE);
process.exitCode = 2;
}
}
async function doctor(config: StewardConfig): Promise<void> {
const ok = (label: string, good: boolean, detail: string) =>
console.log(`${good ? 'ok ' : 'warn'} ${label.padEnd(12)} ${detail}`);
ok('config', true, config.source);
ok('model', true, `${config.model.main} (effort ${config.model.effort})`);
ok('price', Boolean(config.pricing[config.model.main]), `pricing for ${config.model.main}`);
ok('persona', existsSync(config.paths.persona), config.paths.persona);
ok('rules', existsSync(config.paths.rules), config.paths.rules);
ok('data dir', true, `${config.paths.dataDir} (created on first use)`);
const workspace = new Workspace(config.paths.workspace);
const hasWorkspace = await workspace.exists();
ok(
'workspace',
hasWorkspace,
hasWorkspace ? workspace.root : `${workspace.root} missing; run \`steward init\``,
);
ok('time zone', true, config.owner.timezone);
ok(
'policy',
config.policy.rules.length > 0,
`${config.policy.rules.length} rule(s), default ${config.policy.default}`,
);
const hasEnvKey = Boolean(process.env.ANTHROPIC_API_KEY || process.env.ANTHROPIC_AUTH_TOKEN);
ok(
'credentials',
hasEnvKey,
hasEnvKey
? 'found in the environment'
: 'no ANTHROPIC_API_KEY; the SDK will try an `ant auth login` profile',
);
}
/** Lab 00: one call, nothing remembered, no tools. */
async function ask(config: StewardConfig, question: string): Promise<void> {
if (!question) {
console.error('Usage: steward ask "your question"');
process.exitCode = 2;
return;
}
const model = AnthropicModel.fromConfig(config);
const response = await model.complete(
{
system: [{ type: 'text', text: 'You are a helpful assistant.' }],
messages: [{ role: 'user', content: question }],
tools: [],
},
{ onText: (delta) => process.stdout.write(delta) },
);
process.stdout.write('\n');
if (response.stop_reason !== 'end_turn') console.log(` (stopped: ${response.stop_reason})`);
}
/** Lab 01: the turn loop with the two time tools; the conversation lives in memory only. */
async function chatEphemeral(config: StewardConfig): Promise<void> {
const model = AnthropicModel.fromConfig(config);
const system = await buildSystemPrompt(config);
let history: BetaMessageParam[] = [];
const total: TurnUsage = {
modelCalls: 0,
inputTokens: 0,
outputTokens: 0,
cacheReadTokens: 0,
cacheWriteTokens: 0,
contextTokens: 0,
};
await runTerminalChat({
assistantName: config.assistant.name,
banner: `${config.assistant.name} (ephemeral: nothing is saved) - model ${model.model}`,
reply: async (text, io) => {
const result = await runTurn({
model,
system,
tools: timeTools,
toolContext: { timezone: config.owner.timezone, now: () => new Date() },
history,
userMessage: { role: 'user', content: text },
maxSteps: config.model.maxStepsPerTurn,
...io,
});
history = [...history, ...result.added];
total.modelCalls += result.usage.modelCalls;
total.inputTokens += result.usage.inputTokens;
total.outputTokens += result.usage.outputTokens;
total.cacheReadTokens += result.usage.cacheReadTokens;
total.cacheWriteTokens += result.usage.cacheWriteTokens;
return result;
},
newConversation: async () => {
history = [];
return 'Started a new conversation.';
},
usage: () => formatUsage(total),
});
}
/**
* Labs 02-12: the full assistant behind the gateway.
* steward chat terminal + scheduler
* steward serve web chat + scheduler (+ terminal when run in a terminal)
*/
async function run(
config: StewardConfig,
key: string | undefined,
mode: { web: boolean; terminal: boolean },
): Promise<void> {
const lock = new ProcessLock(config.paths.dataDir);
await lock.acquire();
const app = await createApp(config, {
...(process.env.STEWARD_RECORD ? { recordTo: process.env.STEWARD_RECORD } : {}),
});
const gateway = new Gateway(app);
const log = (line: string) => console.log(`[${new Date().toISOString()}] ${line}`);
// Scheduler (lab 09).
await app.jobs.syncOwnerJobs(config.scheduler.jobs, new Date(), config.owner.timezone);
const scheduler = config.scheduler.enabled
? new Scheduler({
store: app.jobs,
gateway,
timezone: config.owner.timezone,
catchUpHours: config.scheduler.catchUpHours,
log: mode.terminal ? undefined : log,
})
: undefined;
await scheduler?.start();
// Web channel (lab 08).
let server: ServerType | undefined;
if (mode.web && config.web.enabled) {
const configured = config.web.token || process.env.STEWARD_WEB_TOKEN || '';
const token = configured || randomBytes(24).toString('base64url');
const adapter = new WebAdapter();
gateway.register(adapter);
const web = createWebApp(gateway, adapter, {
token,
host: config.web.host,
port: config.web.port,
health: async () => ({
scheduler: scheduler
? { lastTick: scheduler.lastTick ?? null, nextDue: (await scheduler.nextDue()) ?? null }
: 'disabled',
spendTodayUsd: Number((await app.ledger.today()).toFixed(4)),
dailyLimitUsd: config.limits.dailyUsd,
}),
});
server = serve({ fetch: web.fetch, hostname: config.web.host, port: config.web.port });
log(`web chat on http://${config.web.host}:${config.web.port}`);
if (!configured) log(`web token (this run only): ${token}`);
}
// Graceful shutdown (lab 12): stop the clock, stop accepting requests, cancel and record
// turns in flight, release the lock.
let closing: Promise<void> | undefined;
const shutdown = (reason: string) =>
(closing ??= (async () => {
log(`shutting down (${reason})`);
scheduler?.stop();
server?.close();
await gateway.close();
await lock.release();
})());
process.once('SIGTERM', () => void shutdown('SIGTERM').then(() => process.exit(0)));
if (mode.terminal) {
const terminal = new TerminalAdapter();
gateway.register(terminal);
const channelKey = key ?? gateway.sessionKeyFor('terminal');
let session = await gateway.session(channelKey);
const recovery = gateway.recovery(channelKey);
const notes: string[] = [];
if (recovery?.sealedTornLine) notes.push('closed a torn last line in the log');
if (recovery?.skippedLines) notes.push(`${recovery.skippedLines} unreadable line(s) skipped`);
if (recovery?.interruptedTurn) {
notes.push(`${recovery.interruptedTurn} was interrupted last time`);
}
const earlier = session.messages().filter((m) => m.role === 'user').length;
const jobs = (await app.jobs.list()).filter((j) => j.enabled).length;
await runTerminalChat({
assistantName: config.assistant.name,
banner:
`${config.assistant.name} - session ${session.key} (${session.id}), ` +
`${earlier} earlier message(s) - model ${app.model.model}\n` +
`workspace ${app.workspace.root}; ${jobs} scheduled job(s)` +
(notes.length > 0 ? `\nRecovery: ${notes.join('; ')}` : ''),
reply: (text, io) =>
key
? gateway.runInSession(key, 'terminal', text, io)
: gateway.handleMessage({ channel: 'terminal', sender: 'owner', text }, io),
newConversation: async () => {
session = await gateway.newConversation('terminal', key);
return `Started session ${session.id}. The previous one is kept on disk; memory is kept too.`;
},
usage: async () => describeUsage(session, config, await app.ledger.today()),
approvals: {
pending: () => gateway.pendingApprovals(),
answer: (approvalId, decision, always, io) =>
gateway.answerApproval(approvalId, decision, {
channel: 'terminal',
sender: 'owner',
always,
...io,
}),
},
});
await shutdown('terminal closed');
return;
}
process.once('SIGINT', () => void shutdown('SIGINT').then(() => process.exit(0)));
log('running; press Ctrl+C to stop');
await new Promise<never>(() => undefined);
}
function describeUsage(session: Session, config: StewardConfig, todayUsd?: number): string {
const usage = session.usage();
const cost = totalCost(session.billedTurns(), config.pricing);
const context = usage.contextTokens ?? 0;
const trigger = config.context.compaction.triggerTokens;
return [
formatUsage(usage),
`cache hit rate ${(cacheHitRate(usage) * 100).toFixed(0)}% of input tokens`,
`cost ${formatUsd(cost.usd)}` +
(cost.unpriced > 0 ? ` (+${cost.unpriced} unpriced turn(s))` : ''),
`context ${context} tokens in the last request` +
(config.context.compaction.enabled ? ` (compaction at ${trigger})` : ''),
...(todayUsd !== undefined
? [
`spent today ${formatUsd(todayUsd)}` +
(config.limits.dailyUsd > 0
? ` of ${formatUsd(config.limits.dailyUsd)} daily limit`
: ''),
]
: []),
].join('\n');
}
async function listSessions(config: StewardConfig): Promise<void> {
const store = new SessionStore(config.paths.dataDir);
const sessions = await store.list();
if (sessions.length === 0) {
console.log(`No sessions yet in ${store.dir}`);
return;
}
for (const s of sessions) {
console.log(`${s.key.padEnd(28)} current ${s.current} (${s.previous} earlier)`);
}
}
async function usageReport(config: StewardConfig): Promise<void> {
const store = new SessionStore(config.paths.dataDir);
const sessions = await store.list();
if (sessions.length === 0) {
console.log('No sessions yet.');
return;
}
for (const s of sessions) {
const session = await store.peek(s.key);
if (!session) continue;
const report = describeUsage(session, config).split('\n').join('\n ');
console.log(`${s.key} (${s.current})\n ${report}`);
}
}
function describeBlock(block: { type: string } & Record<string, unknown>): string {
switch (block.type) {
case 'text':
return String(block.text).replace(/\n/g, ' ');
case 'tool_use':
return `[tool_use ${String(block.name)} ${JSON.stringify(block.input).slice(0, 120)}]`;
case 'tool_result':
return `[tool_result${block.is_error ? ' error' : ''}]`;
default:
return `[${block.type}]`;
}
}
async function show(config: StewardConfig, key: string): Promise<void> {
const store = new SessionStore(config.paths.dataDir);
const session = await store.peek(key);
if (!session) {
console.log(`No session ${key}. See: steward sessions`);
return;
}
console.log(`Session ${session.key} (${session.id}) - ${store.fileFor(session.id)}\n`);
for (const event of session.history()) {
let detail = '';
switch (event.type) {
case 'message': {
const content = event.message.content;
const summary =
typeof content === 'string'
? content
: (content ?? [])
.map((b) =>
describeBlock(b as unknown as { type: string } & Record<string, unknown>),
)
.join(' ');
console.log(`${event.ts} ${event.turnId} ${event.message.role.padEnd(9)} ${summary}`);
continue;
}
case 'turn_completed':
detail = `${event.stop}, ${formatUsage(event.usage)}`;
break;
case 'turn_interrupted':
detail = event.reason;
break;
case 'turn_started':
detail = `via ${event.channel}`;
break;
case 'approval_requested':
detail = `[${event.approvalId}] ${event.summary}`;
break;
case 'approval_resolved':
detail = `[${event.approvalId}] ${event.decision} by ${event.by}`;
break;
}
console.log(`${event.ts} ${event.type} ${detail}`);
}
}
async function initWorkspace(config: StewardConfig): Promise<void> {
const workspace = new Workspace(config.paths.workspace);
const source = path.join(LAB_ROOT, 'examples', 'workspace');
if ((await workspace.exists()) && (await readdir(workspace.root)).length > 0) {
console.log(`${workspace.root} is not empty; nothing copied.`);
return;
}
await cp(source, workspace.root, { recursive: true, errorOnExist: false, force: false });
console.log(`Copied the example study workspace to ${workspace.root}`);
}
async function auditTail(config: StewardConfig, count: number): Promise<void> {
const limit = Number.isFinite(count) && count > 0 ? count : 20;
const entries = await new AuditLog(config.paths.dataDir).tail(limit);
if (entries.length === 0) {
console.log('No tool calls recorded yet.');
return;
}
for (const e of entries) {
const ms = e.ms !== undefined ? ` ${e.ms}ms` : '';
const summary = e.summary.split('\n')[0];
console.log(`${e.ts} ${e.decision.padEnd(15)} ${e.outcome.padEnd(8)} ${summary}${ms}`);
console.log(`${' '.repeat(26)}${e.session}: ${e.reason}`);
}
}
async function showMemory(config: StewardConfig, entry?: string): Promise<void> {
const memory = new MemoryStore(config.paths.dataDir);
if (entry) {
console.log(await memory.view(entry.startsWith('/') ? entry : `/memories/${entry}`));
return;
}
const files = await memory.listFiles();
console.log(files.length > 0 ? files.join('\n') : `Memory is empty (${memory.dir}).`);
}
async function jobsCommand(config: StewardConfig, args: string[]): Promise<void> {
const app = await createApp(config);
const lock = new ProcessLock(config.paths.dataDir);
const syncOwnerJobs = () =>
app.jobs.syncOwnerJobs(config.scheduler.jobs, new Date(), config.owner.timezone);
if (args[0] === 'run' && args[1]) {
await lock.acquire();
try {
await syncOwnerJobs();
const job = await app.jobs.get(args[1]);
if (!job) throw new Error(`no job "${args[1]}"`);
const gateway = new Gateway(app);
gateway.register(new TerminalAdapter());
const scheduler = new Scheduler({
store: app.jobs,
gateway,
timezone: config.owner.timezone,
catchUpHours: config.scheduler.catchUpHours,
});
// Only this job, even if others are due: they run when the scheduler next ticks.
await scheduler.runNow(job.id);
await gateway.close();
} finally {
await lock.release();
}
return;
}
// Listing only reads while another Steward process owns the data folder (lab 12): that
// process updates jobs.json itself, and a second writer could undo its changes.
const owned = await lock.acquire().then(
() => true,
(err: unknown) => {
if (err instanceof LockError) return false;
throw err;
},
);
if (owned) {
try {
await syncOwnerJobs();
} finally {
await lock.release();
}
}
const jobs = await app.jobs.list();
if (jobs.length === 0) {
console.log('No scheduled jobs. Add some under scheduler.jobs in your config, or ask Steward.');
return;
}
for (const j of jobs) {
const schedule = j.cron ? `cron "${j.cron}"` : `once at ${j.at}`;
console.log(
`${j.id.padEnd(24)} ${j.enabled ? 'on ' : 'off'} ${j.createdBy.padEnd(9)} ${schedule}\n` +
`${' '.repeat(25)}next ${j.nextRun ?? '-'}; last ${j.lastStatus ?? 'never ran'}`,
);
}
}
async function evalCommand(
config: StewardConfig,
only: string | undefined,
repeat: number,
): Promise<void> {
const scenarios = (await loadScenarios(path.join(LAB_ROOT, 'evals', 'scenarios'))).filter(
(s) => !only || s.name === only,
);
if (scenarios.length === 0) {
console.log(only ? `No scenario named ${only}.` : 'No scenarios found.');
return;
}
const times = Number.isInteger(repeat) && repeat > 0 ? repeat : 1;
console.log(
`Running ${scenarios.length} scenario(s) x${times} against ${config.model.main}. ` +
'This calls the real API and costs money.\n',
);
let totalUsd = 0;
let failures = 0;
for (const scenario of scenarios) {
let passed = 0;
for (let i = 0; i < times; i++) {
const result = await runScenario(scenario, {
baseConfig: config,
model: () => AnthropicModel.fromConfig(config),
subagentModel: () => AnthropicModel.fromConfig(config, 'subagent'),
});
totalUsd += result.usd;
if (result.passed) passed++;
else {
console.log(
` FAIL ${scenario.name} (run ${i + 1})${result.error ? `: ${result.error}` : ''}`,
);
for (const c of result.checks.filter((c) => !c.passed)) {
console.log(` ${c.check}\n -> ${c.detail}`);
}
}
}
if (passed < times) failures++;
console.log(`${passed === times ? 'pass' : 'FAIL'} ${scenario.name} ${passed}/${times}`);
}
console.log(`\ncost ${formatUsd(totalUsd)}`);
if (failures > 0) process.exitCode = 1;
}
async function backupCommand(config: StewardConfig, target: string): Promise<void> {
const folder = await backupDataDir(config.paths.dataDir, target);
console.log(`Backed up ${config.paths.dataDir} to ${folder}`);
}
main().catch((err: unknown) => {
console.error(`steward: ${(err as Error).message}`);
process.exitCode = 1;
});