Skip to main content

Let Diagrid start and stop your agent's AgentCore sessions

With Diagrid-managed sessions, Diagrid runs your agent in an Amazon Bedrock AgentCore session only while the agent has work. Diagrid calls this serverless compute: it's what the --compute options of the Diagrid CLI set up. Your clients start runs through Diagrid, not through AgentCore. When the agent has pending work and no worker is connected, Diagrid starts an AgentCore session, whose container connects as the agent's worker. When the agent has had no work for a cooldown period, Diagrid stops the session.

This guide attaches serverless compute to the agent from AgentCore hosted agents, and runs the agent's front end on your machine.

A run in a Diagrid-managed sessionpending work, no workerno work for the cooldownstart runAssumeRoleWithWebIdentityInvokeAgentRuntime {}start sessionconnect as workerrun stepsresultStopRuntimeSessionFront endyour machineDiagridthe agent's IDAWSSTS, AgentCoreWorkerAgentCore sessionFront endyour machineDiagridthe agent's IDAWSSTS, AgentCoreWorkerAgentCore session
A run in a Diagrid-managed sessionDiagrid acts in your AWS account as a role that trusts only this agent's ID, the agent's workload identity. It stores no AWS credentials.

How it works​

  • When a worker starts. The agent has pending or in-flight work, such as a run a client started, and no worker is connected. Diagrid starts one worker. A worker that crashes is replaced.
  • When a worker stops. The agent has had no pending and no in-flight work for the cooldown, 300 seconds by default. Work that arrives in bursts keeps the worker.
  • How Diagrid reaches AWS. Diagrid gets a short-lived token for the agent's ID from the region's OIDC issuer, and exchanges it with AWS STS for credentials of an IAM role in your account. The role trusts only this agent's ID, and may only start and stop sessions of one Runtime. CloudTrail records the agent's SPIFFE ID as the web identity of each call.
  • Which code a worker runs. By default, Diagrid invokes the Runtime's DEFAULT endpoint, so new workers run the Runtime's newest version. You can pin a version with a named endpoint. See Pin a code version.

What the worker must do​

Diagrid starts a worker by invoking a new session with an empty JSON body, {}. The container must:

  • Not connect to Diagrid when the process starts. AgentCore runs the process once to take the snapshot it restores every session from. A connection opened then is in every session, already closed.
  • Start the worker on the first POST /invocations, and start nothing on a repeated one.
  • Answer HealthyBusy on GET /ping while the worker runs, so AgentCore doesn't end the session at its idle timeout.
  • Never stop the worker on its own.

AgentcoreRunner from the Diagrid package takes care of all of this. See the reference.

Prerequisites​

  • AgentCore hosted agents completed, with its CloudFormation stack and its secret kept, and its environment variables set in your terminal.
  • The Diagrid CLI, version 1.146.0 or later.
  • Permission in the AWS account to create an IAM role, an IAM OIDC identity provider and a CloudFormation stack.

1. Keep worker sessions running​

Set AGENT_WORKER_KEEPALIVE on the Runtime, so that a session answers HealthyBusy once its worker runs. The session then runs until Diagrid stops it, or until the Runtime's maximum lifetime, 8 hours by default. Deploy the stack from step 4 of AgentCore hosted agents again from the budget-planner folder, with KeepAlive set to true. The other parameters keep their values:

aws cloudformation deploy --region "$AWS_REGION" --stack-name agentcore-quickstart-budget-planner \
--template-file template.yaml --capabilities CAPABILITY_NAMED_IAM \
--parameter-overrides KeepAlive=true

Every worker is replaced when it reaches the Runtime's maximum lifetime. Work it holds goes back to the queue and runs on the next worker, and an activity longer than the maximum lifetime can't complete.

Check that the Runtime is READY again, as in step 4 of AgentCore hosted agents.

From now on, a session you start yourself with invoke-agent-runtime, as in step 5 of AgentCore hosted agents, also keeps running. Its worker stays connected to Diagrid and takes the agent's runs, so Diagrid doesn't start a session of its own. If you invoked the Runtime after this step, stop that session, using the session ID of that invocation:

aws bedrock-agentcore stop-runtime-session --region "$AWS_REGION" --agent-runtime-arn "$RUNTIME_ARN" --runtime-session-id "$SESSION_ID"

2. Generate the AWS setup​

diagrid agent compute setup writes the IAM resources that let Diagrid start and stop sessions of the Runtime, as a CloudFormation template or as Terraform:

  • An IAM OIDC identity provider for the issuer of each region the project runs in.
  • An IAM role, named diagrid-budget-planner-invoker, that trusts the agent's ID in each of those regions, and only that ID.
  • A policy on the role that allows bedrock-agentcore:InvokeAgentRuntime and bedrock-agentcore:StopRuntimeSession on the Runtime and its endpoints.

Generate the CloudFormation template:

diagrid agent compute setup budget-planner --project agentcore-quickstart \
--compute aws-agentcore --compute-agentcore-runtime-arn "$RUNTIME_ARN" \
--output cloudformation > invoker.yaml

Without --output, the command writes Terraform. --role-name sets another name for the role.

An AWS account has one IAM OIDC provider per issuer, shared by every agent that uses the account in that region. If the account already has one for the region's issuer, remove it from the template, or import it, before you apply. A project in a region group gets one provider and one trust entry per member region, so trust keeps working when the project fails over.

3. Apply the setup​

The template names the role, so deploying it needs CAPABILITY_NAMED_IAM. Deploy the stack and read the role's ARN from its outputs:

aws cloudformation deploy --region "$AWS_REGION" --stack-name diagrid-budget-planner-invoker \
--template-file invoker.yaml --capabilities CAPABILITY_NAMED_IAM
export INVOKER_ROLE_ARN="$(aws cloudformation describe-stacks --region "$AWS_REGION" \
--stack-name diagrid-budget-planner-invoker \
--query "Stacks[0].Outputs[?OutputKey=='RoleArn'].OutputValue" --output text)"
echo "$INVOKER_ROLE_ARN"

The ARN ends with role/diagrid-budget-planner-invoker.

4. Attach the serverless compute​

Attach the Runtime and the role to the agent:

diagrid agent update budget-planner --project agentcore-quickstart \
--compute aws-agentcore \
--compute-agentcore-runtime-arn "$RUNTIME_ARN" \
--compute-agentcore-role-arn "$INVOKER_ROLE_ARN"
diagrid agent get budget-planner --project agentcore-quickstart -o json | jq '.status.appIds[0].spec.compute'

The compute settings show the provider awsAgentCore with the Runtime ARN, the DEFAULT endpoint and the role ARN, and the scaling settings.

5. Run the front end​

The front end starts runs through Diagrid and executes none of them. It is the same main.py, with AGENT_WORKER set to false. In the budget-planner folder, with the variables from the quickstart's steps 5 and 6 set:

AGENT_WORKER=false uv run python main.py

The front end and the workers must run the same main.py, because the worker reads the agent's prompt, model and tools from it.

6. Send a task​

From another terminal, create a new session ID and send the quickstart's request with it:

export SESSION_ID="serverless-$(uuidgen)"
curl -X POST http://localhost:8080/invocations \
-H "Content-Type: text/plain" \
-H "X-Amzn-Bedrock-AgentCore-Runtime-Session-Id: $SESSION_ID" \
-d 'Calculate the budget for a corporate event with venue, catering, and entertainment'

The front end starts the run and waits. Diagrid sees the pending run, starts an AgentCore session, and gives the run to its worker once it connects. The answer has the same shape as in the quickstart. The first answer takes longer than a later one, because a session has to start.

7. Watch the worker start and stop​

Follow the worker's logs in CloudWatch. The log group is named after the Runtime and its endpoint:

aws logs tail "/aws/bedrock-agentcore/runtimes/${RUNTIME_ARN##*/}-DEFAULT" --region "$AWS_REGION" --since 30m --follow

When Diagrid starts a worker, the logs show the worker connecting to Diagrid with Successfully connected to … Waiting for work items..., followed by Diagrid's start request, "POST /invocations HTTP/1.1" 200 OK. When Diagrid stops the worker, the logs end with Worker shutdown completed and Finished server process.

The run is a workflow under the budget-planner ID, as in the quickstart's inspection step, and its steps ran in the AgentCore session.

Leave the agent idle for longer than the cooldown. Diagrid stops the session. In CloudWatch, the ActiveSessionCount metric in the AWS/Bedrock-AgentCore namespace drops back, and has no data while no session runs.

8. Simulate a crash​

Stop the worker's AgentCore session in the middle of a run. Diagrid sees the agent's pending work and no connected worker, starts a new session, and the run continues from its last completed step. The front end's request waits through the crash and gets the answer.

Make the runs longer​

The quickstart's agent finishes a run in a few seconds, too fast to interrupt. Its main.py has a slow tool for this, check_vendor_availability, which is off unless LONG_RUN_SECONDS is set. Deploy the stack again with LongRunSeconds set to 30, so the workers check each item's vendor for 30 seconds. The image doesn't change, and the front end doesn't need the setting:

aws cloudformation deploy --region "$AWS_REGION" --stack-name agentcore-quickstart-budget-planner \
--template-file template.yaml --capabilities CAPABILITY_NAMED_IAM \
--parameter-overrides LongRunSeconds=30

A worker that is already running keeps the settings it started with, and takes the next run. Leave the agent idle for longer than the cooldown, or stop that worker's session as shown below, before you continue.

Start a long run​

Send a task with a new session ID, as in step 6:

export SESSION_ID="crash-demo-$(uuidgen)"
curl -X POST http://localhost:8080/invocations \
-H "Content-Type: text/plain" \
-H "X-Amzn-Bedrock-AgentCore-Runtime-Session-Id: $SESSION_ID" \
-d 'Calculate the budget for a corporate event with venue, catering, and entertainment, and check vendor availability'

The run takes about two minutes, and the request waits for its answer. Leave it running.

Stop the worker's session​

Watch the logs from step 7. When they show check_vendor_availability(venue): done and then check_vendor_availability(catering): started, stop the worker's session from another terminal, in the budget-planner folder with the same variables set.

Diagrid starts worker sessions with session IDs of its own, not the SESSION_ID your request sent. Each session writes to a log stream named runtime-logs-<session ID>, so the newest such stream names the worker's session:

WORKER_SESSION="$(aws logs describe-log-streams --region "$AWS_REGION" \
--log-group-name "/aws/bedrock-agentcore/runtimes/${RUNTIME_ARN##*/}-DEFAULT" \
--order-by LastEventTime --descending --limit 5 \
--query "logStreams[?starts_with(logStreamName,'runtime-logs-')] | [0].logStreamName" \
--output text | sed 's/^runtime-logs-//')"
echo "$WORKER_SESSION"
aws bedrock-agentcore stop-runtime-session --region "$AWS_REGION" \
--agent-runtime-arn "$RUNTIME_ARN" --runtime-session-id "$WORKER_SESSION"

Watch the run recover​

  • The old worker disconnects. Its log stream shows Disconnected from … at once. Its container can still finish the tool call it was running before AgentCore ends it. Diagrid discards that result.
  • Diagrid starts a new worker. The agent still has work and no connected worker, so Diagrid starts a session, within seconds to half a minute. A new runtime-logs-… stream shows Successfully connected to … Waiting for work items..., then check_vendor_availability(catering): started at once. The venue check isn't repeated.
  • The request gets its answer. The front end's request returns COMPLETED, with the budget and the availability of all three vendors. Nothing retried it.

Print the run's history:

diagrid workflow get "$SESSION_ID" --id budget-planner --project agentcore-quickstart

Every step has one TaskCompleted event. The steps that completed before the crash, the model calls, calculate_budget and the venue check, ran once. Their results came from the run's history. The catering check was interrupted, so it ran again from its start on the new worker: its TaskScheduled and TaskCompleted events are before and after the crash. Activities run at least once, so a tool with side effects must be safe to run twice. See Durable execution.

To turn long runs off again, deploy the stack with LongRunSeconds=0.

Pin a code version​

Every update of the Runtime creates a new version, and the DEFAULT endpoint moves to it. With DEFAULT, every new worker runs the newest version, and workers already running keep the version they started with.

To pin a version, create a named endpoint of the Runtime that points at that version, and set it on the agent:

diagrid agent update budget-planner --project agentcore-quickstart --compute-agentcore-endpoint-name <endpoint-name>

Changing the endpoint name replaces the running workers. Moving a named endpoint to another version doesn't: set the endpoint name again to replace them. --compute-agentcore-endpoint-name DEFAULT goes back to the newest version.

Troubleshooting​

SymptomCause and fix
diagrid agent update fails with Region "<region>" does not support serverless computeA region of the project doesn't support serverless compute, for example because it runs an older version or has serverless compute turned off.
The worker doesn't start, and the agent's runs stay pendingDiagrid stops starting workers after several consecutive failed starts. After you fix the cause, change any compute setting with diagrid agent update to start workers again.
Starts fail with AccessDeniedException on InvokeAgentRuntimeThe role may not invoke that Runtime. AWS gives the same error when the Runtime ARN names a Runtime that doesn't exist. Compare the Runtime ARN with the Resource of the role's policy: aws iam get-role-policy --role-name diagrid-budget-planner-invoker --policy-name start-stop-agentcore-sessions.
Deploying invoker.yaml fails with AWS::EarlyValidation::ResourceExistenceCheckA role named diagrid-budget-planner-invoker already exists in the AWS account, created for another agent named budget-planner. IAM role names are unique in an account across all regions. Delete that role if nothing uses it, or change RoleName in invoker.yaml. The next steps read the role's ARN from the stack's outputs.
Starts fail with IDPCommunicationErrorAWS STS can't reach the region's OIDC issuer.
Starts fail with Received error (500) from runtimeThe container's /invocations failed. Read the worker's logs in CloudWatch.

Clean up​

Detach the serverless compute from the agent. Workers already running are stopped:

diagrid agent update budget-planner --project agentcore-quickstart --remove-compute

Delete the stack. This deletes the role, its policy and the OIDC provider:

aws cloudformation delete-stack --region "$AWS_REGION" --stack-name diagrid-budget-planner-invoker
aws cloudformation wait stack-delete-complete --region "$AWS_REGION" --stack-name diagrid-budget-planner-invoker

Stop the front end with Ctrl+C. Delete the hosted agent's stack, which deletes the Runtime and the execution role, its secret, the image repository and the Diagrid project:

aws cloudformation delete-stack --region "$AWS_REGION" --stack-name agentcore-quickstart-budget-planner
aws cloudformation wait stack-delete-complete --region "$AWS_REGION" --stack-name agentcore-quickstart-budget-planner
aws secretsmanager delete-secret --region "$AWS_REGION" --secret-id "$AGENT_SECRET_ARN" --force-delete-without-recovery
aws ecr delete-repository --repository-name agentcore-quickstart-budget-planner --region "$AWS_REGION" --force
diagrid project delete agentcore-quickstart

Next steps​

Was this page helpful?