Class CopilotSession

java.lang.Object
com.github.copilot.sdk.CopilotSession
All Implemented Interfaces:
AutoCloseable

public final class CopilotSession extends Object implements AutoCloseable
Represents a single conversation session with the Copilot CLI.

A session maintains conversation state, handles events, and manages tool execution. Sessions are created via CopilotClient.createSession(com.github.copilot.sdk.json.SessionConfig) or resumed via CopilotClient.resumeSession(java.lang.String, com.github.copilot.sdk.json.ResumeSessionConfig).

Example Usage


 // Create a session
 var session = client.createSession(new SessionConfig().setModel("gpt-5")).get();

 // Register type-safe event handlers
 session.on(AssistantMessageEvent.class, msg -> {
 	System.out.println(msg.getData().content());
 });
 session.on(SessionIdleEvent.class, idle -> {
 	System.out.println("Session is idle");
 });

 // Send messages
 session.sendAndWait(new MessageOptions().setPrompt("Hello!")).get();

 // Clean up
 session.close();
 
Since:
1.0.0
See Also:
  • Method Details

    • getSessionId

      public String getSessionId()
      Gets the unique identifier for this session.
      Returns:
      the session ID
    • getWorkspacePath

      public String getWorkspacePath()
      Gets the path to the session workspace directory when infinite sessions are enabled.

      The workspace directory contains checkpoints/, plan.md, and files/ subdirectories.

      Returns:
      the workspace path, or null if infinite sessions are disabled
    • setEventErrorHandler

      public void setEventErrorHandler(EventErrorHandler handler)
      Sets a custom error handler for exceptions thrown by event handlers.

      When an event handler registered via on(Consumer) or on(Class, Consumer) throws an exception during event dispatch, the error handler is invoked with the event and exception. The error is always logged at Level.WARNING regardless of whether a custom handler is set.

      Whether dispatch continues or stops after an error is controlled by the EventErrorPolicy set via setEventErrorPolicy(com.github.copilot.sdk.EventErrorPolicy). The error handler is always invoked regardless of the policy.

      If the error handler itself throws an exception, that exception is caught and logged at Level.SEVERE, and dispatch is stopped regardless of the configured policy.

      Example:

      
       session.setEventErrorHandler((event, exception) -> {
       	metrics.increment("handler.errors");
       	logger.error("Handler failed on {}: {}", event.getType(), exception.getMessage());
       });
       
      Parameters:
      handler - the error handler, or null to use only the default logging behavior
      Throws:
      IllegalStateException - if this session has been terminated
      Since:
      1.0.8
      See Also:
    • setEventErrorPolicy

      public void setEventErrorPolicy(EventErrorPolicy policy)
      Sets the error propagation policy for event dispatch.

      Controls whether remaining event listeners continue to execute when a preceding listener throws an exception. Errors are always logged at Level.WARNING regardless of the policy.

      The configured EventErrorHandler (if any) is always invoked regardless of the policy.

      Example:

      
       // Opt-in to suppress errors (continue dispatching despite errors)
       session.setEventErrorPolicy(EventErrorPolicy.SUPPRESS_AND_LOG_ERRORS);
       session.setEventErrorHandler((event, ex) -> logger.error("Handler failed, continuing: {}", ex.getMessage(), ex));
       
      Parameters:
      policy - the error policy (default is EventErrorPolicy.PROPAGATE_AND_LOG_ERRORS)
      Throws:
      IllegalStateException - if this session has been terminated
      Since:
      1.0.8
      See Also:
    • send

      public CompletableFuture<String> send(String prompt)
      Sends a simple text message to the Copilot session.

      This is a convenience method equivalent to send(new MessageOptions().setPrompt(prompt)).

      Parameters:
      prompt - the message text to send
      Returns:
      a future that resolves with the message ID assigned by the server
      Throws:
      IllegalStateException - if this session has been terminated
      See Also:
    • sendAndWait

      public CompletableFuture<AssistantMessageEvent> sendAndWait(String prompt)
      Sends a simple text message and waits until the session becomes idle.

      This is a convenience method equivalent to sendAndWait(new MessageOptions().setPrompt(prompt)).

      Parameters:
      prompt - the message text to send
      Returns:
      a future that resolves with the final assistant message event, or null if no assistant message was received
      Throws:
      IllegalStateException - if this session has been terminated
      See Also:
    • send

      public CompletableFuture<String> send(MessageOptions options)
      Sends a message to the Copilot session.

      This method sends a message asynchronously and returns immediately. Use sendAndWait(MessageOptions) to wait for the response.

      Parameters:
      options - the message options containing the prompt and attachments
      Returns:
      a future that resolves with the message ID assigned by the server
      Throws:
      IllegalStateException - if this session has been terminated
      See Also:
    • sendAndWait

      public CompletableFuture<AssistantMessageEvent> sendAndWait(MessageOptions options, long timeoutMs)
      Sends a message and waits until the session becomes idle.

      This method blocks until the assistant finishes processing the message or until the timeout expires. It's suitable for simple request/response interactions where you don't need to process streaming events.

      Parameters:
      options - the message options containing the prompt and attachments
      timeoutMs - timeout in milliseconds (0 or negative for no timeout)
      Returns:
      a future that resolves with the final assistant message event, or null if no assistant message was received. The future completes exceptionally with a TimeoutException if the timeout expires.
      Throws:
      IllegalStateException - if this session has been terminated
      See Also:
    • sendAndWait

      Sends a message and waits until the session becomes idle with default 60 second timeout.
      Parameters:
      options - the message options containing the prompt and attachments
      Returns:
      a future that resolves with the final assistant message event, or null if no assistant message was received
      Throws:
      IllegalStateException - if this session has been terminated
      See Also:
    • on

      public Closeable on(Consumer<AbstractSessionEvent> handler)
      Registers a callback for all session events.

      The handler will be invoked for every event in this session, including assistant messages, tool calls, and session state changes. For type-safe handling of specific event types, prefer on(Class, Consumer) instead.

      Exception handling: If a handler throws an exception, the error is routed to the configured EventErrorHandler (if set). Whether remaining handlers execute depends on the configured EventErrorPolicy.

      Example:

      
       // Collect all events
       var events = new ArrayList<AbstractSessionEvent>();
       session.on(events::add);
       
      Parameters:
      handler - a callback to be invoked when a session event occurs
      Returns:
      a Closeable that, when closed, unsubscribes the handler
      Throws:
      IllegalStateException - if this session has been terminated
      See Also:
    • on

      public <T extends AbstractSessionEvent> Closeable on(Class<T> eventType, Consumer<T> handler)
      Registers an event handler for a specific event type.

      This provides a type-safe way to handle specific events without needing instanceof checks. The handler will only be called for events matching the specified type.

      Exception handling: If a handler throws an exception, the error is routed to the configured EventErrorHandler (if set). Whether remaining handlers execute depends on the configured EventErrorPolicy.

      Example Usage

      
       // Handle assistant messages
       session.on(AssistantMessageEvent.class, msg -> {
       	System.out.println(msg.getData().content());
       });
      
       // Handle session idle
       session.on(SessionIdleEvent.class, idle -> {
       	done.complete(null);
       });
      
       // Handle streaming deltas
       session.on(AssistantMessageDeltaEvent.class, delta -> {
       	System.out.print(delta.getData().deltaContent());
       });
       
      Type Parameters:
      T - the event type
      Parameters:
      eventType - the class of the event to listen for
      handler - a callback invoked when events of this type occur
      Returns:
      a Closeable that unsubscribes the handler when closed
      Throws:
      IllegalStateException - if this session has been terminated
      See Also:
    • getMessages

      Gets the complete list of messages and events in the session.

      This retrieves the full conversation history, including all user messages, assistant responses, tool invocations, and other session events.

      Returns:
      a future that resolves with a list of all session events
      Throws:
      IllegalStateException - if this session has been terminated
      See Also:
    • abort

      public CompletableFuture<Void> abort()
      Aborts the currently processing message in this session.

      Use this to cancel a long-running operation or stop the assistant from continuing to generate a response.

      Returns:
      a future that completes when the abort is acknowledged
      Throws:
      IllegalStateException - if this session has been terminated
    • close

      public void close()
      Disposes the session and releases all associated resources.

      This destroys the session on the server, clears all event handlers, and releases tool and permission handlers. After calling this method, the session cannot be used again. Subsequent calls to this method have no effect.

      Specified by:
      close in interface AutoCloseable