fork method

  1. @override
Future<Session> fork(
  1. SessionMetadata source, {
  2. required String cwd,
  3. String? entryId,
  4. ForkPosition position = ForkPosition.before,
  5. String? id,
  6. String? parentSessionPath,
  7. Map<String, dynamic>? metadata,
})
override

Forks source into a new session containing a prefix of its tree.

When entryId is given, the fork contains the branch ending at that entry (ForkPosition.at) or everything before it, which requires the entry to be a user message (ForkPosition.before, the default).

Implementation

@override
Future<Session> fork(
  SessionMetadata source, {
  required String cwd,
  String? entryId,
  ForkPosition position = ForkPosition.before,
  String? id,
  String? parentSessionPath,
  Map<String, dynamic>? metadata,
}) async {
  final sourceSession = await open(source);
  final forkedEntries = await _entriesToFork(
    sourceSession.getStorage(),
    entryId,
    position,
  );
  final sessionId = id ?? createSessionId();
  final createdAt = DateTime.now();
  final sessionsRoot = await _getSessionsRoot();
  final cwdDir = _fsOrThrow(
    await _fs.joinPath([sessionsRoot, encodeSessionCwd(cwd)]),
    'Failed to resolve session directory for $cwd',
  );
  _fsOrThrow(
    await _fs.createDir(cwdDir, recursive: true),
    'Failed to create session directory for $cwd',
  );
  final storage = await JsonlSessionStorage.create(
    _fs,
    await _createSessionFilePath(sessionId, createdAt, cwd),
    cwd: cwd,
    sessionId: sessionId,
    parentSessionPath: parentSessionPath ?? source.path,
    metadata: metadata ?? source.metadata,
    ioRetry: _ioRetry,
  );
  for (final entry in forkedEntries) {
    await storage.appendEntry(entry);
  }
  return Session(storage);
}