Session lifecycle hooks let you respond to session start and end events. Use them to:
The onSessionStart hook is called when a session begins (new or resumed).
import type { SessionStartHookInput, HookInvocation, SessionStartHookOutput } from "copilot-sdk-supercharged";
type SessionStartHandler = (
input: SessionStartHookInput,
invocation: HookInvocation
) => Promise<SessionStartHookOutput | null | undefined>;
type SessionStartHandler = (
input: SessionStartHookInput,
invocation: HookInvocation
) => Promise<SessionStartHookOutput | null | undefined>;
from copilot.session import SessionStartHookInput, SessionStartHookOutput
from copilot.session import SessionStartHandler as SdkSessionStartHandler
from typing import Callable, Awaitable
SessionStartHandler = Callable[
[SessionStartHookInput, dict[str, str]],
Awaitable[SessionStartHookOutput | None]
]
def check(handler: SessionStartHandler) -> SdkSessionStartHandler:
return handler
SessionStartHandler = Callable[
[SessionStartHookInput, dict[str, str]],
Awaitable[SessionStartHookOutput | None]
]
package main
import copilot "github.com/microsoft/copilot-sdk/go/v2"
// Aliases let the signature below use the package's own type names.
type (
SessionStartHookInput = copilot.SessionStartHookInput
HookInvocation = copilot.HookInvocation
SessionStartHookOutput = copilot.SessionStartHookOutput
)
type SessionStartHandler func(
input SessionStartHookInput,
invocation HookInvocation,
) (*SessionStartHookOutput, error)
var _ = copilot.SessionStartHandler(SessionStartHandler(nil))
func main() {}
type SessionStartHandler func(
input SessionStartHookInput,
invocation HookInvocation,
) (*SessionStartHookOutput, error)
using Microsoft.Copilot;
public delegate Task<SessionStartHookOutput?> SessionStartHandler(
SessionStartHookInput input,
HookInvocation invocation);
static class SessionStartHandlerCheck
{
static SessionHooks Check(SessionStartHandler handler) =>
new() { OnSessionStart = handler.Invoke };
}
public delegate Task<SessionStartHookOutput?> SessionStartHandler(
SessionStartHookInput input,
HookInvocation invocation);
import com.microsoft.copilot.rpc.*;
import java.util.concurrent.CompletableFuture;
public class SessionStartSignature {
static class Documented {
@FunctionalInterface
public interface SessionStartHandler {
CompletableFuture<SessionStartHookOutput> handle(
SessionStartHookInput input,
HookInvocation invocation);
}
}
// The documented interface and the SDK's accept each other's implementations.
static SessionStartHandler toSdk(Documented.SessionStartHandler documented) {
return documented::handle;
}
static Documented.SessionStartHandler fromSdk(SessionStartHandler sdk) {
return sdk::handle;
}
public static void main(String[] args) {}
}
@FunctionalInterface
public interface SessionStartHandler {
CompletableFuture<SessionStartHookOutput> handle(
SessionStartHookInput input,
HookInvocation invocation);
}
40 languages supported. See the full SDK list with cookbooks for Objective-C, F#, Groovy, Julia, COBOL, OCaml, Zig, Nim, D, Erlang, Crystal, Tcl, Solidity, V, and 18 more.
| Field | Type | Description |
|---|---|---|
timestamp | SDK timestamp type | When the hook was triggered |
workingDirectory | string | Current working directory |
source | "startup" | "resume" | "new" | How the session was started |
initialPrompt | string | undefined | The initial prompt if provided |
| Field | Type | Description |
|---|---|---|
additionalContext | string | Context to add at session start |
modifiedConfig | object | Override session configuration |
const session = await client.createSession({
hooks: {
handlers: {
onSessionStart: async (input, invocation) => {
console.log(`Session ${invocation.sessionId} started (${input.source})`);
const projectInfo = await detectProjectType(input.workingDirectory);
return {
additionalContext: `
This is a ${projectInfo.type} project.
Main language: ${projectInfo.language}
Package manager: ${projectInfo.packageManager}
`.trim(),
};
},
},
},
});
from copilot import CopilotClient
from copilot.session import PermissionHandler
async def create_project_session(client: CopilotClient, detect_project_type):
async def on_session_start(input_data, invocation):
print(f"Session {invocation['session_id']} started ({input_data['source']})")
project_info = await detect_project_type(input_data["workingDirectory"])
return {
"additionalContext": f"""
This is a {project_info["type"]} project.
Main language: {project_info["language"]}
Package manager: {project_info["packageManager"]}
""".strip()
}
return await client.create_session(
permissions={"on_request": PermissionHandler.approve_all},
hooks={"handlers": {"on_session_start": on_session_start}},
)
const session = await client.createSession({
hooks: {
handlers: {
onSessionStart: async (input, invocation) => {
if (input.source === "resume") {
// Load previous session state
const previousState = await loadSessionState(invocation.sessionId);
return {
additionalContext: `
Session resumed. Previous context:
- Last topic: ${previousState.lastTopic}
- Open files: ${previousState.openFiles.join(", ")}
`.trim(),
};
}
return null;
},
},
},
});
const session = await client.createSession({
hooks: {
handlers: {
onSessionStart: async () => {
const preferences = await loadUserPreferences();
const contextParts = [];
if (preferences.language) {
contextParts.push(`Preferred language: ${preferences.language}`);
}
if (preferences.codeStyle) {
contextParts.push(`Code style: ${preferences.codeStyle}`);
}
if (preferences.verbosity === "concise") {
contextParts.push("Keep responses brief and to the point.");
}
return {
additionalContext: contextParts.join("\n"),
};
},
},
},
});
The onSessionEnd hook is called when a session ends.
A standalone SDK session remains active between prompts. Completing a prompt does not end the session; disconnect or dispose the session to run its end hook.
This callback runs whenever the session ends. Declarative sessionEnd hooks discovered from user configuration, settings, repositories, or plugins run only after the session's first prompt (or the first prompt after a resume) has fired its sessionStart hooks. Explicit hooks.directories and managed-policy hooks run on every session end.
type SessionEndHandler = (
input: SessionEndHookInput,
invocation: HookInvocation
) => Promise<SessionEndHookOutput | null | undefined>;
from copilot.session import SessionEndHookInput, SessionEndHookOutput
from copilot.session import SessionEndHandler as SdkSessionEndHandler
from typing import Callable, Awaitable
SessionEndHandler = Callable[
[SessionEndHookInput, dict[str, str]],
Awaitable[SessionEndHookOutput | None]
]
def check(handler: SessionEndHandler) -> SdkSessionEndHandler:
return handler
SessionEndHandler = Callable[
[SessionEndHookInput, dict[str, str]],
Awaitable[SessionEndHookOutput | None]
]
package main
import copilot "github.com/microsoft/copilot-sdk/go/v2"
// Aliases let the signature below use the package's own type names.
type (
SessionEndHookInput = copilot.SessionEndHookInput
HookInvocation = copilot.HookInvocation
SessionEndHookOutput = copilot.SessionEndHookOutput
)
type SessionEndHandler func(
input SessionEndHookInput,
invocation HookInvocation,
) (*SessionEndHookOutput, error)
var _ = copilot.SessionEndHandler(SessionEndHandler(nil))
func main() {}
type SessionEndHandler func(
input SessionEndHookInput,
invocation HookInvocation,
) (*SessionEndHookOutput, error)
using Microsoft.Copilot;
public delegate Task<SessionEndHookOutput?> SessionEndHandler(
SessionEndHookInput input,
HookInvocation invocation);
static class SessionEndHandlerCheck
{
static SessionHooks Check(SessionEndHandler handler) =>
new() { OnSessionEnd = handler.Invoke };
}
public delegate Task<SessionEndHookOutput?> SessionEndHandler(
SessionEndHookInput input,
HookInvocation invocation);
import com.microsoft.copilot.rpc.*;
import java.util.concurrent.CompletableFuture;
public class SessionEndSignature {
static class Documented {
@FunctionalInterface
public interface SessionEndHandler {
CompletableFuture<SessionEndHookOutput> handle(
SessionEndHookInput input,
HookInvocation invocation);
}
}
// The documented interface and the SDK's accept each other's implementations.
static SessionEndHandler toSdk(Documented.SessionEndHandler documented) {
return documented::handle;
}
static Documented.SessionEndHandler fromSdk(SessionEndHandler sdk) {
return sdk::handle;
}
public static void main(String[] args) {}
}
@FunctionalInterface
public interface SessionEndHandler {
CompletableFuture<SessionEndHookOutput> handle(
SessionEndHookInput input,
HookInvocation invocation);
}
| Field | Type | Description |
|---|---|---|
timestamp | SDK timestamp type | When the hook was triggered |
workingDirectory | string | Current working directory |
reason | string | Why the session ended (see below) |
finalMessage | string | undefined | The last message from the session |
error | string | undefined | Error message if session ended due to error |
| Reason | Description |
|---|---|
"complete" | Session completed normally |
"error" | Session ended due to an error |
"abort" | Session was aborted by user or code |
"timeout" | Session timed out |
"user_exit" | User explicitly ended the session |
| Field | Type | Description |
|---|---|---|
suppressOutput | boolean | Suppress the final session output |
cleanupActions | string[] | List of cleanup actions to perform |
sessionSummary | string | Summary of the session for logging/analytics |
const sessionStartTimes = new Map<string, Date>();
const session = await client.createSession({
hooks: {
handlers: {
onSessionStart: async (input, invocation) => {
sessionStartTimes.set(invocation.sessionId, input.timestamp);
return null;
},
onSessionEnd: async (input, invocation) => {
const startTime = sessionStartTimes.get(invocation.sessionId);
const duration = startTime ? input.timestamp.getTime() - startTime.getTime() : 0;
await recordMetrics({
sessionId: invocation.sessionId,
duration,
endReason: input.reason,
});
sessionStartTimes.delete(invocation.sessionId);
return null;
},
},
},
});
from copilot import CopilotClient
from copilot.session import PermissionHandler
async def create_instrumented_session(client: CopilotClient, record_metrics):
session_start_times = {}
async def on_session_start(input_data, invocation):
session_start_times[invocation["session_id"]] = input_data["timestamp"]
return None
async def on_session_end(input_data, invocation):
start_time = session_start_times.get(invocation["session_id"])
duration = (
(input_data["timestamp"] - start_time).total_seconds() * 1000
if start_time
else 0
)
await record_metrics(
{
"session_id": invocation["session_id"],
"duration": duration,
"end_reason": input_data["reason"],
}
)
session_start_times.pop(invocation["session_id"], None)
return None
return await client.create_session(
permissions={"on_request": PermissionHandler.approve_all},
hooks={
"handlers": {
"on_session_start": on_session_start,
"on_session_end": on_session_end,
}
},
)
const sessionResources = new Map<string, { tempFiles: string[] }>();
const session = await client.createSession({
hooks: {
handlers: {
onSessionStart: async (input, invocation) => {
sessionResources.set(invocation.sessionId, { tempFiles: [] });
return null;
},
onSessionEnd: async (input, invocation) => {
const resources = sessionResources.get(invocation.sessionId);
if (resources) {
// Clean up temp files
for (const file of resources.tempFiles) {
await fs.unlink(file).catch(() => {});
}
sessionResources.delete(invocation.sessionId);
}
console.log(`Session ${invocation.sessionId} ended: ${input.reason}`);
return null;
},
},
},
});
const session = await client.createSession({
hooks: {
handlers: {
onSessionEnd: async (input, invocation) => {
if (input.reason !== "error") {
// Save state for potential resume
await saveSessionState(invocation.sessionId, {
endTime: input.timestamp,
cwd: input.workingDirectory,
reason: input.reason,
});
}
return null;
},
},
},
});
const sessionData: Record<string, { prompts: number; tools: number; startTime: Date }> = {};
const session = await client.createSession({
hooks: {
handlers: {
onSessionStart: async (input, invocation) => {
sessionData[invocation.sessionId] = {
prompts: 0,
tools: 0,
startTime: input.timestamp,
};
return null;
},
onUserPromptSubmitted: async (_, invocation) => {
sessionData[invocation.sessionId].prompts++;
return null;
},
onPreToolUse: async (_, invocation) => {
sessionData[invocation.sessionId].tools++;
return { permissionDecision: "allow" };
},
onSessionEnd: async (input, invocation) => {
const data = sessionData[invocation.sessionId];
console.log(
`
Session Summary:
ID: ${invocation.sessionId}
Duration: ${(input.timestamp.getTime() - data.startTime.getTime()) / 1000}s
Prompts: ${data.prompts}
Tool calls: ${data.tools}
End reason: ${input.reason}
`.trim(),
);
delete sessionData[invocation.sessionId];
return null;
},
},
},
});
The agent stop hook runs when the top-level agent naturally reaches the end of a turn. It is separate from onSessionEnd: the session remains active, and the hook can request another agent turn.
| Language | Handler |
|---|---|
| Node.js / TypeScript | onAgentStop |
| Python | on_agent_stop |
| Go | OnAgentStop |
| .NET | OnAgentStop |
| Rust | on_agent_stop |
| Java | setOnAgentStop |
The public member names follow each language's casing conventions:
| Meaning | Node.js / Python | Go / .NET | Rust | Java |
|---|---|---|---|---|
Why the agent stopped, such as end_turn | stopReason | StopReason | stop_reason | getStopReason() |
| Path to the on-disk session transcript | transcriptPath | TranscriptPath | transcript_path | getTranscriptPath() |
| Whether an earlier block decision already forced this continuation | stopHookActive | StopHookActive | stop_hook_active | getStopHookActive() |
Return no output to let the agent stop. Return a block decision to enqueue another user message and continue:
{
"decision": "block",
"reason": "Run the final validation and fix any failures."
}
The reason is the message that is enqueued: the agent receives it as its next prompt, so write it as an instruction to the agent. It must be non-empty. A block decision without a reason, or with an empty one, lets the agent stop.
Use the active-stop member listed above to avoid repeatedly blocking an agent that has already continued because of this hook. The runtime also caps consecutive block decisions.
Keep onSessionStart fast - Users are waiting for the session to be ready.
Handle all end reasons - Don't assume sessions end cleanly; handle errors and aborts.
Clean up resources - Use onSessionEnd to free any resources allocated during the session.
Store minimal state - If tracking session data, keep it lightweight.
Make cleanup idempotent - onSessionEnd might not be called if the process crashes.
Can you improve this documentation? These fine people already did:
Jeremiah Isaacson, copilot-cli-release-app[bot], Patrick Nikoletich, Brett Cannon, copilot-sdk-mirror-writer[bot], Sunbrye Ly, Rince Yuan, Ed Burns, Bruno Borges, Belal Taher, Steve Sanderson & Andy FellerEdit on GitHub
cljdoc builds & hosts documentation for Clojure/Script libraries
| Ctrl+k | Jump to recent docs |
| ← | Move to previous article |
| → | Move to next article |
| Ctrl+/ | Jump to the search field |