DEV Community

Cover image for Session Management for AI Agents: TTL, Renewals, and Absolute Lifetime
Wallet Guy
Wallet Guy

Posted on

Session Management for AI Agents: TTL, Renewals, and Absolute Lifetime

Session management is the critical security boundary between your AI agent and your wallet — get it wrong, and your agent could outlive its welcome or drain your funds. WAIaaS provides comprehensive session controls with TTL, renewal limits, and absolute lifetimes to ensure your AI agents operate within strict time boundaries and can't persist indefinitely.

Why Session Boundaries Matter

AI agents with wallet access need temporal constraints. Unlike human users who log out at the end of the day, AI agents run continuously and could theoretically hold wallet permissions forever. This creates obvious risks: compromised agents, runaway trading algorithms, or simply agents that should have been decommissioned months ago but still have active wallet access.

Traditional session management assumes human behavior — short bursts of activity followed by natural breaks. AI agents break this model entirely. They need session controls designed specifically for autonomous operation: predictable expiration, controlled renewal windows, and absolute kill switches.

WAIaaS Session Architecture

WAIaaS implements a three-layer session security model specifically designed for AI agents:

Layer 1: Session Authentication (sessionAuth)
Every AI agent gets a time-bounded JWT session token. This is their primary credential for wallet operations.

Layer 2: Renewal Controls
Sessions can be renewed, but only within configured limits. This prevents agents from extending their access indefinitely.

Layer 3: Absolute Lifetime
Even with renewals, sessions have a hard expiration date. No agent can operate beyond its absolute lifetime, regardless of activity.

Creating Sessions with Time Controls

When you create a session for an AI agent, you specify its temporal boundaries:

curl -X POST http://127.0.0.1:3100/v1/sessions \
  -H "Content-Type: application/json" \
  -H "X-Master-Password: my-secret-password" \
  -d '{
    "walletId": "019c47d6-51ef-7f43-a76b-d50e875d95f4",
    "ttl": 3600,
    "maxRenewals": 10,
    "absoluteLifetime": 86400
  }'
Enter fullscreen mode Exit fullscreen mode

This creates a session that:

  • Expires after 1 hour of inactivity (ttl: 3600)
  • Can be renewed up to 10 times (maxRenewals: 10)
  • Dies permanently after 24 hours regardless of activity (absoluteLifetime: 86400)

The response includes your session token:

{
  "id": "019c4cd2-86e8-758f-a61e-9c560307c788",
  "token": "wai_sess_eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "expiresAt": "2024-01-15T15:00:00Z",
  "renewalsRemaining": 10,
  "absoluteExpiresAt": "2024-01-16T14:00:00Z"
}
Enter fullscreen mode Exit fullscreen mode

The Three Session Timers

WAIaaS tracks three different time boundaries for every session:

TTL (Time To Live)
The basic session timeout. If your agent doesn't make any API calls within the TTL window, the session expires. This handles the "agent went offline" scenario.

Max Renewals
How many times the session can be extended. Each successful API call before TTL expiration resets the TTL timer and consumes one renewal. This prevents infinite session extension while allowing active agents to continue operating.

Absolute Lifetime
The hard stop. No matter how active your agent is, the session dies at this timestamp. This is your ultimate safety net against runaway agents.

Default Session Behavior

WAIaaS defaults to unlimited sessions for development convenience, but production deployments should always set explicit limits:

// Development defaults (unlimited)
{
  ttl: undefined,           // Never expires from inactivity
  maxRenewals: undefined,   // Infinite renewals allowed
  absoluteLifetime: undefined // No hard expiration
}

// Recommended production settings
{
  ttl: 3600,               // 1 hour inactivity timeout
  maxRenewals: 24,         // 24 renewals = ~1 day of active use
  absoluteLifetime: 86400  // 24 hour absolute limit
}
Enter fullscreen mode Exit fullscreen mode

Session Renewal in Practice

When your agent makes API calls, WAIaaS automatically handles session renewal. Here's what happens:

# Agent checks balance (first call)
curl http://127.0.0.1:3100/v1/wallet/balance \
  -H "Authorization: Bearer wai_sess_eyJhbGciOiJIUzI1NiJ9..."
Enter fullscreen mode Exit fullscreen mode

Response headers show current session state:

X-Session-Expires-At: 2024-01-15T15:00:00Z
X-Session-Renewals-Remaining: 9
X-Session-Absolute-Expires-At: 2024-01-16T14:00:00Z
Enter fullscreen mode Exit fullscreen mode

Each successful API call within the TTL window:

  1. Resets the TTL timer (session now expires 1 hour from now)
  2. Decrements renewalsRemaining by 1
  3. Returns updated expiration times in response headers

Monitoring Session Health

Your agent should monitor its session status to gracefully handle expiration:

import { WAIaaSClient } from '@waiaas/sdk';

const client = new WAIaaSClient({
  baseUrl: 'http://127.0.0.1:3100',
  sessionToken: process.env.WAIAAS_SESSION_TOKEN,
});

// Check session health before critical operations
try {
  const balance = await client.getBalance();

  // WAIaaS SDK exposes session metadata
  const sessionInfo = client.getSessionInfo();
  console.log(`Renewals remaining: ${sessionInfo.renewalsRemaining}`);
  console.log(`Absolute expiry: ${sessionInfo.absoluteExpiresAt}`);

  if (sessionInfo.renewalsRemaining < 5) {
    console.warn('Session approaching renewal limit');
  }
} catch (error) {
  if (error.code === 'TOKEN_EXPIRED') {
    console.error('Session expired - agent must stop');
    process.exit(1);
  }
}
Enter fullscreen mode Exit fullscreen mode

Session Termination Scenarios

Sessions end in several ways, each with different implications for your agent:

TTL Expiration
Agent went idle too long. The session can potentially be recreated if under renewal limits.

Renewal Exhaustion
Agent hit its maximum renewal count. Session cannot be extended further.

Absolute Lifetime
Hard deadline reached. Session must be recreated from scratch with master auth.

Manual Revocation
Administrator explicitly killed the session via API or CLI.

Security Best Practices

Set Explicit Limits
Never deploy with unlimited sessions in production:

# Bad: unlimited session
curl -X POST http://127.0.0.1:3100/v1/sessions \
  -d '{"walletId": "..."}'  # Uses unlimited defaults

# Good: explicit boundaries
curl -X POST http://127.0.0.1:3100/v1/sessions \
  -d '{
    "walletId": "...",
    "ttl": 3600,
    "maxRenewals": 24,
    "absoluteLifetime": 86400
  }'
Enter fullscreen mode Exit fullscreen mode

Match Limits to Agent Behavior
High-frequency trading bots need different limits than daily reporting agents:

# High-frequency trader: short TTL, many renewals
{
  "ttl": 300,        # 5 minute inactivity = dead
  "maxRenewals": 288, # 5 min * 288 = 24 hours max
  "absoluteLifetime": 86400
}

# Daily report bot: long TTL, few renewals  
{
  "ttl": 7200,       # 2 hour inactivity window
  "maxRenewals": 12, # 12 * 2hr = 24 hours max
  "absoluteLifetime": 86400
}
Enter fullscreen mode Exit fullscreen mode

Monitor Session Health
Build session awareness into your agent's operational monitoring. Sessions approaching limits should trigger alerts.

Graceful Degradation
Design agents to shut down cleanly when sessions expire, rather than crashing or retrying indefinitely.

Quick Start: Secure Agent Sessions

Here's how to set up properly bounded sessions for your AI agents:

  1. Create a session with explicit limits:
waiaas cli session create \
  --wallet-id "your-wallet-uuid" \
  --ttl 3600 \
  --max-renewals 24 \
  --absolute-lifetime 86400
Enter fullscreen mode Exit fullscreen mode
  1. Monitor session health in your agent:
// Check renewals remaining before expensive operations
const sessionInfo = client.getSessionInfo();
if (sessionInfo.renewalsRemaining < 5) {
  console.warn('Low renewals - stopping non-critical operations');
}
Enter fullscreen mode Exit fullscreen mode
  1. Handle expiration gracefully:
try {
  await client.sendToken({to: '...', amount: '0.1'});
} catch (error) {
  if (error.code === 'TOKEN_EXPIRED') {
    console.log('Session expired - shutting down gracefully');
    process.exit(0);
  }
}
Enter fullscreen mode Exit fullscreen mode
  1. Set up monitoring alerts:
# Check session status via CLI
waiaas status --sessions
Enter fullscreen mode Exit fullscreen mode
  1. Revoke sessions manually when needed:
waiaas cli session revoke --session-id "session-uuid"
Enter fullscreen mode Exit fullscreen mode

Session management might seem like a minor detail, but it's your first line of defense against runaway AI agents. Proper TTL, renewal limits, and absolute lifetimes ensure your agents operate within predictable boundaries and can't persist beyond their intended scope.

Ready to implement secure session management for your AI agents? Check out the full WAIaaS implementation on GitHub or explore more at waiaas.ai.

What's Next

Once you have session boundaries in place, explore WAIaaS's policy engine for transaction-level controls and consider setting up human approval workflows for high-value operations. Secure AI agents require multiple layers of protection.

Top comments (0)