Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion packages/pi/src/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {
loadPiInterruptedRun,
loadPiSandbox,
loadPiSession,
migratePiSession,
type PiQueue,
type PiSettings,
type StoredSandbox,
Expand Down Expand Up @@ -264,7 +265,8 @@ async function openPiSession(
credentials: credentialSource,
...sessionOptions
} = options;
const stored = await loadPiSession(c.db);
const loaded = await loadPiSession(c.db);
const stored = loaded && (await migratePiSession(c.db, loaded));
const sandbox = sandboxProvider ? lazySandbox(c, sandboxProvider) : undefined;
// A new session takes its working directory from the sandbox, so only its first open connects.
const firstSandbox =
Expand Down
37 changes: 32 additions & 5 deletions packages/pi/src/storage.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import type {
FileEntry,
SessionEntry,
SessionHeader,
SettingsManager,
import {
CURRENT_SESSION_VERSION,
type FileEntry,
migrateSessionEntries,
type SessionEntry,
type SessionHeader,
type SettingsManager,
} from "@earendil-works/pi-coding-agent";
import type { RawAccess } from "rivetkit/db";
import { migrations } from "rivetkit/unstable/migrations";
Expand Down Expand Up @@ -187,6 +189,31 @@ export async function savePiSettings(
);
}

/**
* Brings a session stored by an older `pi-coding-agent` to the current session
* format with Pi's own migration, and rewrites the stored rows in one
* transaction, so later loads read them as they are.
*/
export async function migratePiSession(
db: RawAccess,
stored: StoredPiSession,
): Promise<StoredPiSession> {
if ((stored.header.version ?? 1) >= CURRENT_SESSION_VERSION) return stored;
const entries = structuredClone(toFileEntries(stored));
migrateSessionEntries(entries);
const [header, ...rest] = entries as [SessionHeader, ...SessionEntry[]];
await db.transaction(async (tx) => {
await tx.execute(`DELETE FROM pi_entry`);
for (const entry of rest) await appendPiEntry(tx, entry);
await tx.execute(
`UPDATE pi_session SET header_json = ?, updated_at = ? WHERE singleton = 1`,
JSON.stringify(header),
Date.now(),
);
});
return { ...stored, header, entries: rest };
}

/** Builds the entry list `SessionManager.inMemory` expects: header first. */
export function toFileEntries(stored: StoredPiSession): FileEntry[] {
return [stored.header, ...stored.entries];
Expand Down
Loading