Create isolated sessions
A common agent configuration allows you to encode the behavior and functionality all instances of the agent will share. Customer- and task-specific data lives at the session level. Two sessions can use the same saved agent and still have separate messages, tool results, files, and credentials.
To run code, the agent needs an environment. An OpenAI-hosted environment provides an isolated workspace, or sandbox, for files and commands. To let the agent access systems that require authentication, attach a vault that holds credentials such as API tokens. Your app decides which resources to attach and which application users can interact with a session.
Assign resources to a session
Here are the key components of a session you can specify when you create it.
| Field | What it selects |
|---|---|
agent_id |
The saved agent whose model, instructions, and tools the session copies. |
environment |
Set type to openai_hosted for a new workspace. Choose its initial files and network access. |
vault_ids |
The vaults that supply credentials. Attach only the vaults this session needs. |
In your app, associate the returned session id and environment.id with the user or customer who owns the session. Use the session ID to send a task. Use the environment ID to work with files once the workspace reports connected.
Example: Isolate each customer’s integration review
Each customer has already authorized these reviews and supplied a GitHub token with read-only access to its own repository. Herringbone stores each token in a dedicated vault.
When the API changes, Herringbone creates both sessions using the same shared agent configuration. Each call to agents.sessions.create attaches the customer’s vault and copies its test data into a new workspace. The examples omit input, so both sessions start idle, with no work in progress.
To start each review, Herringbone’s app sends a message to the session describing the change and asking the agent to propose any necessary updates. It could also include that task at creation.
In the Python examples, agents is OpenAI().beta.agents and db is a SQLite database. The customer tabs show which vault and test data Herringbone selects for each session. Shared backend shows the access checks. Full program sets up both reviews and tests those checks.
Herringbone gives the agent two pages of sample payments so it can check whether the export includes every payment exactly once. The app saves the session and workspace IDs in its review database. When a finance user opens the review, the app checks their access and lists its files.
export_token = os.environ["CUSTOMER_A_GITHUB_TOKEN"]
export_vault = create_repository_vault(
agents, cleanup, "customer-a/payments-export", export_token
)
export_session = agents.sessions.create(
agent_id=shared_agent_id,
vault_ids=[export_vault],
environment={
"type": "openai_hosted",
"network": {
"access": "restricted",
"allowed_domains": ["api.github.com"],
},
"files": [inline_file("/workspace/export-pages.json", export_pages)],
},
)
save_session(db, "customer-a", "payments-export", export_session)
export_review = inspect_customer_session(
agents, db, "finance-user", "customer-a", "payments-export"
)For the proxy review, the agent needs to compare the URL the app sends with the URL the proxy should forward. Herringbone supplies a sample of both and saves this session and workspace under Customer B’s integration. A member of the proxy team can then open the review.
proxy_token = os.environ["CUSTOMER_B_GITHUB_TOKEN"]
proxy_vault = create_repository_vault(
agents, cleanup, "customer-b/payments-proxy", proxy_token
)
proxy_session = agents.sessions.create(
agent_id=shared_agent_id,
vault_ids=[proxy_vault],
environment={
"type": "openai_hosted",
"network": {
"access": "restricted",
"allowed_domains": ["api.github.com"],
},
"files": [inline_file("/workspace/proxy-request.json", proxy_request)],
},
)
save_session(db, "customer-b", "payments-proxy", proxy_session)
proxy_review = inspect_customer_session(
agents, db, "proxy-user", "customer-b", "payments-proxy"
)Both workspaces need to reach api.github.com to read code.
The environment’s allowed_domains permits that connection.
Inside the workspace, GITHUB_TOKEN contains a placeholder.
On HTTPS requests to a host in the credential’s allowed_hosts,
OpenAI’s network proxy replaces the placeholder with the token.
GitHub enforces the token’s repository permissions.
def create_repository_vault(agents, cleanup, repository, token):
vault = agents.vaults.create(name=repository)
cleanup.callback(agents.vaults.delete, vault.id)
agents.vaults.credentials.create(
vault.id,
name="GitHub repository token",
auth={
"type": "environment_variable",
"secret_name": "GITHUB_TOKEN",
"secret_value": token,
"networking": {"type": "limited", "allowed_hosts": ["api.github.com"]},
},
)
return vault.id
def inline_file(path, test_data):
encoded = base64.b64encode(json.dumps(test_data).encode()).decode()
return {"type": "inline", "path": path, "data": encoded}Herringbone’s backend reads its own membership database using the user ID
from its sign-in system. The query returns the session and environment IDs
only for an integration the user can access. The backend then waits for
the environment to report connected before listing files.
def save_session(db, customer, integration, session):
with db:
db.execute(
"""INSERT INTO reviews (customer, integration, session_id, environment_id)
VALUES (?, ?, ?, ?)""",
(customer, integration, session.id, session.environment.id),
)
def inspect_customer_session(agents, db, signed_in_user, customer, integration):
row = db.execute(
"""SELECT session_id, environment_id FROM reviews
JOIN memberships USING (customer, integration)
WHERE user_id = ? AND customer = ? AND integration = ?""",
(signed_in_user, customer, integration),
).fetchone()
if row is None:
raise PermissionError("No access to this review")
session_id, environment_id = row
session = agents.sessions.retrieve(session_id)
deadline = time.monotonic() + 120
while time.monotonic() < deadline:
status = agents.environments.retrieve(environment_id).status
if status == "connected":
files = agents.environments.files.list(environment_id, path="/workspace")
return session.id, environment_id, [file.path for file in files]
if status in {"failed", "expired", "disconnected", "suspended"}:
raise RuntimeError(f"Workspace is {status}")
time.sleep(2)
raise TimeoutError("Workspace did not connect in time")Copy the program into isolate-customer-sessions.py. Set shared_agent_id to the ID of a saved agent in your project. Set OPENAI_API_KEY to a project key with vault permissions. Set CUSTOMER_A_GITHUB_TOKEN and CUSTOMER_B_GITHUB_TOKEN to read-only tokens for two repositories you control.
With uv, a Python package manager, run uv run --with openai==3.42.0 python isolate-customer-sessions.py. Expect Cross-customer access denied when the finance user tries to open the proxy review, then the IDs and files for each authorized review. The program tests Herringbone’s access checks without sending a task or calling GitHub. It deletes the sessions and vaults it created when it exits.
"""Set up isolated export and proxy reviews with one saved Herringbone agent."""
import base64
import json
import os
import sqlite3
import time
from contextlib import ExitStack, closing
from pathlib import Path
from tempfile import TemporaryDirectory
from openai import ConflictError, OpenAI
def create_repository_vault(agents, cleanup, repository, token):
vault = agents.vaults.create(name=repository)
cleanup.callback(agents.vaults.delete, vault.id)
agents.vaults.credentials.create(
vault.id,
name="GitHub repository token",
auth={
"type": "environment_variable",
"secret_name": "GITHUB_TOKEN",
"secret_value": token,
"networking": {"type": "limited", "allowed_hosts": ["api.github.com"]},
},
)
return vault.id
def inline_file(path, test_data):
encoded = base64.b64encode(json.dumps(test_data).encode()).decode()
return {"type": "inline", "path": path, "data": encoded}
def delete_session(agents, session_id):
for attempt in range(10):
try:
agents.sessions.delete(session_id)
return
except ConflictError:
if attempt == 9:
raise
time.sleep(2)
def initialize_store(db):
db.executescript("""
CREATE TABLE reviews (
customer TEXT, integration TEXT, session_id TEXT UNIQUE,
environment_id TEXT UNIQUE, PRIMARY KEY (customer, integration)
);
CREATE TABLE memberships (
user_id TEXT, customer TEXT, integration TEXT,
PRIMARY KEY (user_id, customer, integration)
);
INSERT INTO memberships VALUES
('finance-user', 'customer-a', 'payments-export'),
('proxy-user', 'customer-b', 'payments-proxy');
""")
def save_session(db, customer, integration, session):
with db:
db.execute(
"""INSERT INTO reviews (customer, integration, session_id, environment_id)
VALUES (?, ?, ?, ?)""",
(customer, integration, session.id, session.environment.id),
)
def inspect_customer_session(agents, db, signed_in_user, customer, integration):
row = db.execute(
"""SELECT session_id, environment_id FROM reviews
JOIN memberships USING (customer, integration)
WHERE user_id = ? AND customer = ? AND integration = ?""",
(signed_in_user, customer, integration),
).fetchone()
if row is None:
raise PermissionError("No access to this review")
session_id, environment_id = row
session = agents.sessions.retrieve(session_id)
deadline = time.monotonic() + 120
while time.monotonic() < deadline:
status = agents.environments.retrieve(environment_id).status
if status == "connected":
files = agents.environments.files.list(environment_id, path="/workspace")
return session.id, environment_id, [file.path for file in files]
if status in {"failed", "expired", "disconnected", "suspended"}:
raise RuntimeError(f"Workspace is {status}")
time.sleep(2)
raise TimeoutError("Workspace did not connect in time")
def print_review(customer, integration, review):
session_id, environment_id, files = review
print(
json.dumps(
dict(
customer=customer,
integration=integration,
session_id=session_id,
environment_id=environment_id,
files=files,
)
)
)
def main():
with ExitStack() as cleanup:
agents = cleanup.enter_context(OpenAI()).beta.agents
directory = cleanup.enter_context(TemporaryDirectory())
db = cleanup.enter_context(
closing(sqlite3.connect(Path(directory) / "reviews.db"))
)
initialize_store(db)
shared_agent_id = "agent_abc123" # Use the id returned by POST /v1/agents for your saved agent.
export_pages = [
{
"payments": [
{"payment_id": "p1", "amount": 10},
{"payment_id": "p2", "amount": 20},
],
"next_cursor": "c2",
},
{"payments": [{"payment_id": "p3", "amount": 30}], "next_cursor": None},
]
export_token = os.environ["CUSTOMER_A_GITHUB_TOKEN"]
export_vault = create_repository_vault(
agents, cleanup, "customer-a/payments-export", export_token
)
export_session = agents.sessions.create(
agent_id=shared_agent_id,
vault_ids=[export_vault],
environment={
"type": "openai_hosted",
"network": {
"access": "restricted",
"allowed_domains": ["api.github.com"],
},
"files": [inline_file("/workspace/export-pages.json", export_pages)],
},
)
cleanup.callback(delete_session, agents, export_session.id)
save_session(db, "customer-a", "payments-export", export_session)
proxy_request = {
"incoming": "/proxy/payments?cursor=c2",
"outgoing": "/v1/payments?cursor=c2",
}
proxy_token = os.environ["CUSTOMER_B_GITHUB_TOKEN"]
proxy_vault = create_repository_vault(
agents, cleanup, "customer-b/payments-proxy", proxy_token
)
proxy_session = agents.sessions.create(
agent_id=shared_agent_id,
vault_ids=[proxy_vault],
environment={
"type": "openai_hosted",
"network": {
"access": "restricted",
"allowed_domains": ["api.github.com"],
},
"files": [inline_file("/workspace/proxy-request.json", proxy_request)],
},
)
cleanup.callback(delete_session, agents, proxy_session.id)
save_session(db, "customer-b", "payments-proxy", proxy_session)
try:
inspect_customer_session(
agents, db, "finance-user", "customer-b", "payments-proxy"
)
except PermissionError:
print("Cross-customer access denied")
else:
raise AssertionError("Finance user could access the proxy review")
export_review = inspect_customer_session(
agents, db, "finance-user", "customer-a", "payments-export"
)
print_review("customer-a", "payments-export", export_review)
proxy_review = inspect_customer_session(
agents, db, "proxy-user", "customer-b", "payments-proxy"
)
print_review("customer-b", "payments-proxy", proxy_review)
if __name__ == "__main__":
main()