Sessions¶
Session Container¶
agora_workbench.code_execution.sessions.session.Session(session_id, data, session_type, user_identity, user_token, token_claims, metadata=None)
¶
Bases: Generic[T]
Generic session container managing stateful data across MCP server interactions.
Sessions provide lifecycle management, ownership tracking, and metadata storage for persistent resources like code execution environments, database connections, or computation state. Each session is owned by a specific user (identified via JWT token claims) and tracks access patterns, status transitions, and cleanup requirements.
Attributes:
| Name | Type | Description |
|---|---|---|
session_id |
str
|
Unique identifier for the session. |
data |
T
|
The session's payload data, type-parameterized for type safety. |
session_type |
str
|
Categorizes session type (e.g., "python", "database"). |
user_identity |
str
|
Owner's composite identifier from JWT token ( |
user_token |
str
|
User's bearer token for authentication. |
metadata |
Dict
|
Optional key-value metadata for session configuration. |
token_claims |
Dict
|
Optional cached JWT token claims for session authorization. These claims are used to restore authentication context without re-validating the JWT token. Intentionally excluded from get_info() for security. |
created_at |
datetime
|
Timestamp when session was created. |
last_accessed |
datetime
|
Timestamp of most recent session access. |
status |
str
|
Current session state (e.g., "created", "active", "error"). |
data_manager |
DataLakeDataManager
|
Manager for DataLake asset access. |
Example
from .session import Session session = Session( ... session_id="sess_123", ... data={"counter": 0}, ... session_type="demo", ... user_identity="user-oid-xyz", ... user_token="eyJ...", ... metadata={"version": "1.0"}, ... token_claims={"oid": "user-oid-xyz", "exp": 1234567890}, ... ) session.touch() # Update last accessed time session.update_status("active") info = session.get_info()
Source code in src/agora_workbench/code_execution/sessions/session.py
touch()
¶
update_status(new_status)
¶
Update session status with history tracking.
get_info()
¶
Return session information.
Source code in src/agora_workbench/code_execution/sessions/session.py
cleanup()
¶
Cleanup session resources including session files.
Raises:
| Type | Description |
|---|---|
Exception
|
If cleanup fails, to allow calling code to handle the failure |
Source code in src/agora_workbench/code_execution/sessions/session.py
Session Manager¶
agora_workbench.code_execution.sessions.manager.SessionManager(config=None)
¶
Manages the lifecycle of code-execution sessions and their Jupyter kernels.
Responsibilities include session creation, retrieval, timeout-based cleanup,
kernel provisioning (one AsyncKernelManager per session), background-job
tracking, and artifact registration for the /artifacts download endpoint.
Thread-safety is provided by an internal RLock for session-lifecycle
mutations and per-session asyncio.Lock instances for kernel access.
Source code in src/agora_workbench/code_execution/sessions/manager.py
create_session(data, user_identity, user_token, token_claims, metadata=None, session_id=None)
¶
Create a new session and return its ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
The data/object to store in the session |
required |
user_identity
|
str
|
User identity (Entra ID, email, etc.) |
required |
user_token
|
str
|
User's bearer token for authentication |
required |
metadata
|
Optional[dict]
|
Optional metadata dict |
None
|
session_id
|
Optional[str]
|
Optional custom session ID (default: UUID) |
None
|
token_claims
|
dict
|
Cached JWT claims for the user token. Stored on the session so that background tasks can restore the full auth context without re-validating the token. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Session ID string |
Source code in src/agora_workbench/code_execution/sessions/manager.py
get_session(session_id)
¶
Get a session by ID, updating its access time.
Returns:
| Type | Description |
|---|---|
Session
|
Session object |
Raises:
| Type | Description |
|---|---|
ValueError
|
If session not found or expired |
Source code in src/agora_workbench/code_execution/sessions/manager.py
update_session(session_id, session)
¶
Update an existing session.
Source code in src/agora_workbench/code_execution/sessions/manager.py
update_status(session_id, status)
¶
Update the status of a session.
close_session(session_id)
¶
Explicitly close a session.
Attempts to clean up resources first. If cleanup fails, the session is still deleted to prevent session accumulation, but the error is logged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id
|
str
|
ID of the session to close |
required |
Source code in src/agora_workbench/code_execution/sessions/manager.py
get_artifact_record(session_id, token)
¶
Look up an artifact for the download endpoint.
Returns None for unknown sessions/tokens and for tokens whose
backing file has been removed — both surface as 404 at the HTTP
layer.
Source code in src/agora_workbench/code_execution/sessions/manager.py
find_artifact_by_name(session_id, artifact_name)
¶
Find a registered artifact by its relative name within a session.
Looks up a previously registered artifact (i.e. one that was discovered during a snapshot-diff after an execute) by its relative filename. This is used by the publish pipeline to resolve the local path of an artifact before pushing it to remote storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id
|
str
|
The session that owns the artifact. |
required |
artifact_name
|
str
|
Relative filename as registered (e.g. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
The |
Optional[_ArtifactRecord]
|
class: |
Optional[_ArtifactRecord]
|
exists, otherwise |
Source code in src/agora_workbench/code_execution/sessions/manager.py
start_background_execution_for_session(session_id, code, timeout, working_dir=None)
async
¶
Start execution and return immediately with a background job id.
Source code in src/agora_workbench/code_execution/sessions/manager.py
start_promoted_execution_for_session(session_id, code, timeout, promotion_threshold_s, working_dir=None)
async
¶
Execute code synchronously, promoting to a background job if it exceeds the threshold.
Starts executing like the normal foreground path. If the kernel reaches
idle within promotion_threshold_s seconds the result is returned
as a (stdout, stderr, success, displays, artifacts) tuple — identical
to :meth:execute_code_for_session. If the threshold expires while the
kernel is still busy, the in-flight execution is registered as a
:class:_BackgroundJob and a job-handle dict is returned instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id
|
str
|
Session identifier. |
required |
code
|
str
|
Python code to execute. This method applies the outputs and token preambles internally (same as the foreground path), so callers should pass the raw user code — not pre-preambled. |
required |
timeout
|
float
|
Total execution timeout in seconds. |
required |
promotion_threshold_s
|
float
|
Seconds to wait before promoting. |
required |
working_dir
|
Optional[str]
|
Optional working directory for the kernel. |
None
|
Returns:
| Type | Description |
|---|---|
Tuple[str, str, bool, list[dict], list[dict]] | dict[str, Any]
|
Either the 5-tuple |
Tuple[str, str, bool, list[dict], list[dict]] | dict[str, Any]
|
when the execution completes within the threshold, or a dict with |
Tuple[str, str, bool, list[dict], list[dict]] | dict[str, Any]
|
|
Source code in src/agora_workbench/code_execution/sessions/manager.py
851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 | |
check_background_job(job_id, caller_identity=None)
¶
Return current status/output for a background job.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_id
|
str
|
Background job identifier. |
required |
caller_identity
|
Optional[str]
|
When provided, the caller's user identity is compared to
the identity that submitted the job. Both a missing job and an identity
mismatch raise |
None
|
Source code in src/agora_workbench/code_execution/sessions/manager.py
await_background_job(job_id)
async
¶
Wait for a background job's task to reach a terminal state, then return its status.
Returns None if the job was never registered or has already been purged.
Used by the activity publisher to emit job_finished events; callers must
treat exceptions on the underlying task as terminal (a failed task still
leaves _BackgroundJob.status set by _collect_background_job).
Source code in src/agora_workbench/code_execution/sessions/manager.py
execute_code_for_session(session_id, code, timeout, working_dir=None)
async
¶
Execute code in the session's Jupyter kernel.
Concurrent calls for the same session_id are serialized by a
per-session asyncio.Lock so they cannot race on the shared
Jupyter KernelClient iopub stream.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id
|
str
|
Session identifier |
required |
code
|
str
|
Python code to execute |
required |
timeout
|
float
|
Execution timeout in seconds |
required |
working_dir
|
Optional[str]
|
Optional working directory for kernel |
None
|
Returns:
| Type | Description |
|---|---|
str
|
Tuple of |
str
|
|
bool
|
with MIME type, data, and metadata fields. |
list[dict]
|
metadata for each new or modified file under the session output |
list[dict]
|
directory, including its name, size, MIME type, modification time, |
Tuple[str, str, bool, list[dict], list[dict]]
|
and download token. |
Source code in src/agora_workbench/code_execution/sessions/manager.py
cleanup_idle_kernels(max_idle_time=3600.0)
async
¶
Cleanup kernels that have been idle for too long.
Source code in src/agora_workbench/code_execution/sessions/manager.py
list_sessions()
¶
List all active sessions with metadata.
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
List of session info dicts |
Source code in src/agora_workbench/code_execution/sessions/manager.py
Session Configuration¶
agora_workbench.code_execution.sessions.manager.SessionConfig(max_sessions=100, timeout_minutes=30, cleanup_interval_seconds=300, storage_backend=None)
¶
Configuration for session manager.