# How to Set AI Credits Budget Limits and Track Usage per Session in Copilot SDK

> Set AI credits budget limits and track usage per session in Copilot SDK. Enforce limits with sessionLimits and monitor remaining credits via UI RPC methods.

- Repository: [GitHub/copilot-sdk](https://github.com/github/copilot-sdk)
- Tags: how-to-guide
- Published: 2026-08-02

---

**You can enforce AI Credits budget limits in the Copilot SDK by passing a `sessionLimits` object with `maxAiCredits` to `CopilotSdk.createSession()`, then monitor remaining credits via the `ui.getSessionLimits()` RPC method and handle exhaustion through the `handlePendingSessionLimitsExhausted` callback.**

Managing costs in AI-powered applications requires precise control over token consumption. The GitHub Copilot SDK (`github/copilot-sdk`) provides native support for **AI Credits budget limits**, letting you define spending ceilings per session and track usage in real-time. This capability prevents runaway costs while giving you visibility into remaining credit balances throughout the session lifecycle.

## Configuring Budget Limits at Session Creation

Define your spending ceiling when initializing a new session. The SDK accepts a `sessionLimits` configuration object containing the `maxAiCredits` field, which specifies the maximum number of AI Credits allowed for that specific session.

### Configuration Structure

The `SessionLimitsConfig` interface in **[`src/types.ts`](https://github.com/github/copilot-sdk/blob/main/src/types.ts)** (lines 69-75) defines the shape of the budget configuration:

```typescript
const session = await CopilotSdk.createSession({
  model: "gpt-4o",
  sessionLimits: {
    maxAiCredits: 30  // Hard budget limit
  }
});

```

### Validation Logic

Before the session initializes, the SDK validates your budget value in **[`src/factory.ts`](https://github.com/github/copilot-sdk/blob/main/src/factory.ts)** (lines 407-416). The factory throws an error if you provide a non-finite, non-positive, or otherwise invalid value, ensuring only legitimate budget constraints reach the Copilot API.

## Runtime Enforcement and Transport

Once validated, your budget travels through the SDK's RPC layer to the Copilot API (CAPI), where runtime enforcement occurs.

### RPC Payload Encoding

The `sessionLimits` object is encoded into the payload for `session.create` and `session.resume` requests. In **[`src/generated/rpc.ts`](https://github.com/github/copilot-sdk/blob/main/src/generated/rpc.ts)** (lines 5525-5532), the generated RPC definitions include the `sessionLimits` field on these request messages, ensuring the budget constraint reaches the server.

### Automatic Session Termination

CAPI enforces the ceiling automatically. When accumulated AI Credits spend reaches your defined limit, the runtime stops the session and emits a `session.limits_exhausted` event. You can register the **`handlePendingSessionLimitsExhausted`** helper to react to this notification, as demonstrated in the end-to-end test file **[`rpc_tasks_and_handlers.e2e.test.ts`](https://github.com/github/copilot-sdk/blob/main/rpc_tasks_and_handlers.e2e.test.ts)** (lines 176-180).

## Tracking Usage Per Session

Monitor remaining credits throughout the session lifecycle using event-driven updates and explicit queries.

### Querying Remaining Credits

The SDK exposes the `ui.getSessionLimits()` RPC method, which returns the live `SessionLimitsConfig` record showing current remaining credits. Additionally, **[`src/generated/session-events.ts`](https://github.com/github/copilot-sdk/blob/main/src/generated/session-events.ts)** (lines 68-75) declares that `session.resume` events carry a `sessionLimits` field indicating the current budget state, allowing you to track consumption across session suspensions and resumptions.

### Handling Budget Exhaustion Events

Register a callback to gracefully handle budget depletion:

```typescript
session.rpc.ui.handlePendingSessionLimitsExhausted(({ maxAiCredits }) => {
  console.warn(`Budget exhausted (limit was ${maxAiCredits} credits)`);
  // Implement graceful degradation or user notification
});

```

## Complete Implementation Example

The following pattern demonstrates setting a budget, querying remaining credits, and handling exhaustion:

```typescript
// Create session with 30-credit budget
const session = await CopilotSdk.createSession({
  model: "gpt-4o",
  sessionLimits: { maxAiCredits: 30 }
});

// Poll remaining credits periodically
const limits = await session.rpc.ui.getSessionLimits();
console.log(`Credits left: ${limits.maxAiCredits}`);

// Register exhaustion handler
session.rpc.ui.handlePendingSessionLimitsExhausted(({ maxAiCredits }) => {
  console.warn(`Budget exhausted (limit was ${maxAiCredits} credits)`);
  // Gracefully stop the agent or notify the user
});

```

The end-to-end test in **[`session_config.e2e.test.ts`](https://github.com/github/copilot-sdk/blob/main/session_config.e2e.test.ts)** (lines 485-506) provides a working reference for sessions created with `maxAiCredits` constraints.

## Summary

- **Define budgets** using the `sessionLimits.maxAiCredits` parameter in `CopilotSdk.createSession()`, validated in [`src/factory.ts`](https://github.com/github/copilot-sdk/blob/main/src/factory.ts).
- **Transport limits** occur through RPC payloads defined in [`src/generated/rpc.ts`](https://github.com/github/copilot-sdk/blob/main/src/generated/rpc.ts) to the CAPI runtime.
- **Monitor consumption** via `ui.getSessionLimits()` RPC calls and `session.resume` events from [`src/generated/session-events.ts`](https://github.com/github/copilot-sdk/blob/main/src/generated/session-events.ts).
- **Handle exhaustion** by registering the `handlePendingSessionLimitsExhausted` callback to respond when credits deplete.

## Frequently Asked Questions

### What happens when the AI Credits budget is exhausted?

When the accumulated spend reaches your `maxAiCredits` limit, the CAPI runtime automatically stops the session and emits a `session.limits_exhausted` event. The SDK provides the `handlePendingSessionLimitsExhausted` helper in [`src/generated/rpc.ts`](https://github.com/github/copilot-sdk/blob/main/src/generated/rpc.ts) to register callbacks that trigger when this occurs, allowing you to implement graceful shutdowns or user notifications.

### Can I modify the budget limit after creating a session?

No, the Copilot SDK treats `sessionLimits` as immutable after session initialization. The validation logic in [`src/factory.ts`](https://github.com/github/copilot-sdk/blob/main/src/factory.ts) (lines 407-416) only processes the budget during the initial `createSession` call. To change limits, you must create a new session with updated parameters.

### How does the SDK validate budget values?

The factory validation in [`src/factory.ts`](https://github.com/github/copilot-sdk/blob/main/src/factory.ts) rejects non-finite numbers, negative values, and other invalid inputs before sending requests to CAPI. This ensures only legitimate positive numeric budgets reach the runtime enforcement layer, preventing configuration errors from causing unexpected session behavior.

### Where can I find examples of budget limit implementations?

Reference the end-to-end tests in **[`session_config.e2e.test.ts`](https://github.com/github/copilot-sdk/blob/main/session_config.e2e.test.ts)** (lines 485-506) for session creation examples, and **[`rpc_tasks_and_handlers.e2e.test.ts`](https://github.com/github/copilot-sdk/blob/main/rpc_tasks_and_handlers.e2e.test.ts)** (lines 176-180) for exhaustion handling patterns. These demonstrate real-world usage of the `SessionLimitsConfig` interface defined in [`src/types.ts`](https://github.com/github/copilot-sdk/blob/main/src/types.ts).