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

254 lines
7.9 KiB
TypeScript

import { getAgentDir } from '@earendil-works/pi-coding-agent';
import type {
ExtensionAPI,
ExtensionCommandContext,
ExtensionContext,
ExtensionUIContext,
} from '@earendil-works/pi-coding-agent';
import { captureSession } from './evidence.ts';
import { requireLocalEndpoint } from './endpoint.ts';
import type { SupervisorObserver } from './observer.ts';
import type { ObserverState, PauseReason } from './types.ts';
import { HELP, REASONS, reportLines, statusText, stateLabel, commandError } from './ui.ts';
import { configure, readSettings } from './settings.ts';
import { SupervisorStorage, sessionMetadata } from './storage.ts';
import { createObserver, selectModel } from './runtime.ts';
import { registerDiscussion } from './discussion.ts';
export { isLocalEndpoint } from './endpoint.ts';
class SupervisorController {
observer: SupervisorObserver | undefined;
ui: ExtensionUIContext | undefined;
visible = false;
startToken = 0;
modelName = '';
lastPause: PauseReason | '' = '';
readonly root: string;
readonly pi: ExtensionAPI;
constructor(root: string, pi: ExtensionAPI) {
this.root = root;
this.pi = pi;
}
storage(ctx: ExtensionContext): SupervisorStorage {
return new SupervisorStorage(this.root, ctx.cwd);
}
render(state: ObserverState): void {
if (!this.ui) {
return;
}
this.ui.setStatus(
'supervisor',
`Супервизор: ${stateLabel(state)} · ${String(state.report.length)} замечаний`,
);
if (this.visible) {
this.ui.setWidget('supervisor', reportLines(state.report));
}
if (state.paused !== '' && state.paused !== this.lastPause) {
this.ui.notify(
`Супервизор на паузе: ${REASONS[state.paused]}. Повтор: /supervisor run.`,
'warning',
);
}
this.lastPause = state.paused;
}
reset(): void {
this.startToken += 1;
const previousUI = this.ui;
this.ui = undefined;
this.observer?.stop();
this.observer = undefined;
this.visible = false;
this.modelName = '';
this.lastPause = '';
previousUI?.setWidget('supervisor', undefined);
previousUI?.setStatus('supervisor', undefined);
}
async start(
ctx: ExtensionCommandContext,
requested: string | undefined,
resume = false,
): Promise<void> {
if (sessionMetadata(ctx.sessionManager)) {
throw new Error('nested-supervisor');
}
const token = ++this.startToken;
const storage = this.storage(ctx);
const settings = readSettings(this.root);
const saved = resume ? storage.load(ctx.sessionManager.getSessionId()) : undefined;
const model = selectModel(ctx, saved?.metadata.model ?? requested ?? settings.model);
if (!model) {
throw new Error('model-not-found');
}
await requireLocalEndpoint(ctx.modelRegistry, model);
if (token !== this.startToken) {
return;
}
const fixedModel = structuredClone(model);
const metadata = {
model: `${fixedModel.provider}/${fixedModel.id}`,
sourceId: ctx.sessionManager.getSessionId(),
sourceFile: ctx.sessionManager.getSessionFile() ?? '',
sourceTools: [...this.pi.getActiveTools()],
};
const next = createObserver(fixedModel, ctx, settings, storage, metadata, (state) => {
this.render(state);
});
this.observer?.stop();
this.observer = next;
this.ui = ctx.ui;
this.lastPause = '';
this.modelName = metadata.model;
if (saved) {
next.resume(saved.saved, captureSession(ctx));
} else {
next.start(captureSession(ctx));
}
ctx.ui.notify(
'Супервизор включён. Замечания: /supervisor show; обсуждение: /supervisor open.',
'info',
);
}
async open(ctx: ExtensionCommandContext): Promise<void> {
if (sessionMetadata(ctx.sessionManager)) {
return;
}
const storage = this.storage(ctx);
if (storage.latest(ctx.sessionManager.getSessionId()) === undefined) {
throw new Error('no-saved-session');
}
await ctx.waitForIdle();
this.startToken += 1;
this.observer?.stop();
await this.observer?.idle();
const file = storage.discussion(
ctx.sessionManager.getSessionId(),
ctx.sessionManager.getSessionFile() ?? '',
);
ctx.ui.notify('Открываю отдельный диалог супервизора. Возврат: /supervisor back.', 'info');
await ctx.switchSession(file);
}
async back(ctx: ExtensionCommandContext): Promise<void> {
const metadata = sessionMetadata(ctx.sessionManager);
if (metadata === undefined || metadata.sourceFile.length === 0) {
throw new Error('no-source-session');
}
await ctx.waitForIdle();
await ctx.switchSession(metadata.sourceFile);
}
private withObserver(action: string, ctx: ExtensionCommandContext): void {
if (!this.observer) {
ctx.ui.notify(`Наблюдатель выключен. ${HELP}`, 'info');
return;
}
if (action === 'show') {
this.visible = true;
ctx.ui.setWidget('supervisor', reportLines(this.observer.status().report));
} else if (action === 'status') {
ctx.ui.notify(statusText(this.modelName, this.observer.status()), 'info');
} else {
this.updateObserver(action, ctx);
}
}
private updateObserver(action: string, ctx: ExtensionCommandContext): void {
const observer = this.observer;
if (observer?.active !== true) {
ctx.ui.notify('Для нового запуска используй /supervisor start [provider/model].', 'info');
return;
}
if (action === 'clear') {
observer.clear(captureSession(ctx));
ctx.ui.notify(
'История наблюдателя очищена. Следующее наблюдение начнётся с новых событий.',
'info',
);
} else {
observer.retry(captureSession(ctx));
}
}
async command(args: string, ctx: ExtensionCommandContext): Promise<void> {
if (!ctx.hasUI) {
return;
}
const [action = 'status', requested, ...extra] = args.trim().split(/\s+/).filter(Boolean);
if (extra.length > 0 || (requested !== undefined && action !== 'start')) {
ctx.ui.notify(HELP, 'warning');
return;
}
switch (action) {
case 'config':
await configure(this.root, ctx);
break;
case 'resume':
await this.start(ctx, undefined, true);
break;
case 'open':
await this.open(ctx);
break;
case 'back':
await this.back(ctx);
break;
case 'start':
await this.start(ctx, requested);
break;
case 'stop':
this.startToken += 1;
this.observer?.stop();
break;
case 'hide':
this.visible = false;
ctx.ui.setWidget('supervisor', undefined);
break;
case 'run':
case 'show':
case 'status':
case 'clear':
this.withObserver(action, ctx);
break;
default:
ctx.ui.notify(HELP, 'info');
}
}
}
export default function supervisorExtension(pi: ExtensionAPI, root = getAgentDir()): void {
const controller = new SupervisorController(root, pi);
registerDiscussion(pi);
pi.on('session_shutdown', () => {
controller.reset();
});
pi.on('session_start', () => {
controller.reset();
});
pi.on('session_tree', (_event, ctx) => {
if (controller.observer?.active === true) {
controller.observer.start(captureSession(ctx));
}
});
pi.on('agent_settled', (_event, ctx) => {
if (controller.observer?.active === true) {
controller.observer.offer(captureSession(ctx));
}
});
pi.registerCommand('supervisor', {
description: 'Настройки, наблюдение и диалог с локальным супервизором',
handler: async (args, ctx) => {
try {
await controller.command(args, ctx);
} catch (error) {
ctx.ui.notify(commandError(error), 'error');
}
},
});
}