Skip to main content

Sessions

Store short-lived, app-scoped JSON state under an ID you choose, and hand it to AI agents, LangGraph runs, and voice calls so every function in the flow shares it.​

Why Use Sessions​

A conversation often needs state that belongs to the flow rather than to your database: which customer the caller verified, a cart being assembled across agent turns, or flags a voice call sets for later turns. Without sessions you would stand up a collection and thread its key through every call yourself.

A session is that record, managed by Squid: your code and your agent's AI functions read and write it by ID, and it expires on its own when the flow ends.

Overview​

A session is an app-scoped JSON record under an ID the app chooses:

  • data holds up to 64 KB of JSON. Writes merge top-level keys; deleteKeys removes them.
  • A new session expires 1 day after its last write. Set expiration to { ttlMs } (at least 1000) or 'never' to change that; every upsert moves the expiration to its TTL from now.
  • Managing sessions with squid.sessions() requires the app API key, so do it from backend code. Clients without the API key can still start or attach a session through an agent, LangGraph, or voice call, vetted by your security rules.
note

Sessions are available in the TypeScript and Python clients (squid.sessions()).

Quick Start​

Step 1: Create a session and pass it to an agent​

Backend code
import { executable, SquidService } from '@squidcloud/backend';

export class ExampleService extends SquidService {
@executable()
async startSupportFlow(customerId: string): Promise<string> {
const session = await this.squid.sessions().upsert({
id: `support-${customerId}`, // 1-256 characters, chosen by you
data: { customerId, verified: false },
expiration: { ttlMs: 60 * 60 * 1000 }, // 1 hour after the last write
});
return session.id;
}
}

Step 2: Run agent turns in the session​

Pass session in the ask options. Every AI function the turn calls receives the session as context.session:

Client code
await squid
.ai()
.agent('support-copilot')
.ask('Verify me, my account number is 4821', {
session: { id: sessionId },
});
Backend code
import { aiFunction, AiFunctionCallContext, SquidService } from '@squidcloud/backend';

export class SupportService extends SquidService {
@aiFunction('Marks the caller as verified. Call it when the account number checks out.', [])
async markVerified(_args: Record<string, never>, { session }: AiFunctionCallContext): Promise<string> {
if (!session) return 'No session attached';
// Writing needs the API key, which backend code has.
await this.squid.sessions().upsert({ id: session.id, data: { verified: true } });
return 'Verified';
}
}

Managing Sessions​

All methods live on squid.sessions() and require the app API key:

MethodWhat it does
upsert(request)Creates the session, or updates the one with the same id, and returns it as stored. Each upsert refreshes the TTL.
get(id)Returns the session, or undefined when it is missing or expired.
delete(id)Deletes the session. Deleting a missing session does nothing.
list(request)Returns a page of sessions, newest first. limit defaults to 100 (up to 1000), where filters on top-level data keys and creation time, and nextCursor pages.
Backend code
const { sessions, nextCursor } = await this.squid.sessions().list({
where: { data: { verified: true } },
limit: 100,
});

Attaching a Session to AI Calls​

The session option is accepted by agent ask() and chat(), by LangGraph invoke(), resume(), and their streaming and async variants, and by voice call requests. It is part of the request only, never stored with the agent.

  • With the app API key, the request creates the session or updates the one with the same ID, exactly like sessions().upsert().
  • Without the API key, a new ID creates the session with the request's data. An existing (live) session can only be attached by its ID alone: sending data for a live session fails the call with a 409 SESSION_ALREADY_EXISTS. The agent's @secureAiAgent or @secureLangGraph rules receive both the request's session and the stored storedSession, and a rule that rejects them refuses the call. A call that skips the rules, to a public agent or with the agent's API key, cannot attach a session at all.

A rule that vets sessions:

Backend code
import { secureAiAgent, SecureAiAgentContext, SquidService } from '@squidcloud/backend';

export class ExampleService extends SquidService {
@secureAiAgent('support-copilot')
allowSupportAsk(context: SecureAiAgentContext): boolean {
// A client never grants itself the admin role, and cannot attach a locked session.
if (context.session?.data?.['role'] === 'admin') return false;
if (context.storedSession?.data['locked'] === true) return false;
return this.isAuthenticated();
}
}

Inside a LangGraph run, backend service code reads the session's ID from Squid's run context (this.context.sessionId) and the data with sessions().get(). The caller-supplied LangGraph context does not carry it.

Error Handling​

ErrorCauseSolution
API_KEY_REQUIRED on sessions() calls (401)The client has no app API keyManage sessions from backend code
UNAUTHORIZED on an ask with sessionA security rule refused the sessionVet and allow the session in the agent's rules; see above
403 on an ask with sessionThe call skips security rules: a public agent, or the agent API keyAttach sessions only on calls the agent's rules vet, or use the app API key
SESSION_ALREADY_EXISTS (409)A keyless call sent data for a session that already existsAttach a live session by { id } alone; write data from backend code
Session data over 64 KBThe merged data exceeds the limitKeep sessions small; store large state in a database keyed by the session ID
get() returns undefinedThe session expired or never existedRecreate it, or lengthen expiration

Best Practices​

  • Key sessions on something meaningful, such as a conversation or order ID, so any part of the flow can find them without passing extra state around.
  • Let sessions expire. Pick a TTL that matches the flow instead of 'never', and reserve 'never' for state you delete explicitly.
  • Treat client-supplied session data as untrusted. Without the API key a caller chooses the data of a new session, so validate it in your security rules, and store trusted facts (like verified: true) only from backend code.
  • Store large or durable state elsewhere. A session holds 64 KB and disappears; keep anything lasting in a database and put only its key in the session.