In Magma, sessions are the unique instances of your agent, with their own context and state. This makes it easy to handle different users’ interactions with the same agent.

A new session is created when a hook is triggered with a new session id, or when the agent is accessed via the agent api with a new session id.

When one of these events is triggered without a session id, a new temporary session is created to handle the agent interactions.

Agent API

The agent api is a way to interact with the agent via websocket or http requests.

When using the agent api, you can specify a session id to interact with a specific session of the agent.

HTTP Request

You can specify the session id a few ways when accessing the agent via POST request.

  • Query Parameter: https://api.magmadeploy.com/v1/agents/<agent-id>/chat?sessionId=<session-id>
  • Body Parameter: "sessionId": "<session-id>" or "session_id": "<session-id>"
  • Header: x-session-id: <session-id>

WebSocket Connection

When using the websocket, you can specify the session id using a query parameter.

ws://api.magmadeploy.com/v1/<agent-id>?sessionId=<session-id>

Hooks

When using hooks, you can specify which session should handle the hook. This is done by specifying where in the hook request the session id is located.

@hook('user-update', HookRequest.Body('userId'))
async updateUser(req: Request, res: Response) {
    const { userId, data } = req.body;
}

In this example, the agent that handles the hook is the agent with a sessionId that matches req.body.userId.

The HookRequest helper

The HookRequest helper is a utility object to help you parse the hook request.

It has 3 methods:

  • Body(key: string): Parses the body of the request as JSON, and returns the value of the key.
  • Query(key: string): Returns the value of the query parameter.
  • Headers(key: string): Returns the value of the header parameter.

You can also use the HookRequest object to get the session id from the request.

Example Usage:

  • HookRequest.Body('userId'): references req.body.userId
  • HookRequest.Body('user.id'): references req.body.user.id
  • HookRequest.Query('sessionId'): references req.query.sessionId
  • HookRequest.Headers('x-session-id'): references req.headers['x-session-id']

Jobs

When you declare a job as non-static, it will be scheduled on every session of the agent that is created.

@job('* * * * *')
async sessionJob() {
    console.log('This job will run for every session of the agent')
}

This can be helpful for tasks that are user-specific, and should be run for each user.