refactor: переименовать Pi Retro в Pi Supervisor
This commit is contained in:
@@ -0,0 +1,220 @@
|
||||
import type { Api, Model } from '@earendil-works/pi-ai';
|
||||
import type {
|
||||
ExtensionAPI,
|
||||
ExtensionCommandContext,
|
||||
ExtensionContext,
|
||||
ExtensionUIContext,
|
||||
} from '@earendil-works/pi-coding-agent';
|
||||
import { captureSession } from './evidence.ts';
|
||||
import { requireLocalEndpoint } from './endpoint.ts';
|
||||
import { SupervisorObserver } from './observer.ts';
|
||||
import { pauseReason } from './types.ts';
|
||||
import type { ObserverState, PauseReason } from './types.ts';
|
||||
import { HELP, REASONS, reportLines, stateLabel, statusText } from './ui.ts';
|
||||
|
||||
export { isLocalEndpoint } from './endpoint.ts';
|
||||
|
||||
function selectModel(ctx: ExtensionContext, requested: string | undefined): Model<Api> | undefined {
|
||||
if (requested === undefined) {
|
||||
return ctx.model;
|
||||
}
|
||||
const slash = requested.indexOf('/');
|
||||
return slash > 0
|
||||
? ctx.modelRegistry.find(requested.slice(0, slash), requested.slice(slash + 1))
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function createObserver(
|
||||
model: Model<Api>,
|
||||
registry: ExtensionContext['modelRegistry'],
|
||||
onChange: (state: ObserverState) => void,
|
||||
): SupervisorObserver {
|
||||
return new SupervisorObserver({
|
||||
contextWindow: model.contextWindow,
|
||||
maxOutputTokens: Math.min(4096, model.maxTokens > 0 ? model.maxTokens : 4096),
|
||||
onChange,
|
||||
request: async ({ systemPrompt, messages, signal, sessionId, maxTokens }) => {
|
||||
await requireLocalEndpoint(registry, model);
|
||||
signal.throwIfAborted();
|
||||
return registry.complete(
|
||||
model,
|
||||
{ systemPrompt, messages },
|
||||
{
|
||||
signal,
|
||||
sessionId,
|
||||
maxTokens,
|
||||
cacheRetention: 'long',
|
||||
},
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
class SupervisorController {
|
||||
observer: SupervisorObserver | undefined;
|
||||
ui: ExtensionUIContext | undefined;
|
||||
visible = false;
|
||||
startToken = 0;
|
||||
modelName = '';
|
||||
lastPause: PauseReason | '' = '';
|
||||
|
||||
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): Promise<void> {
|
||||
const token = ++this.startToken;
|
||||
const model = selectModel(ctx, requested);
|
||||
if (!model) {
|
||||
ctx.ui.notify(
|
||||
'Модель не найдена. Укажи /supervisor start provider/model из настроенных моделей Pi.',
|
||||
'warning',
|
||||
);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await requireLocalEndpoint(ctx.modelRegistry, model);
|
||||
if (token !== this.startToken) {
|
||||
return;
|
||||
}
|
||||
const fixedModel = structuredClone(model);
|
||||
const next = createObserver(fixedModel, ctx.modelRegistry, (state) => {
|
||||
this.render(state);
|
||||
});
|
||||
this.observer?.stop();
|
||||
this.observer = next;
|
||||
this.ui = ctx.ui;
|
||||
this.lastPause = '';
|
||||
this.modelName = `${fixedModel.provider}/${fixedModel.id}`;
|
||||
this.observer.start(captureSession(ctx));
|
||||
ctx.ui.notify(
|
||||
'Наблюдатель запущен в отдельном контексте. Замечания: /supervisor show.',
|
||||
'info',
|
||||
);
|
||||
} catch (error) {
|
||||
if (token === this.startToken) {
|
||||
ctx.ui.notify(REASONS[pauseReason(error)], 'error');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 '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): void {
|
||||
const controller = new SupervisorController();
|
||||
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 awaits event handlers. Schedule observation without returning its model request.
|
||||
pi.on('agent_settled', (_event, ctx) => {
|
||||
if (controller.observer?.active === true) {
|
||||
controller.observer.offer(captureSession(ctx));
|
||||
}
|
||||
});
|
||||
pi.registerCommand('supervisor', {
|
||||
description: 'Локальный супервизор в отдельном контексте',
|
||||
handler: async (args, ctx) => {
|
||||
await controller.command(args, ctx);
|
||||
},
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user