Skip to main content

C# SDK: Sessions

Manage CLI sessions with full lifecycle control using the C# SDK for .NET.

Overview

The sessions resource provides complete lifecycle management for CLI sessions. Sessions organize memories into trackable contexts with states (active, paused, completed) and automatic memory counting.

Sessions were added in SDK v1.5.0. Ensure you're using the latest version to access this functionality. All methods are fully async with nullable reference type support.

Create Session

CreateSession.cs
using Trix;

using var client = new TrixClient(
    apiKey: Environment.GetEnvironmentVariable("TRIX_API_KEY")
);

// Create a simple conversation session
var session = await client.Sessions.CreateAsync(
    "Customer Support Chat"
);

Console.WriteLine($"Created session: {session.Id}");
Console.WriteLine($"Status: {session.Status}");

// Create a project session with full metadata
var project = await client.Sessions.CreateAsync(
    new CreateCliSessionRequest
    {
        Name = "Q4 Feature Development",
        Type = SessionType.Project,
        Description = "New analytics dashboard features",
        Tags = new List<string> { "q4", "analytics", "frontend" },
        SpaceId = "spc_abc123",
        RetentionPolicy = RetentionPolicy.Permanent,
        IsPrivate = false,
        Metadata = new Dictionary<string, object>
        {
            { "team", "engineering" },
            { "priority", "high" }
        }
    }
);

Create Overloads

CreateOverloads.cs
// Simplified: name only
var session1 = await client.Sessions.CreateAsync("Session Name");

// Simplified: name and description
var session2 = await client.Sessions.CreateAsync(
    "Session Name",
    "Optional description"
);

// Full control: use CreateCliSessionRequest
var session3 = await client.Sessions.CreateAsync(
    new CreateCliSessionRequest { /* full options */ }
);

Create Parameters

PropertyTypeDescription
NamestringSession name (required, max 200 chars)
TypeSessionTypeConversation, Project, Task, or Temporary
Descriptionstring?Detailed description (max 1000 chars)
TagsList<string>Tags for organization (max 10 tags)
SpaceIdstring?Associate session with a space
RetentionPolicyRetentionPolicyPermanent, Temporary, AutoDelete, OnCompletion
RetentionDaysint?Days before auto-deletion
IsPrivateboolPrivate sessions visible only to creator
MetadataDictionaryCustom key-value metadata

List and Filter Sessions

ListSessions.cs
// List all sessions
var response = await client.Sessions.ListAsync();

Console.WriteLine($"Found {response.Data.Count} sessions");

// Filter by status and type
var activeSessions = await client.Sessions.ListAsync(
    new ListCliSessionsParams
    {
        Status = SessionStatus.Active,
        Type = SessionType.Project,
        Limit = 20
    }
);

// Search sessions
var found = await client.Sessions.ListAsync(
    new ListCliSessionsParams
    {
        Search = "customer support",
        Tags = new List<string> { "q4", "frontend" }
    }
);

// Sort by last active
var recent = await client.Sessions.ListAsync(
    new ListCliSessionsParams
    {
        SortBy = "last_active_at",
        SortOrder = "desc",
        Limit = 10
    }
);

List Parameters

PropertyTypeDescription
StatusSessionStatus?Filter by Active, Paused, Completed, Archived
TypeSessionType?Filter by session type
SpaceIdstring?Filter by space
TagsList<string>Filter by tags
Searchstring?Search name and description
Limitint?Results per page (default: 20, max: 100)
SortBystring?"created_at", "updated_at", "last_active_at", "name"
SortOrderstring?"asc" or "desc"

Get Session

GetSession.cs
// Get session by ID
var session = await client.Sessions.GetAsync("sess_abc123");

Console.WriteLine(session.Name);
Console.WriteLine($"Status: {session.Status}");
Console.WriteLine($"Memories: {session.MemoryCount}");
Console.WriteLine($"Messages: {session.MessageCount}");

// Access timestamps
Console.WriteLine($"Created: {session.CreatedAt}");
Console.WriteLine($"Last active: {session.LastActiveAt}");

Update Session

UpdateSession.cs
// Update session metadata
var updated = await client.Sessions.UpdateAsync(
    "sess_abc123",
    new UpdateCliSessionRequest
    {
        Description = "Updated project description",
        Tags = new List<string> { "q4", "analytics", "frontend", "high-priority" },
        Metadata = new Dictionary<string, object>
        {
            { "status", "in-progress" },
            { "assignee", "engineering-team" }
        }
    }
);

Console.WriteLine($"Session updated: {updated.Name}");

Only provided fields are updated. Omitted fields remain unchanged.

Lifecycle Management

Manage session state transitions: Active → Paused → Active → Completed

Pause Session

PauseSession.cs
// Pause an active session
var paused = await client.Sessions.PauseAsync("sess_abc123");

Console.WriteLine(paused.Status);   // Paused
Console.WriteLine(paused.PausedAt); // DateTime

Paused sessions cannot accept new memories. Pause sessions when taking a break to prevent accidental additions.

Resume Session

ResumeSession.cs
// Resume a paused session
var resumed = await client.Sessions.ResumeAsync("sess_abc123");

Console.WriteLine(resumed.Status);   // Active
Console.WriteLine(resumed.PausedAt); // null

Complete Session

CompleteSession.cs
// Complete with summary
var completed = await client.Sessions.CompleteAsync(
    "sess_abc123",
    new CompleteCliSessionRequest
    {
        Summary = "Successfully launched Q4 campaigns with 15% increase in engagement"
    }
);

Console.WriteLine(completed.Status);      // Completed
Console.WriteLine(completed.CompletedAt); // DateTime
Console.WriteLine(completed.Summary);

// Complete without summary
var done = await client.Sessions.CompleteAsync("sess_def456");

Completed sessions are read-only. They cannot be reopened or modified.

Delete Session

DeleteSession.cs
// Permanently delete a session
await client.Sessions.DeleteAsync("sess_abc123");

Console.WriteLine("Session deleted");

Deleting a session permanently removes it and all associated memories. Consider completing or archiving instead.

Get Active Sessions

GetActiveSessions.cs
// Get currently active sessions
var response = await client.Sessions.GetActiveAsync();

Console.WriteLine($"{response.Data.Count} active sessions");

// Process active sessions
foreach (var session in response.Data)
{
    Console.WriteLine($"{session.Name}: {session.MemoryCount} memories");
}

Get Statistics

GetStats.cs
// Get session statistics
var stats = await client.Sessions.GetStatsAsync();

Console.WriteLine($"Total sessions: {stats.Total}");
Console.WriteLine($"Active: {stats.Active}");
Console.WriteLine($"Paused: {stats.Paused}");
Console.WriteLine($"Completed: {stats.Completed}");
Console.WriteLine($"Archived: {stats.Archived}");

if (stats.ByType != null)
{
    Console.WriteLine("By type:");
    foreach (var (type, count) in stats.ByType)
        Console.WriteLine($"  {type}: {count}");
}

Session Memories

GetSessionMemories.cs
// Get memories associated with a session
var response = await client.Sessions.GetMemoriesAsync(
    "sess_abc123",
    limit: 50
);

Console.WriteLine($"Found {response.Data.Count} memories");

// Process session memories
foreach (var memory in response.Data)
{
    Console.WriteLine($"[{memory.CreatedAt}] {memory.Content}");
}

Creating Memories in Sessions

CreateMemoryInSession.cs
// Create memory in a session
await client.Memories.CreateAsync(new CreateMemoryRequest
{
    Content = "Design system uses Material 3",
    SessionId = "sess_abc123"
});

// Session memory count automatically updates
var session = await client.Sessions.GetAsync("sess_abc123");
Console.WriteLine($"Memory count: {session.MemoryCount}");

Complete Workflow Example

CompleteWorkflow.cs
using Trix;

public class ProjectManager
{
    public static async Task ManageProjectAsync()
    {
        using var client = new TrixClient(
            apiKey: Environment.GetEnvironmentVariable("TRIX_API_KEY")
        );

        // 1. Create project session
        var session = await client.Sessions.CreateAsync(
            new CreateCliSessionRequest
            {
                Name = "Mobile App Redesign",
                Type = SessionType.Project,
                Description = "Redesign iOS and Android apps",
                Tags = new List<string> { "mobile", "ui", "q1-2024" },
                SpaceId = "spc_engineering"
            }
        );

        Console.WriteLine($"Created session: {session.Id}");

        // 2. Add memories during work
        await client.Memories.CreateAsync(new CreateMemoryRequest
        {
            Content = "Design system uses Material 3",
            SessionId = session.Id
        });

        await client.Memories.CreateAsync(new CreateMemoryRequest
        {
            Content = "Target: iOS 15+ and Android 12+",
            SessionId = session.Id
        });

        // 3. Pause when taking a break
        await client.Sessions.PauseAsync(session.Id);
        Console.WriteLine("Session paused");

        // ... some time later ...

        // 4. Resume work
        await client.Sessions.ResumeAsync(session.Id);
        Console.WriteLine("Session resumed");

        // 5. Add more work
        await client.Memories.CreateAsync(new CreateMemoryRequest
        {
            Content = "Added dark mode support",
            SessionId = session.Id
        });

        // 6. Complete with summary
        var completed = await client.Sessions.CompleteAsync(
            session.Id,
            new CompleteCliSessionRequest
            {
                Summary = "Successfully launched redesigned apps with 95% positive feedback"
            }
        );

        Console.WriteLine($"Project completed with {completed.MemoryCount} memories");
    }
}

await ProjectManager.ManageProjectAsync();

.NET Types

Types.cs
using Trix.Models;

// Session types enum
public enum SessionType
{
    Conversation,
    Project,
    Task,
    Temporary
}

// Session statuses enum
public enum SessionStatus
{
    Active,
    Paused,
    Completed,
    Archived
}

// Retention policies enum
public enum RetentionPolicy
{
    Permanent,
    Temporary,
    AutoDelete,
    OnCompletion
}

// Full session model
public class CliSession
{
    public string Id { get; set; }
    public string AccountId { get; set; }
    public string UserId { get; set; }
    public string CreatedBy { get; set; }
    public string Name { get; set; }
    public string? Description { get; set; }
    public SessionType Type { get; set; }
    public SessionStatus Status { get; set; }
    public string? SpaceId { get; set; }
    public string? OriginType { get; set; }
    public List<string>? Tags { get; set; }
    public RetentionPolicy RetentionPolicy { get; set; }
    public int? RetentionDays { get; set; }
    public string? Summary { get; set; }
    public bool IsPrivate { get; set; }
    public int MessageCount { get; set; }
    public int MemoryCount { get; set; }
    public Dictionary<string, object>? Metadata { get; set; }
    public DateTime CreatedAt { get; set; }
    public DateTime UpdatedAt { get; set; }
    public DateTime LastActiveAt { get; set; }
    public DateTime? PausedAt { get; set; }
    public DateTime? CompletedAt { get; set; }
    public DateTime? ArchivedAt { get; set; }
}

Error Handling

ErrorHandling.cs
using Trix;

try
{
    // Try to pause a completed session
    await client.Sessions.PauseAsync("sess_abc123");
}
catch (TrixException error)
{
    if (error.StatusCode == 409)
    {
        Console.WriteLine("Invalid state transition");
        Console.WriteLine("Session may already be paused or completed");
    }
    else if (error.StatusCode == 404)
    {
        Console.WriteLine("Session not found");
    }
    else
    {
        Console.WriteLine($"Error: {error.Message}");
    }
}

Best Practices

  • Use using statements: Always dispose of TrixClient properly
  • Null-safety: Use nullable reference types (enabled by default)
  • Descriptive names: Use clear, searchable session names
  • Use appropriate types: Choose the session type that matches your use case
  • Tag consistently: Establish tagging conventions for your team
  • Pause inactive sessions: Prevent accidental memory additions
  • Add summaries: Include completion summaries for future reference
  • Set retention policies: Use temporary sessions for ephemeral work
  • Async/await: Use async methods throughout for better performance

Next Steps