Class CopilotSession
- All Implemented Interfaces:
AutoCloseable
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 with a permission handler (required)
var session = client
.createSession(new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL).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();
-
Method Summary
Modifier and TypeMethodDescriptionabort()Aborts the currently processing message in this session.voidclose()Disposes the session and releases all associated resources.compact()Compacts the session context to reduce token usage.Deselects the currently selected custom agent, returning to the default agent.Gets the currently selected custom agent for this session, ornullif no custom agent is selected.Gets the complete list of messages and events in the session.Gets the unique identifier for this session.Gets the path to the session workspace directory when infinite sessions are enabled.Lists the custom agents available for selection in this session.<T extends AbstractSessionEvent>
CloseableRegisters an event handler for a specific event type.on(Consumer<AbstractSessionEvent> handler) Registers a callback for all session events.selectAgent(String agentName) Selects a custom agent for this session.send(MessageOptions options) Sends a message to the Copilot session.Sends a simple text message to the Copilot session.sendAndWait(MessageOptions options) Sends a message and waits until the session becomes idle with default 60 second timeout.sendAndWait(MessageOptions options, long timeoutMs) Sends a message and waits until the session becomes idle.sendAndWait(String prompt) Sends a simple text message and waits until the session becomes idle.voidsetEventErrorHandler(EventErrorHandler handler) Sets a custom error handler for exceptions thrown by event handlers.voidsetEventErrorPolicy(EventErrorPolicy policy) Sets the error propagation policy for event dispatch.Changes the model for this session.
-
Method Details
-
getSessionId
Gets the unique identifier for this session.- Returns:
- the session ID
-
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
nullif infinite sessions are disabled
-
setEventErrorHandler
Sets a custom error handler for exceptions thrown by event handlers.When an event handler registered via
on(Consumer)oron(Class, Consumer)throws an exception during event dispatch, the error handler is invoked with the event and exception. The error is always logged atLevel.WARNINGregardless of whether a custom handler is set.Whether dispatch continues or stops after an error is controlled by the
EventErrorPolicyset viasetEventErrorPolicy(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, ornullto use only the default logging behavior- Throws:
IllegalStateException- if this session has been terminated- Since:
- 1.0.8
- See Also:
-
setEventErrorPolicy
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.WARNINGregardless of the policy.EventErrorPolicy.PROPAGATE_AND_LOG_ERRORS(default) — log the error and stop dispatch after the first errorEventErrorPolicy.SUPPRESS_AND_LOG_ERRORS— log the error and continue dispatching to all remaining listeners
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 isEventErrorPolicy.PROPAGATE_AND_LOG_ERRORS)- Throws:
IllegalStateException- if this session has been terminated- Since:
- 1.0.8
- See Also:
-
send
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
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
nullif no assistant message was received - Throws:
IllegalStateException- if this session has been terminated- See Also:
-
send
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
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.
The returned future can be cancelled via
Future.cancel(boolean). If cancelled externally, the future completes withCancellationException. If the timeout expires first, the future completes exceptionally with aTimeoutException.- Parameters:
options- the message options containing the prompt and attachmentstimeoutMs- timeout in milliseconds (0 or negative for no timeout)- Returns:
- a future that resolves with the final assistant message event, or
nullif no assistant message was received. The future completes exceptionally with a TimeoutException if the timeout expires, or with CancellationException if cancelled externally. - 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
nullif no assistant message was received - Throws:
IllegalStateException- if this session has been terminated- See Also:
-
on
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 configuredEventErrorPolicy.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
Registers an event handler for a specific event type.This provides a type-safe way to handle specific events without needing
instanceofchecks. 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 configuredEventErrorPolicy.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 forhandler- 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
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
-
setModel
Changes the model for this session.The new model takes effect for the next message. Conversation history is preserved.
session.setModel("gpt-4.1").get();- Parameters:
model- the model ID to switch to (e.g.,"gpt-4.1")- Returns:
- a future that completes when the model switch is acknowledged
- Throws:
IllegalStateException- if this session has been terminated- Since:
- 1.0.11
-
listAgents
Lists the custom agents available for selection in this session.- Returns:
- a future that resolves with the list of available agents
- Throws:
IllegalStateException- if this session has been terminated- Since:
- 1.0.11
-
getCurrentAgent
Gets the currently selected custom agent for this session, ornullif no custom agent is selected.- Returns:
- a future that resolves with the current agent, or
nullif using the default agent - Throws:
IllegalStateException- if this session has been terminated- Since:
- 1.0.11
-
selectAgent
Selects a custom agent for this session.- Parameters:
agentName- the name/identifier of the agent to select- Returns:
- a future that resolves with the selected agent information
- Throws:
IllegalStateException- if this session has been terminated- Since:
- 1.0.11
-
deselectAgent
Deselects the currently selected custom agent, returning to the default agent.- Returns:
- a future that completes when the agent is deselected
- Throws:
IllegalStateException- if this session has been terminated- Since:
- 1.0.11
-
compact
Compacts the session context to reduce token usage.This triggers an immediate session compaction, summarizing the conversation history to free up context window space.
- Returns:
- a future that completes when compaction finishes
- Throws:
IllegalStateException- if this session has been terminated- Since:
- 1.0.11
-
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:
closein interfaceAutoCloseable
-