All Products
Search
Document Center

AgentBay:Sessions

Last Updated:Dec 23, 2025

Description

The Session class represents a session in the AgentBay cloud environment. It provides methods to manage the file system and execute commands.

Method

Description

Environment

Linux Computer Use

WindowsComputer Use

Browser Use

Mobile Use

Code Space

create

Creates a new session in the AgentBay cloud environment.

Supported

Supported

Supported

Supported

Supported

delete

Deletes a session by its ID.

Not supported

Not supported

Not supported

Not supported

Not supported

get_link

Gets the link for this session.

Supported

Supported

Supported

Supported

Supported

list

Lists all available sessions.

Not supported

Not supported

Not supported

Not supported

Not supported

info

Gets information about this session.

Not supported

Not supported

Not supported

Not supported

Not supported

set_labels

Sets labels for this session.

Not supported

Not supported

Not supported

Not supported

Not supported

get_labels

Gets the labels for this session.

Not supported

Not supported

Not supported

Not supported

Not supported

Properties

Property name

Description

agent_bay

The AgentBay instance that created this session.

session_id

The ID of this session.

resource_url

The URL of the resource associated with this session.

file_system

The FileSystem instance for this session.

command

The Command instance for this session.

oss

The Object Storage Service (OSS) instance for this session.

application

The ApplicationManager instance for this session.

window

The WindowManager instance for this session.

ui

The UI instance for this session.

context

The FileSystem instance for this session.

Methods

delete - Delete a session

Golang

Delete() (*DeleteResult, error)

Return values

  • *DeleteResult: A result object that contains the success status and request ID.

  • error: An error message if the delete operation fails.

Example

package main

import (
	"fmt"
	"os"

	"github.com/aliyun/wuying-agentbay-sdk/golang/pkg/agentbay"
)

func main() {
	// Initialize the SDK.
	client, err := agentbay.NewAgentBay("your_api_key", nil)
	if err != nil {
		fmt.Printf("Error initializing AgentBay client: %v\n", err)
		os.Exit(1)
	}

	// Create a session.
	createResult, err := client.Create(nil)
	if err != nil {
		fmt.Printf("Error creating session: %v\n", err)
		os.Exit(1)
	}
	
	session := createResult.Session
	fmt.Printf("Session created with ID: %s\n", session.SessionID)
	
	// Use the session...
	
	// Delete the session.
	deleteResult, err := session.Delete()
	if err != nil {
		fmt.Printf("Error deleting session: %v\n", err)
		os.Exit(1)
	}
	
	fmt.Println("Session deleted successfully")
	fmt.Printf("Request ID: %s\n", deleteResult.RequestID)
}

Python

delete() -> DeleteResult

Return value

  • DeleteResult: A result object that contains the success status, request ID, and error message.

Example

from agentbay import AgentBay

# Initialize the SDK.
agent_bay = AgentBay(api_key="your_api_key")

# Create a session.
result = agent_bay.create()
if result.success:
    session = result.session
    print(f"Session created successfully. ID: {session.session_id}")
    
    # Use the session...
    
    # Delete the session.
    delete_result = session.delete()
    if delete_result.success:
        print("Session deleted successfully")
    else:
        print(f"Failed to delete session: {delete_result.error_message}")

TypeScript

delete(): Promise<DeleteResult>=

Return value

  • Promise<DeleteResult>: A promise that resolves to a result object. The object contains the success status, request ID, and error message.

Example

import { AgentBay } from 'wuying-agentbay-sdk';

// Initialize the SDK.
const agentBay = new AgentBay({ apiKey: 'your_api_key' });

// Create and delete a session.
async function createAndDeleteSession() {
  try {
    const result = await agentBay.create();
    if (result.success) {
      const session = result.session;
      console.log(`Session created successfully. ID: ${session.sessionId}`);
      
      // Use the session...
      
      // Delete the session.
      const deleteResult = await session.delete();
      if (deleteResult.success) {
        console.log('Session deleted successfully');
      } else {
        console.log(`Failed to delete session: ${deleteResult.errorMessage}`);
      }
    }
  } catch (error) {
    console.error('Error:', error);
  }
}

createAndDeleteSession();

set_labels - Set session labels

Golang

SetLabels(labels map[string]string) (*models.Response, error)

Parameter

  • labels (map[string]string): A map of key-value pairs that represents the labels to set.

Return values

  • *models.Response: A response object that contains the request ID and status information.

  • error: An error message if the labels fail to be set.

Example

// Set session labels.
labels := map[string]string{
	"project":     "demo",
	"environment": "testing",
	"version":     "1.0.0",
}

response, err := session.SetLabels(labels)
if err != nil {
	fmt.Printf("Error setting labels: %v\n", err)
	os.Exit(1)
}

fmt.Println("Labels set successfully")
fmt.Printf("Request ID: %s\n", response.RequestID)

Python

set_labels(labels: Dict[str, str]) -> OperationResult

Parameter

  • labels (Dict[str, str]): A dictionary of key-value pairs that represents the labels to set.

Return value

  • OperationResult: A result object that contains the success status, request ID, and error message.

Exception

  • AgentBayError: Raised if the label setting operation fails due to an API error or other issues.

Example

# Set session labels.
labels = {
    "project": "demo",
    "environment": "testing",
    "version": "1.0.0"
}
result = session.set_labels(labels)
if result.success:
    print("Labels set successfully")
else:
    print(f"Failed to set labels: {result.error_message}")

TypeScript

setLabels(labels: Record<string, string>): Promise<OperationResult>

Parameter

  • labels (Record<string, string>): An object of key-value pairs that represents the labels to set.

Return value

  • Promise<OperationResult>: A promise that resolves to a result object. The object contains the request ID and status information.

Example

// Set session labels.
async function setSessionLabels(session: Session) {
  try {
    const labels = {
      project: 'demo',
      environment: 'testing',
      version: '1.0.0'
    };
    
    const result = await session.setLabels(labels);
    console.log(`Labels set successfully. Request ID: ${result.requestId}`);
    return result;
  } catch (error) {
    console.error(`Failed to set labels: ${error}`);
    throw error;
  }
}

get_labels - Get session labels

Golang

GetLabels() (map[string]string, error)

Return values

  • map[string]string: A map that contains the key-value pairs of the session labels.

  • error: An error message if the labels cannot be retrieved.

Example

// Get session labels.
labels, err := session.GetLabels()
if err != nil {
	fmt.Printf("Error getting labels: %v\n", err)
	os.Exit(1)
}

fmt.Println("Session labels:")
for key, value := range labels {
	fmt.Printf("%s: %s\n", key, value)
}

Python

get_labels() -> Dict[str, str]

Return value

  • Dict[str, str]: A dictionary that contains the key-value pairs of the session labels.

Exception

  • AgentBayError: Raised if the labels cannot be retrieved due to an API error or other issues.

Example

# Get session labels.
try:
    labels = session.get_labels()
    print(f"Session labels: {labels}")
except AgentBayError as e:
    print(f"Failed to get labels: {e}")

TypeScript

getLabels(): Promise<LabelResult>

Return value

  • Promise<LabelResult>: A promise that resolves to a result object. The object contains the session labels, request ID, and success status.

Example

// Get session labels.
async function getSessionLabels(session: Session) {
  try {
    const result = await session.getLabels();
    console.log(`Session labels: ${JSON.stringify(result.labels)}`);
    console.log(`Request ID: ${result.requestId}`);
    return result.labels;
  } catch (error) {
    console.error(`Failed to get labels: ${error}`);
    throw error;
  }
}

info - Get session information

Golang

Info() (*SessionInfo, error)

Return values

  • *SessionInfo: An object that contains session information, such as SessionID, ResourceURL, and AppID.

  • error: An error message if the session information cannot be retrieved.

Example

// Get session information.
info, err := session.Info()
if err != nil {
	fmt.Printf("Error getting session info: %v\n", err)
	os.Exit(1)
}

fmt.Printf("Session ID: %s\n", info.SessionID)
fmt.Printf("Resource URL: %s\n", info.ResourceURL)
fmt.Printf("App ID: %s\n", info.AppID)

Python

info() -> SessionInfo

Return value

  • SessionInfo: An object that contains session information, such as session_id, resource_url, and app_id.

Exception

  • AgentBayError: Raised if the information cannot be retrieved due to an API error or other issues.

Example

# Get session information.
try:
    info = session.info()
    print(f"Session ID: {info.session_id}")
    print(f"Resource URL: {info.resource_url}")
    print(f"Application ID: {info.app_id}")
except AgentBayError as e:
    print(f"Failed to get session information: {e}")

TypeScript

info(): Promise<InfoResult>

Return value

  • Promise<InfoResult>: A promise that resolves to a result object. The object contains session information, such as sessionId and resourceUrl, the request ID, and the success status.

Example

// Get session information.
async function getSessionInfo(session: Session) {
  try {
    const result = await session.info();
    console.log(`Session ID: ${result.data.sessionId}`);
    console.log(`Resource URL: ${result.data.resourceUrl}`);
    console.log(`Request ID: ${result.requestId}`);
    return result.data;
  } catch (error) {
    console.error(`Failed to get session information: ${error}`);
    throw error;
  }
}

get_link - Get a session link

Golang

GetLink(protocolType string, port int) (string, error)

Parameters

  • protocolType (string): The protocol type of the link, such as http or https. If this parameter is empty, the default protocol is used.

  • port (int): The port number of the link. If this parameter is 0, the default port is used.

Return values

  • string: The session link, such as https://example.com/session/123:8443.

  • error: An error message if the link cannot be retrieved.

Example

// Get the session link using the default protocol and port.
link, err := session.GetLink("", 0)
if err != nil {
	fmt.Printf("Error getting link: %v\n", err)
	os.Exit(1)
}

fmt.Printf("Session link: %s\n", link)

// Get the link with a custom protocol and port.
customLink, err := session.GetLink("https", 8443)
if err != nil {
	fmt.Printf("Error getting custom link: %v\n", err)
	os.Exit(1)
}

fmt.Printf("Custom link: %s\n", customLink)

Python

get_link(protocol_type: Optional[str] = None, port: Optional[int] = None) -> str

Parameters

  • protocol_type (str, optional): The protocol type of the link, such as "http" or "https". If you do not specify this parameter, the default protocol is used.

  • port (int, optional): The port number of the link. If this parameter is None, the default port is used.

Return value

  • str: The session link, such as https://example.com/session/123:8443.

Exception

  • AgentBayError: Raised if the link cannot be retrieved due to an API error or other issues.

Example

# Get the session link.
try:
    link = session.get_link()
    print(f"Session link: {link}")
    
    # Get the link with a custom protocol and port.
    custom_link = session.get_link("https", 8443)
    print(f"Custom link: {custom_link}")
except AgentBayError as e:
    print(f"Failed to get the link: {e}")

TypeScript

getLink(protocolType?: string, port?: number): Promise<LinkResult>

Parameters

  • protocolType (string, optional): The protocol type of the link, such as "http" or "https". If this parameter is not specified, the default protocol is used.

  • port (number, optional): The port number of the link. If this parameter is not specified, the default port is used.

Return value

  • Promise<LinkResult>: A promise that resolves to a result object. The object contains the session link, request ID, and success status.

Example

// Get the session link.
async function getSessionLink(session: Session) {
  try {
    const result = await session.getLink();
    console.log(`Session link: ${result.data}`);
    console.log(`Request ID: ${result.requestId}`);
    
    // Get the link with a custom protocol and port.
    const customResult = await session.getLink('https', 8443);
    console.log(`Custom link: ${customResult.data}`);
    
    return result.data;
  } catch (error) {
    console.error(`Failed to get the link: ${error}`);
    throw error;
  }
}