feat: сохранять настройки и сессии супервизора в Pi 1.4

This commit is contained in:
Suslov-MD
2026-10-25 15:53:47 +03:00
parent ced355b0ee
commit a73e09d5a1
21 changed files with 1134 additions and 142 deletions
+176
View File
@@ -0,0 +1,176 @@
import { chmodSync, mkdirSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { join, resolve } from 'node:path';
import { SessionManager } from '@earendil-works/pi-coding-agent';
import type { ExtensionContext } from '@earendil-works/pi-coding-agent';
import type { Message } from '@earendil-works/pi-ai';
import { isArray, isRecord } from './evidence.ts';
import { parseCheckpoint } from './checkpoint.ts';
import type { SavedObserver } from './checkpoint.ts';
import { readJson, writeJson } from './settings.ts';
import { DISCUSSION_PROMPT, SUPERVISOR_PROMPT } from './prompt.ts';
export const SESSION_MARKER = 'harness-supervisor-session';
const CHECKPOINT_MARKER = 'harness-supervisor-checkpoint';
export interface SessionMetadata {
model: string;
sourceId: string;
sourceFile: string;
sourceTools: string[];
}
export function sessionMetadata(
manager: Pick<ExtensionContext['sessionManager'], 'getBranch'>,
): SessionMetadata | undefined {
const entry = manager
.getBranch()
.findLast((item) => item.type === 'custom' && item.customType === SESSION_MARKER);
if (entry?.type !== 'custom' || !isRecord(entry.data)) {
return undefined;
}
const data = entry.data;
if (
typeof data.model !== 'string' ||
typeof data.sourceId !== 'string' ||
typeof data.sourceFile !== 'string' ||
!isArray(data.sourceTools) ||
!data.sourceTools.every((tool) => typeof tool === 'string')
) {
throw new Error('invalid-checkpoint');
}
return {
model: data.model,
sourceId: data.sourceId,
sourceFile: data.sourceFile,
sourceTools: data.sourceTools,
};
}
export class SupervisorStorage {
readonly root: string;
readonly cwd: string;
readonly sessionDir: string;
manager: SessionManager | undefined;
written = 0;
observerId = '';
constructor(root: string, cwd: string) {
this.root = root;
this.cwd = resolve(cwd);
const encoded = `--${this.cwd.replace(/^[/\\]/, '').replace(/[/\\:]/g, '-')}--`;
this.sessionDir = join(root, 'sessions', encoded);
}
private pointer(sourceId: string): string {
const id = createHash('sha256').update(`${this.cwd}\0${sourceId}`).digest('hex');
return join(this.root, 'supervisor', 'sources', `${id}.json`);
}
latest(sourceId: string): string | undefined {
const value = readJson(this.pointer(sourceId));
if (value === undefined) {
return undefined;
}
if (typeof value !== 'string' || resolve(value, '..') !== resolve(this.sessionDir)) {
throw new Error('invalid-checkpoint');
}
return value;
}
save(saved: SavedObserver, metadata: SessionMetadata): void {
try {
this.persist(saved, metadata);
} catch {
this.manager = undefined;
this.written = 0;
throw new Error('storage-failed');
}
}
private persist(saved: SavedObserver, metadata: SessionMetadata): void {
if (!this.manager || this.observerId !== saved.checkpoint.sessionId) {
mkdirSync(this.sessionDir, { recursive: true, mode: 0o700 });
this.manager = SessionManager.create(this.cwd, this.sessionDir);
this.manager.appendSessionInfo(`Supervisor · ${metadata.model}`);
this.manager.appendCustomEntry(SESSION_MARKER, metadata);
const slash = metadata.model.indexOf('/');
this.manager.appendModelChange(
metadata.model.slice(0, slash),
metadata.model.slice(slash + 1),
);
this.manager.appendMessage({
role: 'system',
content: SUPERVISOR_PROMPT,
timestamp: Date.now(),
});
this.observerId = saved.checkpoint.sessionId;
this.written = 0;
}
for (const message of saved.messages.slice(this.written)) {
this.manager.appendMessage(message);
}
this.manager.appendCustomEntry(SESSION_MARKER, metadata);
this.manager.appendCustomEntry(CHECKPOINT_MARKER, saved.checkpoint);
const file = this.manager.getSessionFile();
if (file === undefined) {
throw new Error('storage-failed');
}
chmodSync(file, 0o600);
writeJson(this.pointer(metadata.sourceId), file);
this.written = saved.messages.length;
}
load(sourceId: string): { saved: SavedObserver; metadata: SessionMetadata } {
const file = this.latest(sourceId);
if (file === undefined) {
throw new Error('no-saved-session');
}
const manager = SessionManager.open(file);
const metadata = sessionMetadata(manager);
const entry = manager
.getBranch()
.findLast((item) => item.type === 'custom' && item.customType === CHECKPOINT_MARKER);
if (!metadata || metadata.sourceId !== sourceId || entry?.type !== 'custom') {
throw new Error('invalid-checkpoint');
}
const checkpoint = parseCheckpoint(entry.data);
const messages: Message[] = [];
for (const item of manager.getBranch(entry.id)) {
if (
item.type === 'message' &&
(item.message.role === 'user' || item.message.role === 'assistant')
) {
messages.push(item.message);
}
}
// A resumed writer starts a new file, preserving the old session and any discussion.
this.manager = undefined;
return { saved: { checkpoint, messages }, metadata };
}
discussion(sourceId: string, sourceFile = ''): string {
const source = this.latest(sourceId);
if (source === undefined) {
throw new Error('no-saved-session');
}
const manager = SessionManager.forkFrom(source, this.cwd, this.sessionDir);
const metadata = sessionMetadata(manager);
if (metadata && sourceFile.length > 0) {
manager.appendCustomEntry(SESSION_MARKER, { ...metadata, sourceFile });
}
manager.appendSessionInfo('Supervisor · обсуждение');
manager.appendMessage({ role: 'system', content: DISCUSSION_PROMPT, timestamp: Date.now() });
manager.appendMessage({
role: 'user',
content:
'Продолжим обсуждение замечаний супервизора. Отвечай обычным текстом, а не JSON. Дождись моего вопроса.',
timestamp: Date.now(),
});
const file = manager.getSessionFile();
if (file === undefined) {
throw new Error('storage-failed');
}
chmodSync(file, 0o600);
return file;
}
}