Liking cljdoc? Tell your friends :D

Session limits

Session limits let an application set an AI Credits budget for a Copilot session. Use execution.limits when creating or resuming a session to set a soft cap for the current accounting window.

Configure a session limit

Set maxAiCredits to the AI Credits soft cap for the session's current accounting window. Usage is checked after model calls return, so one response can exceed the configured value before the runtime blocks the next model call. The SDK forwards this value to the Copilot runtime when it creates or resumes the session. The value must be at least 30 and greater than the AI Credits the session has already used; a lower value is rejected.

TypeScript
import { approveAll } from "copilot-sdk-supercharged";

const session = await client.createSession({
    permissions: {
        onRequest: approveAll,
    },
    execution: {
        limits: {
            maxAiCredits: 30,
        },
    },
});

const resumed = await client.resumeSession(session.sessionId, {
    permissions: {
        onRequest: approveAll,
    },
    execution: {
        limits: {
            maxAiCredits: 30,
        },
    },
});
const session = await client.createSession({
    permissions: {
        onRequest: approveAll,
    },
    execution: {
        limits: {
            maxAiCredits: 30,
        },
    },
});

const resumed = await client.resumeSession(session.sessionId, {
    permissions: {
        onRequest: approveAll,
    },
    execution: {
        limits: {
            maxAiCredits: 30,
        },
    },
});
Python
from copilot import CopilotClient
from copilot.session import PermissionHandler


async def main(client: CopilotClient):
    session = await client.create_session(
        permissions={"on_request": PermissionHandler.approve_all},
        execution={
            "limits": {
                "max_ai_credits": 30,
            }
        },
    )

    resumed = await client.resume_session(
        session.session_id,
        permissions={"on_request": PermissionHandler.approve_all},
        execution={
            "limits": {
                "max_ai_credits": 30,
            }
        },
    )
session = await client.create_session(
    permissions={"on_request": PermissionHandler.approve_all},
    execution={
        "limits": {
            "max_ai_credits": 30,
        }
    },
)

resumed = await client.resume_session(
    session.session_id,
    permissions={"on_request": PermissionHandler.approve_all},
    execution={
        "limits": {
            "max_ai_credits": 30,
        }
    },
)
Go
package main

import (
	"context"

	copilot "github.com/microsoft/copilot-sdk/go/v2"
	"github.com/microsoft/copilot-sdk/go/v2/rpc"
)

func main() {
	ctx := context.Background()
	client := copilot.NewClient(&copilot.ClientOptions{Mode: copilot.ModeCodingAgent})

	session, err := client.CreateSession(ctx, &copilot.CreateSessionOptions{
		Permissions: copilot.SessionPermissionOptions{
			OnRequest: copilot.PermissionHandler.ApproveAll,
		},
		Execution: copilot.SessionExecutionOptions{
			Limits: &rpc.SessionLimitsConfig{
				MaxAiCredits: copilot.Float64(30),
			},
		},
	})

	resumed, err := client.ResumeSession(ctx, session.SessionID, &copilot.ResumeSessionOptions{
		Permissions: copilot.SessionPermissionOptions{
			OnRequest: copilot.PermissionHandler.ApproveAll,
		},
		Execution: copilot.SessionExecutionOptions{
			Limits: &rpc.SessionLimitsConfig{
				MaxAiCredits: copilot.Float64(30),
			},
		},
	})
	_, _ = resumed, err
}
session, err := client.CreateSession(ctx, &copilot.CreateSessionOptions{
	Permissions: copilot.SessionPermissionOptions{
		OnRequest: copilot.PermissionHandler.ApproveAll,
	},
	Execution: copilot.SessionExecutionOptions{
		Limits: &rpc.SessionLimitsConfig{
			MaxAiCredits: copilot.Float64(30),
		},
	},
})

resumed, err := client.ResumeSession(ctx, session.SessionID, &copilot.ResumeSessionOptions{
	Permissions: copilot.SessionPermissionOptions{
		OnRequest: copilot.PermissionHandler.ApproveAll,
	},
	Execution: copilot.SessionExecutionOptions{
		Limits: &rpc.SessionLimitsConfig{
			MaxAiCredits: copilot.Float64(30),
		},
	},
})

.NET
await using var client = new CopilotClient(new CopilotClientOptions { Mode = CopilotClientMode.CodingAgent });
#pragma warning disable MCPSDK001 // Session limits are experimental.

var session = await client.CreateSessionAsync(new CreateSessionOptions
{
    Permissions = new SessionPermissionOptions
    {
        OnRequest = PermissionHandler.ApproveAll
    },
    Execution = new SessionExecutionOptions
    {
        Limits = new SessionLimitsConfig
        {
            MaxAiCredits = 30,
        }
    }
});
var resumed = await client.ResumeSessionAsync(session.SessionId, new ResumeSessionOptions
{
    Permissions = new SessionPermissionOptions
    {
        OnRequest = PermissionHandler.ApproveAll
    },
    Execution = new SessionExecutionOptions
    {
        Limits = new SessionLimitsConfig
        {
            MaxAiCredits = 30,
        }
    }
});
#pragma warning disable MCPSDK001 // Session limits are experimental.

var session = await client.CreateSessionAsync(new CreateSessionOptions
{
    Permissions = new SessionPermissionOptions
    {
        OnRequest = PermissionHandler.ApproveAll
    },
    Execution = new SessionExecutionOptions
    {
        Limits = new SessionLimitsConfig
        {
            MaxAiCredits = 30,
        }
    }
});
var resumed = await client.ResumeSessionAsync(session.SessionId, new ResumeSessionOptions
{
    Permissions = new SessionPermissionOptions
    {
        OnRequest = PermissionHandler.ApproveAll
    },
    Execution = new SessionExecutionOptions
    {
        Limits = new SessionLimitsConfig
        {
            MaxAiCredits = 30,
        }
    }
});

The .NET SessionExecutionOptions.Limits property raises the MCPSDK001 experimental diagnostic. Suppress it with #pragma warning disable MCPSDK001 or a project-level <NoWarn>MCPSDK001</NoWarn>.

Java
import com.microsoft.copilot.CopilotClient;
import com.microsoft.copilot.rpc.CopilotClientMode;
import com.microsoft.copilot.rpc.CopilotClientOptions;
import com.microsoft.copilot.CopilotSession;
import com.microsoft.copilot.generated.rpc.SessionLimitsConfig;
import com.microsoft.copilot.rpc.CreateSessionOptions;
import com.microsoft.copilot.rpc.PermissionHandler;
import com.microsoft.copilot.rpc.ResumeSessionOptions;
import com.microsoft.copilot.rpc.SessionExecutionOptions;
import com.microsoft.copilot.rpc.SessionPermissionOptions;

public class SessionLimitsExample {
    public static void main(String[] args) throws Exception {
        try (var client = new CopilotClient(new CopilotClientOptions().setMode(CopilotClientMode.CODING_AGENT))) {
            client
                    .start()
                    .get();

            CopilotSession session = client
                    .createSession(new CreateSessionOptions()
                            .setPermissions(new SessionPermissionOptions()
                                    .setOnRequest(PermissionHandler.APPROVE_ALL))
                            .setExecution(new SessionExecutionOptions()
                                    .setLimits(new SessionLimitsConfig(30.0))))
                    .get();

            CopilotSession resumed = client
                    .resumeSession(session
                            .getSessionId(),
                            new ResumeSessionOptions()
                                    .setPermissions(new SessionPermissionOptions()
                                            .setOnRequest(PermissionHandler.APPROVE_ALL))
                                    .setExecution(new SessionExecutionOptions()
                                            .setLimits(new SessionLimitsConfig(30.0))))
                    .get();
        }
    }
}
import com.microsoft.copilot.generated.rpc.SessionLimitsConfig;
import com.microsoft.copilot.rpc.CreateSessionOptions;
import com.microsoft.copilot.rpc.PermissionHandler;
import com.microsoft.copilot.rpc.ResumeSessionOptions;
import com.microsoft.copilot.rpc.SessionExecutionOptions;
import com.microsoft.copilot.rpc.SessionPermissionOptions;

CopilotSession session = client
        .createSession(new CreateSessionOptions()
                .setPermissions(new SessionPermissionOptions()
                        .setOnRequest(PermissionHandler.APPROVE_ALL))
                .setExecution(new SessionExecutionOptions()
                        .setLimits(new SessionLimitsConfig(30.0))))
        .get();

CopilotSession resumed = client
        .resumeSession(session
                .getSessionId(),
                new ResumeSessionOptions()
                        .setPermissions(new SessionPermissionOptions()
                                .setOnRequest(PermissionHandler.APPROVE_ALL))
                        .setExecution(new SessionExecutionOptions()
                                .setLimits(new SessionLimitsConfig(30.0))))
        .get();
Rust
let limits = SessionLimitsConfig {
    max_ai_credits: Some(30.0),
};

let session = client
    .create_session(
        CreateSessionOptions::default()
            .with_permissions(|__sdk_group| __sdk_group.approve_all_permissions())
            .with_execution(|__sdk_group| __sdk_group.with_limits(limits.clone())),
    )
    .await?;

let resumed = client
    .resume_session(
        ResumeSessionOptions::new(session.id().clone())
            .with_permissions(|__sdk_group| __sdk_group.approve_all_permissions())
            .with_execution(|__sdk_group| __sdk_group.with_limits(limits)),
    )
    .await?;

Observe budget events

Applications can subscribe to session events to update UI when the soft cap changes or the session is about to run out of budget.

Event typeWhen it is emittedImportant fields
session.session_limits_changedActive session limits changed. A null sessionLimits value means no limits are active.sessionLimits.maxAiCredits?
session.usage_checkpointThe runtime records durable aggregate usage for resume and accounting.totalNanoAiu, totalPremiumRequests?
session_limits_exhausted.requestedThe budget is used up, or the next model call would be the session's final call without tools, and the runtime needs a user decision before continuing.requestId, maxAiCredits, usedAiCredits
session_limits_exhausted.completedThe exhausted-limit prompt was resolved.requestId, response.action, response.additionalAiCredits?, response.maxAiCredits?

session_limits_exhausted.requested is not like the first two events. The runtime emits it only when a consumer has registered interest in it, and subscribing with session.on does not count. Once it is emitted, the turn waits until the application answers with the session.ui.handlePendingSessionLimitsExhausted RPC, using the requestId from the event. The response.action is "add" (with additionalAiCredits), "set" (with maxAiCredits), "unset" or "cancel".

The runtime asks at two points. The first comes before the budget is used up: when 10% or less of it remains, the next model call is the session's final call, made without tools. The runtime asks before that call, at most once per request. If the answer raises the limit out of that final 10% or removes it, the turn continues with tools; otherwise the final call runs without tools. The second comes once the budget is used up: an accepted "add", "set" or "unset" lets the turn continue, and "cancel" stops it.

Use the generated event types for the SDK language you are using. For example, TypeScript registers interest with session.rpc.eventLog.registerInterest, narrows by event type, and answers the request:

import { approveAll } from "copilot-sdk-supercharged";

const session = await client.createSession({
    permissions: {
        onRequest: approveAll,
    },
});

await session.rpc.eventLog.registerInterest({
    eventType: "session_limits_exhausted.requested",
});

session.on("session_limits_exhausted.requested", async (event) => {
    // Ask the user here, then resolve the pending request.
    await session.rpc.ui.handlePendingSessionLimitsExhausted({
        requestId: event.data.requestId,
        response: { action: "add", additionalAiCredits: 10 },
    });
});
await session.rpc.eventLog.registerInterest({
    eventType: "session_limits_exhausted.requested",
});

session.on("session_limits_exhausted.requested", async (event) => {
    // Ask the user here, then resolve the pending request.
    await session.rpc.ui.handlePendingSessionLimitsExhausted({
        requestId: event.data.requestId,
        response: { action: "add", additionalAiCredits: 10 },
    });
});

registerInterest returns a handle. Pass it to session.rpc.eventLog.releaseInterest to stop the runtime from treating your application as a consumer of the event.

Can you improve this documentation? These fine people already did:
copilot-cli-release-app[bot], copilot-sdk-mirror-writer[bot], Jeremiah Isaacson, examon & Tamás Szabó
Edit on GitHub

cljdoc builds & hosts documentation for Clojure/Script libraries

Keyboard shortcuts
Ctrl+kJump to recent docs
←Move to previous article
→Move to next article
Ctrl+/Jump to the search field
× close