Files
harness-lab/experiments/pi-supervisor/src/settings.ts
T

118 lines
3.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { randomUUID } from 'node:crypto';
import type { ExtensionCommandContext } from '@earendil-works/pi-coding-agent';
import { isRecord } from './evidence.ts';
import { isLocalEndpoint } from './endpoint.ts';
export interface Settings {
model: string;
timeoutSeconds: number;
maxOutputTokens: number;
}
export const DEFAULT_SETTINGS: Settings = {
model: '',
timeoutSeconds: 240,
maxOutputTokens: 4096,
};
export function readJson(file: string): unknown {
try {
const data: unknown = JSON.parse(readFileSync(file, 'utf8'));
return data;
} catch (error) {
if (isRecord(error) && error.code === 'ENOENT') {
return undefined;
}
throw new Error('storage-failed');
}
}
export function writeJson(file: string, data: unknown): void {
const temporary = `${file}.${randomUUID()}.tmp`;
try {
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
writeFileSync(temporary, JSON.stringify(data), { mode: 0o600, flag: 'wx' });
renameSync(temporary, file);
} finally {
rmSync(temporary, { force: true });
}
}
function positiveInteger(value: unknown): value is number {
return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
}
export function readSettings(root: string): Settings {
const value = readJson(join(root, 'supervisor', 'settings.json'));
if (value === undefined) {
return { ...DEFAULT_SETTINGS };
}
if (
!isRecord(value) ||
typeof value.model !== 'string' ||
!positiveInteger(value.timeoutSeconds) ||
value.timeoutSeconds > 3600 ||
!positiveInteger(value.maxOutputTokens) ||
value.maxOutputTokens > 65536
) {
throw new Error('invalid-settings');
}
return {
model: value.model,
timeoutSeconds: value.timeoutSeconds,
maxOutputTokens: value.maxOutputTokens,
};
}
export async function configure(root: string, ctx: ExtensionCommandContext): Promise<void> {
const settings = readSettings(root);
const choice = await ctx.ui.select('Настройки супервизора', [
`Модель: ${settings.model || 'текущая модель Pi'}`,
`Таймаут: ${String(settings.timeoutSeconds)} с`,
`Лимит ответа: ${String(settings.maxOutputTokens)} токенов`,
]);
if (choice === undefined || choice.length === 0) {
return;
}
const next = await changeSetting(choice, settings, ctx);
if (next) {
writeJson(join(root, 'supervisor', 'settings.json'), next);
ctx.ui.notify('Настройки сохранены. Модель — для start; лимиты — для start и resume.', 'info');
}
}
async function changeSetting(
choice: string,
settings: Settings,
ctx: ExtensionCommandContext,
): Promise<Settings | undefined> {
if (choice.startsWith('Модель:')) {
const models = ctx.modelRegistry
.getAvailable()
.filter((model) => isLocalEndpoint(model.baseUrl));
const selected = await ctx.ui.select('Модель супервизора', [
'Текущая модель Pi',
...models.map((model) => `${model.provider}/${model.id}`),
]);
return selected !== undefined
? { ...settings, model: selected === 'Текущая модель Pi' ? '' : selected }
: undefined;
}
const timeout = choice.startsWith('Таймаут:');
const key = timeout ? 'timeoutSeconds' : 'maxOutputTokens';
const maximum = timeout ? 3600 : 65536;
const input = await ctx.ui.input(
`Введите целое число от 1 до ${String(maximum)}`,
String(settings[key]),
);
if (input === undefined) {
return undefined;
}
const number = Number(input);
if (!positiveInteger(number) || number > maximum) {
throw new Error('invalid-settings');
}
return { ...settings, [key]: number };
}