feat(session): Explicit session id naming (#5076)
This commit is contained in:
@@ -23,6 +23,7 @@ export interface Args {
|
||||
mode?: Mode;
|
||||
noSession?: boolean;
|
||||
session?: string;
|
||||
sessionId?: string;
|
||||
fork?: string;
|
||||
sessionDir?: string;
|
||||
models?: string[];
|
||||
@@ -95,6 +96,8 @@ export function parseArgs(args: string[]): Args {
|
||||
result.noSession = true;
|
||||
} else if (arg === "--session" && i + 1 < args.length) {
|
||||
result.session = args[++i];
|
||||
} else if (arg === "--session-id" && i + 1 < args.length) {
|
||||
result.sessionId = args[++i];
|
||||
} else if (arg === "--fork" && i + 1 < args.length) {
|
||||
result.fork = args[++i];
|
||||
} else if (arg === "--session-dir" && i + 1 < args.length) {
|
||||
@@ -224,6 +227,7 @@ ${chalk.bold("Options:")}
|
||||
--continue, -c Continue previous session
|
||||
--resume, -r Select a session to resume
|
||||
--session <path|id> Use specific session file or partial UUID
|
||||
--session-id <id> Use exact project session ID, creating it if missing
|
||||
--fork <path|id> Fork specific session file or partial UUID into a new session
|
||||
--session-dir <dir> Directory for session storage and lookup
|
||||
--no-session Don't save session (ephemeral)
|
||||
|
||||
@@ -202,6 +202,14 @@ function createSessionId(): string {
|
||||
return uuidv7();
|
||||
}
|
||||
|
||||
export function assertValidSessionId(id: string): void {
|
||||
if (!/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/.test(id)) {
|
||||
throw new Error(
|
||||
"Session id must be non-empty, contain only alphanumeric characters, '-', '_', and '.', and start and end with an alphanumeric character",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Generate a unique short ID (8 hex chars, collision-checked) */
|
||||
function generateId(byId: { has(id: string): boolean }): string {
|
||||
for (let i = 0; i < 100; i++) {
|
||||
@@ -721,7 +729,13 @@ export class SessionManager {
|
||||
private labelTimestampsById: Map<string, string> = new Map();
|
||||
private leafId: string | null = null;
|
||||
|
||||
private constructor(cwd: string, sessionDir: string, sessionFile: string | undefined, persist: boolean) {
|
||||
private constructor(
|
||||
cwd: string,
|
||||
sessionDir: string,
|
||||
sessionFile: string | undefined,
|
||||
persist: boolean,
|
||||
newSessionOptions?: NewSessionOptions,
|
||||
) {
|
||||
this.cwd = resolvePath(cwd);
|
||||
this.sessionDir = normalizePath(sessionDir);
|
||||
this.persist = persist;
|
||||
@@ -732,7 +746,7 @@ export class SessionManager {
|
||||
if (sessionFile) {
|
||||
this.setSessionFile(sessionFile);
|
||||
} else {
|
||||
this.newSession();
|
||||
this.newSession(newSessionOptions);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -770,6 +784,9 @@ export class SessionManager {
|
||||
}
|
||||
|
||||
newSession(options?: NewSessionOptions): string | undefined {
|
||||
if (options?.id !== undefined) {
|
||||
assertValidSessionId(options.id);
|
||||
}
|
||||
this.sessionId = options?.id ?? createSessionId();
|
||||
const timestamp = new Date().toISOString();
|
||||
const header: SessionHeader = {
|
||||
@@ -845,14 +862,23 @@ export class SessionManager {
|
||||
|
||||
const hasAssistant = this.fileEntries.some((e) => e.type === "message" && e.message.role === "assistant");
|
||||
if (!hasAssistant) {
|
||||
// Mark as not flushed so when assistant arrives, all entries get written
|
||||
this.flushed = false;
|
||||
if (this.flushed) {
|
||||
appendFileSync(this.sessionFile, `${JSON.stringify(entry)}\n`);
|
||||
} else {
|
||||
// Mark as not flushed so when assistant arrives, all entries get written
|
||||
this.flushed = false;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.flushed) {
|
||||
for (const e of this.fileEntries) {
|
||||
appendFileSync(this.sessionFile, `${JSON.stringify(e)}\n`);
|
||||
const fd = openSync(this.sessionFile, "wx");
|
||||
try {
|
||||
for (const e of this.fileEntries) {
|
||||
writeFileSync(fd, `${JSON.stringify(e)}\n`);
|
||||
}
|
||||
} finally {
|
||||
closeSync(fd);
|
||||
}
|
||||
this.flushed = true;
|
||||
} else {
|
||||
@@ -1308,9 +1334,9 @@ export class SessionManager {
|
||||
* @param cwd Working directory (stored in session header)
|
||||
* @param sessionDir Optional session directory. If omitted, uses default (~/.pi/agent/sessions/<encoded-cwd>/).
|
||||
*/
|
||||
static create(cwd: string, sessionDir?: string): SessionManager {
|
||||
static create(cwd: string, sessionDir?: string, options?: NewSessionOptions): SessionManager {
|
||||
const dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd);
|
||||
return new SessionManager(cwd, dir, undefined, true);
|
||||
return new SessionManager(cwd, dir, undefined, true, options);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1356,7 +1382,12 @@ export class SessionManager {
|
||||
* @param targetCwd Target working directory (where the new session will be stored)
|
||||
* @param sessionDir Optional session directory. If omitted, uses default for targetCwd.
|
||||
*/
|
||||
static forkFrom(sourcePath: string, targetCwd: string, sessionDir?: string): SessionManager {
|
||||
static forkFrom(
|
||||
sourcePath: string,
|
||||
targetCwd: string,
|
||||
sessionDir?: string,
|
||||
options?: NewSessionOptions,
|
||||
): SessionManager {
|
||||
const resolvedSourcePath = resolvePath(sourcePath);
|
||||
const resolvedTargetCwd = resolvePath(targetCwd);
|
||||
const sourceEntries = loadEntriesFromFile(resolvedSourcePath);
|
||||
@@ -1375,7 +1406,10 @@ export class SessionManager {
|
||||
}
|
||||
|
||||
// Create new session file with new ID but forked content
|
||||
const newSessionId = createSessionId();
|
||||
if (options?.id !== undefined) {
|
||||
assertValidSessionId(options.id);
|
||||
}
|
||||
const newSessionId = options?.id ?? createSessionId();
|
||||
const timestamp = new Date().toISOString();
|
||||
const fileTimestamp = timestamp.replace(/[:.]/g, "-");
|
||||
const newSessionFile = join(dir, `${fileTimestamp}_${newSessionId}.jsonl`);
|
||||
@@ -1389,7 +1423,7 @@ export class SessionManager {
|
||||
cwd: resolvedTargetCwd,
|
||||
parentSession: resolvedSourcePath,
|
||||
};
|
||||
appendFileSync(newSessionFile, `${JSON.stringify(newHeader)}\n`);
|
||||
writeFileSync(newSessionFile, `${JSON.stringify(newHeader)}\n`, { flag: "wx" });
|
||||
|
||||
// Copy all non-header entries from source
|
||||
for (const entry of sourceEntries) {
|
||||
|
||||
@@ -37,7 +37,7 @@ import {
|
||||
MissingSessionCwdError,
|
||||
type SessionCwdIssue,
|
||||
} from "./core/session-cwd.ts";
|
||||
import { SessionManager } from "./core/session-manager.ts";
|
||||
import { assertValidSessionId, SessionManager } from "./core/session-manager.ts";
|
||||
import { SettingsManager } from "./core/settings-manager.ts";
|
||||
import { printTimings, resetTimings, time } from "./core/timings.ts";
|
||||
import { runMigrations, showDeprecationWarnings } from "./migrations.ts";
|
||||
@@ -145,6 +145,16 @@ type ResolvedSession =
|
||||
* Resolve a session argument to a file path.
|
||||
* If it looks like a path, use as-is. Otherwise try to match as session ID prefix.
|
||||
*/
|
||||
async function findLocalSessionByExactId(
|
||||
sessionId: string,
|
||||
cwd: string,
|
||||
sessionDir?: string,
|
||||
): Promise<{ type: "local"; path: string } | undefined> {
|
||||
const localSessions = await SessionManager.list(cwd, sessionDir);
|
||||
const localMatch = localSessions.find((s) => s.id === sessionId);
|
||||
return localMatch ? { type: "local", path: localMatch.path } : undefined;
|
||||
}
|
||||
|
||||
async function resolveSessionPath(sessionArg: string, cwd: string, sessionDir?: string): Promise<ResolvedSession> {
|
||||
// If it looks like a file path, resolve it before handing it to the session manager.
|
||||
if (sessionArg.includes("/") || sessionArg.includes("\\") || sessionArg.endsWith(".jsonl")) {
|
||||
@@ -153,19 +163,20 @@ async function resolveSessionPath(sessionArg: string, cwd: string, sessionDir?:
|
||||
|
||||
// Try to match as session ID in current project first
|
||||
const localSessions = await SessionManager.list(cwd, sessionDir);
|
||||
const localMatches = localSessions.filter((s) => s.id.startsWith(sessionArg));
|
||||
const localMatch =
|
||||
localSessions.find((s) => s.id === sessionArg) ?? localSessions.find((s) => s.id.startsWith(sessionArg));
|
||||
|
||||
if (localMatches.length >= 1) {
|
||||
return { type: "local", path: localMatches[0].path };
|
||||
if (localMatch) {
|
||||
return { type: "local", path: localMatch.path };
|
||||
}
|
||||
|
||||
// Try global search across all projects
|
||||
const allSessions = await SessionManager.listAll();
|
||||
const globalMatches = allSessions.filter((s) => s.id.startsWith(sessionArg));
|
||||
const globalMatch =
|
||||
allSessions.find((s) => s.id === sessionArg) ?? allSessions.find((s) => s.id.startsWith(sessionArg));
|
||||
|
||||
if (globalMatches.length >= 1) {
|
||||
const match = globalMatches[0];
|
||||
return { type: "global", path: match.path, cwd: match.cwd };
|
||||
if (globalMatch) {
|
||||
return { type: "global", path: globalMatch.path, cwd: globalMatch.cwd };
|
||||
}
|
||||
|
||||
// Not found anywhere
|
||||
@@ -202,9 +213,33 @@ function validateForkFlags(parsed: Args): void {
|
||||
}
|
||||
}
|
||||
|
||||
function forkSessionOrExit(sourcePath: string, cwd: string, sessionDir?: string): SessionManager {
|
||||
function validateSessionIdFlags(parsed: Args): void {
|
||||
if (parsed.sessionId === undefined) return;
|
||||
|
||||
const conflictingFlags = [
|
||||
parsed.session ? "--session" : undefined,
|
||||
parsed.continue ? "--continue" : undefined,
|
||||
parsed.resume ? "--resume" : undefined,
|
||||
parsed.noSession ? "--no-session" : undefined,
|
||||
].filter((flag): flag is string => flag !== undefined);
|
||||
|
||||
if (conflictingFlags.length > 0) {
|
||||
console.error(chalk.red(`Error: --session-id cannot be combined with ${conflictingFlags.join(", ")}`));
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
try {
|
||||
return SessionManager.forkFrom(sourcePath, cwd, sessionDir);
|
||||
assertValidSessionId(parsed.sessionId);
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
console.error(chalk.red(`Error: ${message}`));
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
function forkSessionOrExit(sourcePath: string, cwd: string, sessionDir?: string, sessionId?: string): SessionManager {
|
||||
try {
|
||||
return SessionManager.forkFrom(sourcePath, cwd, sessionDir, { id: sessionId });
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
console.error(chalk.red(`Error: ${message}`));
|
||||
@@ -218,18 +253,26 @@ async function createSessionManager(
|
||||
sessionDir: string | undefined,
|
||||
settingsManager: SettingsManager,
|
||||
): Promise<SessionManager> {
|
||||
if (parsed.noSession) {
|
||||
return SessionManager.inMemory();
|
||||
if (parsed.noSession || parsed.help || parsed.listModels !== undefined) {
|
||||
return SessionManager.inMemory(cwd);
|
||||
}
|
||||
|
||||
if (parsed.fork) {
|
||||
if (parsed.sessionId) {
|
||||
const existingTarget = await findLocalSessionByExactId(parsed.sessionId, cwd, sessionDir);
|
||||
if (existingTarget) {
|
||||
console.error(chalk.red(`Session already exists with id '${parsed.sessionId}'`));
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
const resolved = await resolveSessionPath(parsed.fork, cwd, sessionDir);
|
||||
|
||||
switch (resolved.type) {
|
||||
case "path":
|
||||
case "local":
|
||||
case "global":
|
||||
return forkSessionOrExit(resolved.path, cwd, sessionDir);
|
||||
return forkSessionOrExit(resolved.path, cwd, sessionDir, parsed.sessionId);
|
||||
|
||||
case "not_found":
|
||||
console.error(chalk.red(`No session found matching '${resolved.arg}'`));
|
||||
@@ -282,7 +325,14 @@ async function createSessionManager(
|
||||
return SessionManager.continueRecent(cwd, sessionDir);
|
||||
}
|
||||
|
||||
return SessionManager.create(cwd, sessionDir);
|
||||
if (parsed.sessionId) {
|
||||
const existingSession = await findLocalSessionByExactId(parsed.sessionId, cwd, sessionDir);
|
||||
if (existingSession) {
|
||||
return SessionManager.open(existingSession.path, sessionDir);
|
||||
}
|
||||
}
|
||||
|
||||
return SessionManager.create(cwd, sessionDir, { id: parsed.sessionId });
|
||||
}
|
||||
|
||||
function buildSessionOptions(
|
||||
@@ -483,6 +533,7 @@ export async function main(args: string[], options?: MainOptions) {
|
||||
}
|
||||
|
||||
validateForkFlags(parsed);
|
||||
validateSessionIdFlags(parsed);
|
||||
|
||||
// Run migrations (pass cwd for project-local migrations)
|
||||
const { migratedAuthProviders: migratedProviders, deprecationWarnings } = runMigrations(process.cwd());
|
||||
|
||||
Reference in New Issue
Block a user